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
554 ID.AddInteger(scConstant);
555 ID.AddPointer(V);
556 void *IP = nullptr;
557 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
558 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
559 UniqueSCEVs.InsertNode(S, IP);
560 S->computeAndSetCanonical(*this);
561 return S;
562}
563
565 return getConstant(ConstantInt::get(getContext(), Val));
566}
567
568const SCEV *
571 // TODO: Avoid implicit trunc?
572 // See https://github.com/llvm/llvm-project/issues/112510.
573 return getConstant(
574 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
575}
576
579 ID.AddInteger(scVScale);
580 ID.AddPointer(Ty);
581 void *IP = nullptr;
582 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
583 return S;
584 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
585 UniqueSCEVs.InsertNode(S, IP);
586 S->computeAndSetCanonical(*this);
587 return S;
588}
589
591 SCEV::NoWrapFlags Flags) {
592 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
593 if (EC.isScalable())
594 Res = getMulExpr(Res, getVScale(Ty), Flags);
595 return Res;
596}
597
601
602SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
603 const SCEV *Op, Type *ITy)
604 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
605 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
606 "Must be a non-bit-width-changing pointer-to-integer cast!");
607}
608
609SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, SCEVUse Op,
610 Type *ITy)
611 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
612 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
613 "Must be a non-bit-width-changing pointer-to-integer cast!");
614}
615
620
621SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
622 Type *ty)
624 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
625 "Cannot truncate non-integer value!");
626}
627
628SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
629 Type *ty)
631 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
632 "Cannot zero extend non-integer value!");
633}
634
635SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
636 Type *ty)
638 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
639 "Cannot sign extend non-integer value!");
640}
641
643 // Clear this SCEVUnknown from various maps.
644 SE->forgetMemoizedResults({this});
645
646 // Remove this SCEVUnknown from the uniquing map.
647 SE->UniqueSCEVs.RemoveNode(this);
648
649 // Release the value.
650 setValPtr(nullptr);
651}
652
653void SCEVUnknown::allUsesReplacedWith(Value *New) {
654 // Clear this SCEVUnknown from various maps.
655 SE->forgetMemoizedResults({this});
656
657 // Remove this SCEVUnknown from the uniquing map.
658 SE->UniqueSCEVs.RemoveNode(this);
659
660 // Replace the value pointer in case someone is still using this SCEVUnknown.
661 setValPtr(New);
662}
663
664//===----------------------------------------------------------------------===//
665// SCEV Utilities
666//===----------------------------------------------------------------------===//
667
668/// Compare the two values \p LV and \p RV in terms of their "complexity" where
669/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
670/// operands in SCEV expressions.
671static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
672 Value *RV, unsigned Depth) {
674 return 0;
675
676 // Order pointer values after integer values. This helps SCEVExpander form
677 // GEPs.
678 bool LIsPointer = LV->getType()->isPointerTy(),
679 RIsPointer = RV->getType()->isPointerTy();
680 if (LIsPointer != RIsPointer)
681 return (int)LIsPointer - (int)RIsPointer;
682
683 // Compare getValueID values.
684 unsigned LID = LV->getValueID(), RID = RV->getValueID();
685 if (LID != RID)
686 return (int)LID - (int)RID;
687
688 // Sort arguments by their position.
689 if (const auto *LA = dyn_cast<Argument>(LV)) {
690 const auto *RA = cast<Argument>(RV);
691 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
692 return (int)LArgNo - (int)RArgNo;
693 }
694
695 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
696 const auto *RGV = cast<GlobalValue>(RV);
697
698 if (auto L = LGV->getLinkage() - RGV->getLinkage())
699 return L;
700
701 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
702 auto LT = GV->getLinkage();
703 return !(GlobalValue::isPrivateLinkage(LT) ||
705 };
706
707 // Use the names to distinguish the two values, but only if the
708 // names are semantically important.
709 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
710 return LGV->getName().compare(RGV->getName());
711 }
712
713 // For instructions, compare their loop depth, and their operand count. This
714 // is pretty loose.
715 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
716 const auto *RInst = cast<Instruction>(RV);
717
718 // Compare loop depths.
719 const BasicBlock *LParent = LInst->getParent(),
720 *RParent = RInst->getParent();
721 if (LParent != RParent) {
722 unsigned LDepth = LI->getLoopDepth(LParent),
723 RDepth = LI->getLoopDepth(RParent);
724 if (LDepth != RDepth)
725 return (int)LDepth - (int)RDepth;
726 }
727
728 // Compare the number of operands.
729 unsigned LNumOps = LInst->getNumOperands(),
730 RNumOps = RInst->getNumOperands();
731 if (LNumOps != RNumOps)
732 return (int)LNumOps - (int)RNumOps;
733
734 for (unsigned Idx : seq(LNumOps)) {
735 int Result = CompareValueComplexity(LI, LInst->getOperand(Idx),
736 RInst->getOperand(Idx), Depth + 1);
737 if (Result != 0)
738 return Result;
739 }
740 }
741
742 return 0;
743}
744
745// Return negative, zero, or positive, if LHS is less than, equal to, or greater
746// than RHS, respectively. A three-way result allows recursive comparisons to be
747// more efficient.
748// If the max analysis depth was reached, return std::nullopt, assuming we do
749// not know if they are equivalent for sure.
750static std::optional<int>
751CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS,
752 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
753 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
754 if (LHS == RHS)
755 return 0;
756
757 // Primarily, sort the SCEVs by their getSCEVType().
758 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
759 if (LType != RType)
760 return (int)LType - (int)RType;
761
763 return std::nullopt;
764
765 // Aside from the getSCEVType() ordering, the particular ordering
766 // isn't very important except that it's beneficial to be consistent,
767 // so that (a + b) and (b + a) don't end up as different expressions.
768 switch (LType) {
769 case scUnknown: {
770 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
771 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
772
773 int X =
774 CompareValueComplexity(LI, LU->getValue(), RU->getValue(), Depth + 1);
775 return X;
776 }
777
778 case scConstant: {
781
782 // Compare constant values.
783 const APInt &LA = LC->getAPInt();
784 const APInt &RA = RC->getAPInt();
785 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
786 if (LBitWidth != RBitWidth)
787 return (int)LBitWidth - (int)RBitWidth;
788 return LA.ult(RA) ? -1 : 1;
789 }
790
791 case scVScale: {
792 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
793 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
794 return LTy->getBitWidth() - RTy->getBitWidth();
795 }
796
797 case scAddRecExpr: {
800
801 // There is always a dominance between two recs that are used by one SCEV,
802 // so we can safely sort recs by loop header dominance. We require such
803 // order in getAddExpr.
804 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
805 if (LLoop != RLoop) {
806 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
807 assert(LHead != RHead && "Two loops share the same header?");
808 if (DT.dominates(LHead, RHead))
809 return 1;
810 assert(DT.dominates(RHead, LHead) &&
811 "No dominance between recurrences used by one SCEV?");
812 return -1;
813 }
814
815 [[fallthrough]];
816 }
817
818 case scTruncate:
819 case scZeroExtend:
820 case scSignExtend:
821 case scPtrToAddr:
822 case scPtrToInt:
823 case scAddExpr:
824 case scMulExpr:
825 case scUDivExpr:
826 case scSMaxExpr:
827 case scUMaxExpr:
828 case scSMinExpr:
829 case scUMinExpr:
831 ArrayRef<SCEVUse> LOps = LHS->operands();
832 ArrayRef<SCEVUse> ROps = RHS->operands();
833
834 // Lexicographically compare n-ary-like expressions.
835 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
836 if (LNumOps != RNumOps)
837 return (int)LNumOps - (int)RNumOps;
838
839 for (unsigned i = 0; i != LNumOps; ++i) {
840 auto X = CompareSCEVComplexity(LI, LOps[i].getPointer(),
841 ROps[i].getPointer(), DT, Depth + 1);
842 if (X != 0)
843 return X;
844 }
845 return 0;
846 }
847
849 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
850 }
851 llvm_unreachable("Unknown SCEV kind!");
852}
853
854/// Given a list of SCEV objects, order them by their complexity, and group
855/// objects of the same complexity together by value. When this routine is
856/// finished, we know that any duplicates in the vector are consecutive and that
857/// complexity is monotonically increasing.
858///
859/// Note that we go take special precautions to ensure that we get deterministic
860/// results from this routine. In other words, we don't want the results of
861/// this to depend on where the addresses of various SCEV objects happened to
862/// land in memory.
864 DominatorTree &DT) {
865 if (Ops.size() < 2) return; // Noop
866
867 // Whether LHS has provably less complexity than RHS.
868 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
869 auto Complexity = CompareSCEVComplexity(LI, LHS, RHS, DT);
870 return Complexity && *Complexity < 0;
871 };
872 if (Ops.size() == 2) {
873 // This is the common case, which also happens to be trivially simple.
874 // Special case it.
875 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
876 if (IsLessComplex(RHS, LHS))
877 std::swap(LHS, RHS);
878 return;
879 }
880
881 // Do the rough sort by complexity.
883 Ops, [&](SCEVUse LHS, SCEVUse RHS) { return IsLessComplex(LHS, RHS); });
884
885 // Now that we are sorted by complexity, group elements of the same
886 // complexity. Note that this is, at worst, N^2, but the vector is likely to
887 // be extremely short in practice. Note that we take this approach because we
888 // do not want to depend on the addresses of the objects we are grouping.
889 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
890 const SCEV *S = Ops[i];
891 unsigned Complexity = S->getSCEVType();
892
893 // If there are any objects of the same complexity and same value as this
894 // one, group them.
895 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
896 if (Ops[j] == S) { // Found a duplicate.
897 // Move it to immediately after i'th element.
898 std::swap(Ops[i+1], Ops[j]);
899 ++i; // no need to rescan it.
900 if (i == e-2) return; // Done!
901 }
902 }
903 }
904}
905
906/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
907/// least HugeExprThreshold nodes).
909 return any_of(Ops, [](const SCEV *S) {
911 });
912}
913
914/// Performs a number of common optimizations on the passed \p Ops. If the
915/// whole expression reduces down to a single operand, it will be returned.
916///
917/// The following optimizations are performed:
918/// * Fold constants using the \p Fold function.
919/// * Remove identity constants satisfying \p IsIdentity.
920/// * If a constant satisfies \p IsAbsorber, return it.
921/// * Sort operands by complexity.
922template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
923static const SCEV *
925 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
926 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
927 const SCEVConstant *Folded = nullptr;
928 for (unsigned Idx = 0; Idx < Ops.size();) {
929 const SCEV *Op = Ops[Idx];
930 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
931 if (!Folded)
932 Folded = C;
933 else
934 Folded = cast<SCEVConstant>(
935 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
936 Ops.erase(Ops.begin() + Idx);
937 continue;
938 }
939 ++Idx;
940 }
941
942 if (Ops.empty()) {
943 assert(Folded && "Must have folded value");
944 return Folded;
945 }
946
947 if (Folded && IsAbsorber(Folded->getAPInt()))
948 return Folded;
949
950 GroupByComplexity(Ops, &LI, DT);
951 if (Folded && !IsIdentity(Folded->getAPInt()))
952 Ops.insert(Ops.begin(), Folded);
953
954 return Ops.size() == 1 ? Ops[0] : nullptr;
955}
956
957//===----------------------------------------------------------------------===//
958// Simple SCEV method implementations
959//===----------------------------------------------------------------------===//
960
961/// Compute BC(It, K). The result has width W. Assume, K > 0.
962static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
963 ScalarEvolution &SE,
964 Type *ResultTy) {
965 // Handle the simplest case efficiently.
966 if (K == 1)
967 return SE.getTruncateOrZeroExtend(It, ResultTy);
968
969 // We are using the following formula for BC(It, K):
970 //
971 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
972 //
973 // Suppose, W is the bitwidth of the return value. We must be prepared for
974 // overflow. Hence, we must assure that the result of our computation is
975 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
976 // safe in modular arithmetic.
977 //
978 // However, this code doesn't use exactly that formula; the formula it uses
979 // is something like the following, where T is the number of factors of 2 in
980 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
981 // exponentiation:
982 //
983 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
984 //
985 // This formula is trivially equivalent to the previous formula. However,
986 // this formula can be implemented much more efficiently. The trick is that
987 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
988 // arithmetic. To do exact division in modular arithmetic, all we have
989 // to do is multiply by the inverse. Therefore, this step can be done at
990 // width W.
991 //
992 // The next issue is how to safely do the division by 2^T. The way this
993 // is done is by doing the multiplication step at a width of at least W + T
994 // bits. This way, the bottom W+T bits of the product are accurate. Then,
995 // when we perform the division by 2^T (which is equivalent to a right shift
996 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
997 // truncated out after the division by 2^T.
998 //
999 // In comparison to just directly using the first formula, this technique
1000 // is much more efficient; using the first formula requires W * K bits,
1001 // but this formula less than W + K bits. Also, the first formula requires
1002 // a division step, whereas this formula only requires multiplies and shifts.
1003 //
1004 // It doesn't matter whether the subtraction step is done in the calculation
1005 // width or the input iteration count's width; if the subtraction overflows,
1006 // the result must be zero anyway. We prefer here to do it in the width of
1007 // the induction variable because it helps a lot for certain cases; CodeGen
1008 // isn't smart enough to ignore the overflow, which leads to much less
1009 // efficient code if the width of the subtraction is wider than the native
1010 // register width.
1011 //
1012 // (It's possible to not widen at all by pulling out factors of 2 before
1013 // the multiplication; for example, K=2 can be calculated as
1014 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1015 // extra arithmetic, so it's not an obvious win, and it gets
1016 // much more complicated for K > 3.)
1017
1018 // Protection from insane SCEVs; this bound is conservative,
1019 // but it probably doesn't matter.
1020 if (K > 1000)
1021 return SE.getCouldNotCompute();
1022
1023 unsigned W = SE.getTypeSizeInBits(ResultTy);
1024
1025 // Calculate K! / 2^T and T; we divide out the factors of two before
1026 // multiplying for calculating K! / 2^T to avoid overflow.
1027 // Other overflow doesn't matter because we only care about the bottom
1028 // W bits of the result.
1029 APInt OddFactorial(W, 1);
1030 unsigned T = 1;
1031 for (unsigned i = 3; i <= K; ++i) {
1032 unsigned TwoFactors = countr_zero(i);
1033 T += TwoFactors;
1034 OddFactorial *= (i >> TwoFactors);
1035 }
1036
1037 // We need at least W + T bits for the multiplication step
1038 unsigned CalculationBits = W + T;
1039
1040 // Calculate 2^T, at width T+W.
1041 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1042
1043 // Calculate the multiplicative inverse of K! / 2^T;
1044 // this multiplication factor will perform the exact division by
1045 // K! / 2^T.
1046 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
1047
1048 // Calculate the product, at width T+W
1049 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1050 CalculationBits);
1051 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1052 for (unsigned i = 1; i != K; ++i) {
1053 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1054 Dividend = SE.getMulExpr(Dividend,
1055 SE.getTruncateOrZeroExtend(S, CalculationTy));
1056 }
1057
1058 // Divide by 2^T
1059 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1060
1061 // Truncate the result, and divide by K! / 2^T.
1062
1063 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1064 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1065}
1066
1067/// Return the value of this chain of recurrences at the specified iteration
1068/// number. We can evaluate this recurrence by multiplying each element in the
1069/// chain by the binomial coefficient corresponding to it. In other words, we
1070/// can evaluate {A,+,B,+,C,+,D} as:
1071///
1072/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1073///
1074/// where BC(It, k) stands for binomial coefficient.
1076 ScalarEvolution &SE) const {
1077 return evaluateAtIteration(operands(), It, SE);
1078}
1079
1081 const SCEV *It,
1082 ScalarEvolution &SE) {
1083 assert(Operands.size() > 0);
1084 const SCEV *Result = Operands[0].getPointer();
1085 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1086 // The computation is correct in the face of overflow provided that the
1087 // multiplication is performed _after_ the evaluation of the binomial
1088 // coefficient.
1089 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1090 if (isa<SCEVCouldNotCompute>(Coeff))
1091 return Coeff;
1092
1093 Result =
1094 SE.getAddExpr(Result, SE.getMulExpr(Operands[i].getPointer(), Coeff));
1095 }
1096 return Result;
1097}
1098
1099//===----------------------------------------------------------------------===//
1100// SCEV Expression folder implementations
1101//===----------------------------------------------------------------------===//
1102
1103/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
1104/// which computes a pointer-typed value, and rewrites the whole expression
1105/// tree so that *all* the computations are done on integers, and the only
1106/// pointer-typed operands in the expression are SCEVUnknown.
1107/// The CreatePtrCast callback is invoked to create the actual conversion
1108/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
1110 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1112 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1113 Type *TargetTy;
1114 ConversionFn CreatePtrCast;
1115
1116public:
1118 ConversionFn CreatePtrCast)
1119 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1120
1121 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1122 Type *TargetTy, ConversionFn CreatePtrCast) {
1123 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1124 return Rewriter.visit(Scev);
1125 }
1126
1127 const SCEV *visit(const SCEV *S) {
1128 Type *STy = S->getType();
1129 // If the expression is not pointer-typed, just keep it as-is.
1130 if (!STy->isPointerTy())
1131 return S;
1132 // Else, recursively sink the cast down into it.
1133 return Base::visit(S);
1134 }
1135
1136 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1137 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1138 // implementation drops.
1139 SmallVector<SCEVUse, 2> Operands;
1140 bool Changed = false;
1141 for (SCEVUse Op : Expr->operands()) {
1142 Operands.push_back(visit(Op.getPointer()));
1143 Changed |= Op.getPointer() != Operands.back();
1144 }
1145 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1146 }
1147
1148 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1149 SmallVector<SCEVUse, 2> Operands;
1150 bool Changed = false;
1151 for (SCEVUse Op : Expr->operands()) {
1152 Operands.push_back(visit(Op.getPointer()));
1153 Changed |= Op.getPointer() != Operands.back();
1154 }
1155 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1156 }
1157
1158 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1159 assert(Expr->getType()->isPointerTy() &&
1160 "Should only reach pointer-typed SCEVUnknown's.");
1161 // Perform some basic constant folding. If the operand of the cast is a
1162 // null pointer, don't create a cast SCEV expression (that will be left
1163 // as-is), but produce a zero constant.
1165 return SE.getZero(TargetTy);
1166 return CreatePtrCast(Expr);
1167 }
1168};
1169
1171 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1172
1173 // It isn't legal for optimizations to construct new ptrtoint expressions
1174 // for non-integral pointers.
1175 if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1176 return getCouldNotCompute();
1177
1178 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1179
1180 // We can only trivially model ptrtoint if SCEV's effective (integer) type
1181 // is sufficiently wide to represent all possible pointer values.
1182 // We could theoretically teach SCEV to truncate wider pointers, but
1183 // that isn't implemented for now.
1186 return getCouldNotCompute();
1187
1188 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1190 Op, *this, IntPtrTy, [this, IntPtrTy](const SCEVUnknown *U) {
1192 ID.AddInteger(scPtrToInt);
1193 ID.AddPointer(U);
1194 void *IP = nullptr;
1195 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1196 return S;
1197 SCEV *S = new (SCEVAllocator)
1198 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), U, IntPtrTy);
1199 UniqueSCEVs.InsertNode(S, IP);
1200 S->computeAndSetCanonical(*this);
1201 registerUser(S, U);
1202 return static_cast<const SCEV *>(S);
1203 });
1204 assert(IntOp->getType()->isIntegerTy() &&
1205 "We must have succeeded in sinking the cast, "
1206 "and ending up with an integer-typed expression!");
1207 return IntOp;
1208}
1209
1211 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1212
1213 // Treat pointers with unstable representation conservatively, since the
1214 // address bits may change.
1215 if (DL.hasUnstableRepresentation(Op->getType()))
1216 return getCouldNotCompute();
1217
1218 Type *Ty = DL.getAddressType(Op->getType());
1219
1220 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1221 // The rewriter handles null pointer constant folding.
1223 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1225 ID.AddInteger(scPtrToAddr);
1226 ID.AddPointer(U);
1227 ID.AddPointer(Ty);
1228 void *IP = nullptr;
1229 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1230 return S;
1231 SCEV *S = new (SCEVAllocator)
1232 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1233 UniqueSCEVs.InsertNode(S, IP);
1234 S->computeAndSetCanonical(*this);
1235 registerUser(S, U);
1236 return static_cast<const SCEV *>(S);
1237 });
1238 assert(IntOp->getType()->isIntegerTy() &&
1239 "We must have succeeded in sinking the cast, "
1240 "and ending up with an integer-typed expression!");
1241 return IntOp;
1242}
1243
1245 assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1246
1247 const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1248 if (isa<SCEVCouldNotCompute>(IntOp))
1249 return IntOp;
1250
1251 return getTruncateOrZeroExtend(IntOp, Ty);
1252}
1253
1255 unsigned Depth) {
1256 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1257 "This is not a truncating conversion!");
1258 assert(isSCEVable(Ty) &&
1259 "This is not a conversion to a SCEVable type!");
1260 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1261 Ty = getEffectiveSCEVType(Ty);
1262
1264 ID.AddInteger(scTruncate);
1265 ID.AddPointer(Op);
1266 ID.AddPointer(Ty);
1267 void *IP = nullptr;
1268 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1269
1270 // Fold if the operand is constant.
1271 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1272 return getConstant(
1273 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1274
1275 // trunc(trunc(x)) --> trunc(x)
1277 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1278
1279 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1281 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1282
1283 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1285 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1286
1287 if (Depth > MaxCastDepth) {
1288 SCEV *S =
1289 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1290 UniqueSCEVs.InsertNode(S, IP);
1291 S->computeAndSetCanonical(*this);
1292 registerUser(S, Op);
1293 return S;
1294 }
1295
1296 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1297 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1298 // if after transforming we have at most one truncate, not counting truncates
1299 // that replace other casts.
1301 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1302 SmallVector<SCEVUse, 4> Operands;
1303 unsigned numTruncs = 0;
1304 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1305 ++i) {
1306 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1307 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1309 numTruncs++;
1310 Operands.push_back(S);
1311 }
1312 if (numTruncs < 2) {
1313 if (isa<SCEVAddExpr>(Op))
1314 return getAddExpr(Operands);
1315 if (isa<SCEVMulExpr>(Op))
1316 return getMulExpr(Operands);
1317 llvm_unreachable("Unexpected SCEV type for Op.");
1318 }
1319 // Although we checked in the beginning that ID is not in the cache, it is
1320 // possible that during recursion and different modification ID was inserted
1321 // into the cache. So if we find it, just return it.
1322 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1323 return S;
1324 }
1325
1326 // If the input value is a chrec scev, truncate the chrec's operands.
1327 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1328 SmallVector<SCEVUse, 4> Operands;
1329 for (const SCEV *Op : AddRec->operands())
1330 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1331 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1332 }
1333
1334 // Return zero if truncating to known zeros.
1335 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1336 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1337 return getZero(Ty);
1338
1339 // The cast wasn't folded; create an explicit cast node. We can reuse
1340 // the existing insert position since if we get here, we won't have
1341 // made any changes which would invalidate it.
1342 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1343 Op, Ty);
1344 UniqueSCEVs.InsertNode(S, IP);
1345 S->computeAndSetCanonical(*this);
1346 registerUser(S, Op);
1347 return S;
1348}
1349
1350// Get the limit of a recurrence such that incrementing by Step cannot cause
1351// signed overflow as long as the value of the recurrence within the
1352// loop does not exceed this limit before incrementing.
1353static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1354 ICmpInst::Predicate *Pred,
1355 ScalarEvolution *SE) {
1356 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1357 if (SE->isKnownPositive(Step)) {
1358 *Pred = ICmpInst::ICMP_SLT;
1360 SE->getSignedRangeMax(Step));
1361 }
1362 if (SE->isKnownNegative(Step)) {
1363 *Pred = ICmpInst::ICMP_SGT;
1365 SE->getSignedRangeMin(Step));
1366 }
1367 return nullptr;
1368}
1369
1370// Get the limit of a recurrence such that incrementing by Step cannot cause
1371// unsigned overflow as long as the value of the recurrence within the loop does
1372// not exceed this limit before incrementing.
1374 ICmpInst::Predicate *Pred,
1375 ScalarEvolution *SE) {
1376 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1377 *Pred = ICmpInst::ICMP_ULT;
1378
1380 SE->getUnsignedRangeMax(Step));
1381}
1382
1383namespace {
1384
1385struct ExtendOpTraitsBase {
1386 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1387 unsigned);
1388};
1389
1390// Used to make code generic over signed and unsigned overflow.
1391template <typename ExtendOp> struct ExtendOpTraits {
1392 // Members present:
1393 //
1394 // static const SCEV::NoWrapFlags WrapType;
1395 //
1396 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1397 //
1398 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1399 // ICmpInst::Predicate *Pred,
1400 // ScalarEvolution *SE);
1401};
1402
1403template <>
1404struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1405 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1406
1407 static const GetExtendExprTy GetExtendExpr;
1408
1409 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1410 ICmpInst::Predicate *Pred,
1411 ScalarEvolution *SE) {
1412 return getSignedOverflowLimitForStep(Step, Pred, SE);
1413 }
1414};
1415
1416const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1418
1419template <>
1420struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1421 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1422
1423 static const GetExtendExprTy GetExtendExpr;
1424
1425 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1426 ICmpInst::Predicate *Pred,
1427 ScalarEvolution *SE) {
1428 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1429 }
1430};
1431
1432const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1434
1435} // end anonymous namespace
1436
1437// The recurrence AR has been shown to have no signed/unsigned wrap or something
1438// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1439// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1440// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1441// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1442// expression "Step + sext/zext(PreIncAR)" is congruent with
1443// "sext/zext(PostIncAR)"
1444template <typename ExtendOpTy>
1445static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1446 ScalarEvolution *SE, unsigned Depth) {
1447 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1448 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1449
1450 const Loop *L = AR->getLoop();
1451 const SCEV *Start = AR->getStart();
1452 const SCEV *Step = AR->getStepRecurrence(*SE);
1453
1454 // Check for a simple looking step prior to loop entry.
1455 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1456 if (!SA)
1457 return nullptr;
1458
1459 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1460 // subtraction is expensive. For this purpose, perform a quick and dirty
1461 // difference, by checking for Step in the operand list. Note, that
1462 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1463 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1464 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1465 if (*It == Step) {
1466 DiffOps.erase(It);
1467 break;
1468 }
1469
1470 if (DiffOps.size() == SA->getNumOperands())
1471 return nullptr;
1472
1473 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1474 // `Step`:
1475
1476 // 1. NSW/NUW flags on the step increment.
1477 auto PreStartFlags =
1479 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1481 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1482
1483 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1484 // "S+X does not sign/unsign-overflow".
1485 //
1486
1487 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1488 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1489 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1490 return PreStart;
1491
1492 // 2. Direct overflow check on the step operation's expression.
1493 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1494 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1495 const SCEV *OperandExtendedStart =
1496 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1497 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1498 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1499 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1500 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1501 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1502 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1503 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1504 }
1505 return PreStart;
1506 }
1507
1508 // 3. Loop precondition.
1510 const SCEV *OverflowLimit =
1511 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1512
1513 if (OverflowLimit &&
1514 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1515 return PreStart;
1516
1517 return nullptr;
1518}
1519
1520// Get the normalized zero or sign extended expression for this AddRec's Start.
1521template <typename ExtendOpTy>
1522static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1523 ScalarEvolution *SE,
1524 unsigned Depth) {
1525 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1526
1527 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1528 if (!PreStart)
1529 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1530
1531 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1532 Depth),
1533 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1534}
1535
1536// Try to prove away overflow by looking at "nearby" add recurrences. A
1537// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1538// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1539//
1540// Formally:
1541//
1542// {S,+,X} == {S-T,+,X} + T
1543// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1544//
1545// If ({S-T,+,X} + T) does not overflow ... (1)
1546//
1547// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1548//
1549// If {S-T,+,X} does not overflow ... (2)
1550//
1551// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1552// == {Ext(S-T)+Ext(T),+,Ext(X)}
1553//
1554// If (S-T)+T does not overflow ... (3)
1555//
1556// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1557// == {Ext(S),+,Ext(X)} == LHS
1558//
1559// Thus, if (1), (2) and (3) are true for some T, then
1560// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1561//
1562// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1563// does not overflow" restricted to the 0th iteration. Therefore we only need
1564// to check for (1) and (2).
1565//
1566// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1567// is `Delta` (defined below).
1568template <typename ExtendOpTy>
1569bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1570 const SCEV *Step,
1571 const Loop *L) {
1572 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1573
1574 // We restrict `Start` to a constant to prevent SCEV from spending too much
1575 // time here. It is correct (but more expensive) to continue with a
1576 // non-constant `Start` and do a general SCEV subtraction to compute
1577 // `PreStart` below.
1578 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1579 if (!StartC)
1580 return false;
1581
1582 APInt StartAI = StartC->getAPInt();
1583
1584 for (unsigned Delta : {-2, -1, 1, 2}) {
1585 const SCEV *PreStart = getConstant(StartAI - Delta);
1586
1587 FoldingSetNodeID ID;
1588 ID.AddInteger(scAddRecExpr);
1589 ID.AddPointer(PreStart);
1590 ID.AddPointer(Step);
1591 ID.AddPointer(L);
1592 void *IP = nullptr;
1593 const auto *PreAR =
1594 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1595
1596 // Give up if we don't already have the add recurrence we need because
1597 // actually constructing an add recurrence is relatively expensive.
1598 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1599 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1601 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1602 DeltaS, &Pred, this);
1603 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1604 return true;
1605 }
1606 }
1607
1608 return false;
1609}
1610
1611// Finds an integer D for an expression (C + x + y + ...) such that the top
1612// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1613// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1614// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1615// the (C + x + y + ...) expression is \p WholeAddExpr.
1617 const SCEVConstant *ConstantTerm,
1618 const SCEVAddExpr *WholeAddExpr) {
1619 const APInt &C = ConstantTerm->getAPInt();
1620 const unsigned BitWidth = C.getBitWidth();
1621 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1622 uint32_t TZ = BitWidth;
1623 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1624 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1625 if (TZ) {
1626 // Set D to be as many least significant bits of C as possible while still
1627 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1628 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1629 }
1630 return APInt(BitWidth, 0);
1631}
1632
1633// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1634// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1635// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1636// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1638 const APInt &ConstantStart,
1639 const SCEV *Step) {
1640 const unsigned BitWidth = ConstantStart.getBitWidth();
1641 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1642 if (TZ)
1643 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1644 : ConstantStart;
1645 return APInt(BitWidth, 0);
1646}
1647
1649 const ScalarEvolution::FoldID &ID, const SCEV *S,
1652 &FoldCacheUser) {
1653 auto I = FoldCache.insert({ID, S});
1654 if (!I.second) {
1655 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1656 // entry.
1657 auto &UserIDs = FoldCacheUser[I.first->second];
1658 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1659 for (unsigned I = 0; I != UserIDs.size(); ++I)
1660 if (UserIDs[I] == ID) {
1661 std::swap(UserIDs[I], UserIDs.back());
1662 break;
1663 }
1664 UserIDs.pop_back();
1665 I.first->second = S;
1666 }
1667 FoldCacheUser[S].push_back(ID);
1668}
1669
1670const SCEV *
1672 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1673 "This is not an extending conversion!");
1674 assert(isSCEVable(Ty) &&
1675 "This is not a conversion to a SCEVable type!");
1676 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1677 Ty = getEffectiveSCEVType(Ty);
1678
1679 FoldID ID(scZeroExtend, Op, Ty);
1680 if (const SCEV *S = FoldCache.lookup(ID))
1681 return S;
1682
1683 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1685 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1686 return S;
1687}
1688
1690 unsigned Depth) {
1691 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1692 "This is not an extending conversion!");
1693 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1694 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1695
1696 // Fold if the operand is constant.
1697 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1698 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1699
1700 // zext(zext(x)) --> zext(x)
1702 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1703
1704 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1705 // zero-extension distributes over the recurrence.
1706 if (Depth <= MaxCastDepth)
1707 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(Op))
1708 if (AR->isAffine() && AR->hasNoUnsignedWrap()) {
1709 const SCEV *Start =
1711 const SCEV *Step =
1712 getZeroExtendExpr(AR->getStepRecurrence(*this), Ty, Depth + 1);
1713 return getAddRecExpr(Start, Step, AR->getLoop(), AR->getNoWrapFlags());
1714 }
1715
1716 // Before doing any expensive analysis, check to see if we've already
1717 // computed a SCEV for this Op and Ty.
1719 ID.AddInteger(scZeroExtend);
1720 ID.AddPointer(Op);
1721 ID.AddPointer(Ty);
1722 void *IP = nullptr;
1723 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1724 if (Depth > MaxCastDepth) {
1725 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1726 Op, Ty);
1727 UniqueSCEVs.InsertNode(S, IP);
1728 S->computeAndSetCanonical(*this);
1729 registerUser(S, Op);
1730 return S;
1731 }
1732
1733 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1735 // It's possible the bits taken off by the truncate were all zero bits. If
1736 // so, we should be able to simplify this further.
1737 const SCEV *X = ST->getOperand();
1739 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1740 unsigned NewBits = getTypeSizeInBits(Ty);
1741 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1742 CR.zextOrTrunc(NewBits)))
1743 return getTruncateOrZeroExtend(X, Ty, Depth);
1744 }
1745
1746 // If the input value is a chrec scev, and we can prove that the value
1747 // did not overflow the old, smaller, value, we can zero extend all of the
1748 // operands (often constants). This allows analysis of something like
1749 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1751 if (AR->isAffine()) {
1752 const SCEV *Start = AR->getStart();
1753 const SCEV *Step = AR->getStepRecurrence(*this);
1754 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1755 const Loop *L = AR->getLoop();
1756
1757 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1758
1759 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1760 // Note that this serves two purposes: It filters out loops that are
1761 // simply not analyzable, and it covers the case where this code is
1762 // being called from within backedge-taken count analysis, such that
1763 // attempting to ask for the backedge-taken count would likely result
1764 // in infinite recursion. In the later case, the analysis code will
1765 // cope with a conservative value, and it will take care to purge
1766 // that value once it has finished.
1767 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1768 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1769 // Manually compute the final value for AR, checking for overflow.
1770
1771 // Check whether the backedge-taken count can be losslessly casted to
1772 // the addrec's type. The count is always unsigned.
1773 const SCEV *CastedMaxBECount =
1774 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1775 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1776 CastedMaxBECount, MaxBECount->getType(), Depth);
1777 if (MaxBECount == RecastedMaxBECount) {
1778 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1779 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1780 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1782 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1784 Depth + 1),
1785 WideTy, Depth + 1);
1786 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1787 const SCEV *WideMaxBECount =
1788 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1789 const SCEV *OperandExtendedAdd =
1790 getAddExpr(WideStart,
1791 getMulExpr(WideMaxBECount,
1792 getZeroExtendExpr(Step, WideTy, Depth + 1),
1795 if (ZAdd == OperandExtendedAdd) {
1796 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1797 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1798 // Return the expression with the addrec on the outside.
1799 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1800 Depth + 1);
1801 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1802 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1803 }
1804 // Similar to above, only this time treat the step value as signed.
1805 // This covers loops that count down.
1806 OperandExtendedAdd =
1807 getAddExpr(WideStart,
1808 getMulExpr(WideMaxBECount,
1809 getSignExtendExpr(Step, WideTy, Depth + 1),
1812 if (ZAdd == OperandExtendedAdd) {
1813 // Cache knowledge of AR NW, which is propagated to this AddRec.
1814 // Negative step causes unsigned wrap, but it still can't self-wrap.
1815 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1816 // Return the expression with the addrec on the outside.
1817 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1818 Depth + 1);
1819 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1820 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1821 }
1822 }
1823 }
1824
1825 // Normally, in the cases we can prove no-overflow via a
1826 // backedge guarding condition, we can also compute a backedge
1827 // taken count for the loop. The exceptions are assumptions and
1828 // guards present in the loop -- SCEV is not great at exploiting
1829 // these to compute max backedge taken counts, but can still use
1830 // these to prove lack of overflow. Use this fact to avoid
1831 // doing extra work that may not pay off.
1832 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1833 !AC.assumptions().empty()) {
1834
1835 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1836 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1837 if (AR->hasNoUnsignedWrap()) {
1838 // Same as nuw case above - duplicated here to avoid a compile time
1839 // issue. It's not clear that the order of checks does matter, but
1840 // it's one of two issue possible causes for a change which was
1841 // reverted. Be conservative for the moment.
1842 Start =
1844 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1845 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1846 }
1847
1848 // For a negative step, we can extend the operands iff doing so only
1849 // traverses values in the range zext([0,UINT_MAX]).
1850 if (isKnownNegative(Step)) {
1852 getSignedRangeMin(Step));
1855 // Cache knowledge of AR NW, which is propagated to this
1856 // AddRec. Negative step causes unsigned wrap, but it
1857 // still can't self-wrap.
1858 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1859 // Return the expression with the addrec on the outside.
1860 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1861 Depth + 1);
1862 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1863 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1864 }
1865 }
1866 }
1867
1868 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1869 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1870 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1871 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1872 const APInt &C = SC->getAPInt();
1873 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1874 if (D != 0) {
1875 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1876 const SCEV *SResidual =
1877 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1878 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1879 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1880 Depth + 1);
1881 }
1882 }
1883
1884 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1885 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1886 Start =
1888 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1889 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1890 }
1891 }
1892
1893 // zext(A % B) --> zext(A) % zext(B)
1894 {
1895 const SCEV *LHS;
1896 const SCEV *RHS;
1897 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1898 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1899 getZeroExtendExpr(RHS, Ty, Depth + 1));
1900 }
1901
1902 // zext(A / B) --> zext(A) / zext(B).
1903 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1904 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1905 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1906
1907 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1908 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1909 if (SA->hasNoUnsignedWrap()) {
1910 // If the addition does not unsign overflow then we can, by definition,
1911 // commute the zero extension with the addition operation.
1913 for (SCEVUse Op : SA->operands())
1914 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1915 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1916 }
1917
1918 const APInt *C, *C2;
1919 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1920 // Currently the non-negative check is done manually, as isKnownNonNegative
1921 // is too expensive.
1922 if (SA->hasNoSignedWrap() &&
1924 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1925 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1926 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1927 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1928 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1929 SCEV::FlagNSW, Depth + 1);
1930 }
1931
1932 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1933 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1934 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1935 //
1936 // Often address arithmetics contain expressions like
1937 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1938 // This transformation is useful while proving that such expressions are
1939 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1940 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1941 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1942 if (D != 0) {
1943 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1944 const SCEV *SResidual =
1946 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1947 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1948 Depth + 1);
1949 }
1950 }
1951 }
1952
1953 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1954 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1955 if (SM->hasNoUnsignedWrap()) {
1956 // If the multiply does not unsign overflow then we can, by definition,
1957 // commute the zero extension with the multiply operation.
1959 for (SCEVUse Op : SM->operands())
1960 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1961 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1962 }
1963
1964 // zext(2^K * (trunc X to iN)) to iM ->
1965 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1966 //
1967 // Proof:
1968 //
1969 // zext(2^K * (trunc X to iN)) to iM
1970 // = zext((trunc X to iN) << K) to iM
1971 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1972 // (because shl removes the top K bits)
1973 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1974 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1975 //
1976 const APInt *C;
1977 const SCEV *TruncRHS;
1978 if (match(SM,
1979 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1980 C->isPowerOf2()) {
1981 int NewTruncBits =
1982 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1983 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1984 return getMulExpr(
1985 getZeroExtendExpr(SM->getOperand(0), Ty),
1986 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1987 SCEV::FlagNUW, Depth + 1);
1988 }
1989 }
1990
1991 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1992 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1995 SmallVector<SCEVUse, 4> Operands;
1996 for (SCEVUse Operand : MinMax->operands())
1997 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1999 return getUMinExpr(Operands);
2000 return getUMaxExpr(Operands);
2001 }
2002
2003 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
2005 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
2006 SmallVector<SCEVUse, 4> Operands;
2007 for (SCEVUse Operand : MinMax->operands())
2008 Operands.push_back(getZeroExtendExpr(Operand, Ty));
2009 return getUMinExpr(Operands, /*Sequential*/ true);
2010 }
2011
2012 // The cast wasn't folded; create an explicit cast node.
2013 // Recompute the insert position, as it may have been invalidated.
2014 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2015 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
2016 Op, Ty);
2017 UniqueSCEVs.InsertNode(S, IP);
2018 S->computeAndSetCanonical(*this);
2019 registerUser(S, Op);
2020 return S;
2021}
2022
2023const SCEV *
2025 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2026 "This is not an extending conversion!");
2027 assert(isSCEVable(Ty) &&
2028 "This is not a conversion to a SCEVable type!");
2029 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
2030 Ty = getEffectiveSCEVType(Ty);
2031
2032 FoldID ID(scSignExtend, Op, Ty);
2033 if (const SCEV *S = FoldCache.lookup(ID))
2034 return S;
2035
2036 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
2038 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
2039 return S;
2040}
2041
2043 unsigned Depth) {
2044 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2045 "This is not an extending conversion!");
2046 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
2047 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
2048 Ty = getEffectiveSCEVType(Ty);
2049
2050 // Fold if the operand is constant.
2051 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2052 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
2053
2054 // sext(sext(x)) --> sext(x)
2056 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
2057
2058 // sext(zext(x)) --> zext(x)
2060 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
2061
2062 // If the operand is an affine AddRec with the no-signed-wrap flag, the
2063 // sign-extension distributes over the recurrence.
2064 if (Depth <= MaxCastDepth)
2065 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(Op))
2066 if (AR->isAffine() && AR->hasNoSignedWrap()) {
2067 const SCEV *Start =
2069 const SCEV *Step =
2070 getSignExtendExpr(AR->getStepRecurrence(*this), Ty, Depth + 1);
2071 return getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagNSW);
2072 }
2073
2074 // Before doing any expensive analysis, check to see if we've already
2075 // computed a SCEV for this Op and Ty.
2077 ID.AddInteger(scSignExtend);
2078 ID.AddPointer(Op);
2079 ID.AddPointer(Ty);
2080 void *IP = nullptr;
2081 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2082 // Limit recursion depth.
2083 if (Depth > MaxCastDepth) {
2084 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2085 Op, Ty);
2086 UniqueSCEVs.InsertNode(S, IP);
2087 S->computeAndSetCanonical(*this);
2088 registerUser(S, Op);
2089 return S;
2090 }
2091
2092 // sext(trunc(x)) --> sext(x) or x or trunc(x)
2094 // It's possible the bits taken off by the truncate were all sign bits. If
2095 // so, we should be able to simplify this further.
2096 const SCEV *X = ST->getOperand();
2098 unsigned TruncBits = getTypeSizeInBits(ST->getType());
2099 unsigned NewBits = getTypeSizeInBits(Ty);
2100 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
2101 CR.sextOrTrunc(NewBits)))
2102 return getTruncateOrSignExtend(X, Ty, Depth);
2103 }
2104
2105 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
2106 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
2107 if (SA->hasNoSignedWrap()) {
2108 // If the addition does not sign overflow then we can, by definition,
2109 // commute the sign extension with the addition operation.
2111 for (SCEVUse Op : SA->operands())
2112 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
2113 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
2114 }
2115
2116 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2117 // if D + (C - D + x + y + ...) could be proven to not signed wrap
2118 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2119 //
2120 // For instance, this will bring two seemingly different expressions:
2121 // 1 + sext(5 + 20 * %x + 24 * %y) and
2122 // sext(6 + 20 * %x + 24 * %y)
2123 // to the same form:
2124 // 2 + sext(4 + 20 * %x + 24 * %y)
2125 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2126 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2127 if (D != 0) {
2128 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2129 const SCEV *SResidual =
2131 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2132 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2133 Depth + 1);
2134 }
2135 }
2136 }
2137 // If the input value is a chrec scev, and we can prove that the value
2138 // did not overflow the old, smaller, value, we can sign extend all of the
2139 // operands (often constants). This allows analysis of something like
2140 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2142 if (AR->isAffine()) {
2143 const SCEV *Start = AR->getStart();
2144 const SCEV *Step = AR->getStepRecurrence(*this);
2145 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2146 const Loop *L = AR->getLoop();
2147
2148 // The no-signed-wrap case is handled before the uniquing lookup above.
2149
2150 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2151 // Note that this serves two purposes: It filters out loops that are
2152 // simply not analyzable, and it covers the case where this code is
2153 // being called from within backedge-taken count analysis, such that
2154 // attempting to ask for the backedge-taken count would likely result
2155 // in infinite recursion. In the later case, the analysis code will
2156 // cope with a conservative value, and it will take care to purge
2157 // that value once it has finished.
2158 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2159 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2160 // Manually compute the final value for AR, checking for
2161 // overflow.
2162
2163 // Check whether the backedge-taken count can be losslessly casted to
2164 // the addrec's type. The count is always unsigned.
2165 const SCEV *CastedMaxBECount =
2166 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2167 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2168 CastedMaxBECount, MaxBECount->getType(), Depth);
2169 if (MaxBECount == RecastedMaxBECount) {
2170 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2171 // Check whether Start+Step*MaxBECount has no signed overflow.
2172 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2174 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2176 Depth + 1),
2177 WideTy, Depth + 1);
2178 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2179 const SCEV *WideMaxBECount =
2180 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2181 const SCEV *OperandExtendedAdd =
2182 getAddExpr(WideStart,
2183 getMulExpr(WideMaxBECount,
2184 getSignExtendExpr(Step, WideTy, Depth + 1),
2187 if (SAdd == OperandExtendedAdd) {
2188 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2189 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2190 // Return the expression with the addrec on the outside.
2191 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2192 Depth + 1);
2193 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2194 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2195 }
2196 // Similar to above, only this time treat the step value as unsigned.
2197 // This covers loops that count up with an unsigned step.
2198 OperandExtendedAdd =
2199 getAddExpr(WideStart,
2200 getMulExpr(WideMaxBECount,
2201 getZeroExtendExpr(Step, WideTy, Depth + 1),
2204 if (SAdd == OperandExtendedAdd) {
2205 // If AR wraps around then
2206 //
2207 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2208 // => SAdd != OperandExtendedAdd
2209 //
2210 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2211 // (SAdd == OperandExtendedAdd => AR is NW)
2212
2213 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2214
2215 // Return the expression with the addrec on the outside.
2216 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2217 Depth + 1);
2218 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2219 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2220 }
2221 }
2222 }
2223
2224 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2225 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2226 if (AR->hasNoSignedWrap()) {
2227 // Same as nsw case above - duplicated here to avoid a compile time
2228 // issue. It's not clear that the order of checks does matter, but
2229 // it's one of two issue possible causes for a change which was
2230 // reverted. Be conservative for the moment.
2231 Start =
2233 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2234 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2235 }
2236
2237 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2238 // if D + (C - D + Step * n) could be proven to not signed wrap
2239 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2240 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2241 const APInt &C = SC->getAPInt();
2242 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2243 if (D != 0) {
2244 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2245 const SCEV *SResidual =
2246 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2247 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2248 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2249 Depth + 1);
2250 }
2251 }
2252
2253 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2254 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2255 Start =
2257 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2258 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2259 }
2260 }
2261
2262 // If the input value is provably positive and we could not simplify
2263 // away the sext build a zext instead.
2265 return getZeroExtendExpr(Op, Ty, Depth + 1);
2266
2267 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2268 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2271 SmallVector<SCEVUse, 4> Operands;
2272 for (SCEVUse Operand : MinMax->operands())
2273 Operands.push_back(getSignExtendExpr(Operand, Ty));
2275 return getSMinExpr(Operands);
2276 return getSMaxExpr(Operands);
2277 }
2278
2279 // The cast wasn't folded; create an explicit cast node.
2280 // Recompute the insert position, as it may have been invalidated.
2281 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2282 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2283 Op, Ty);
2284 UniqueSCEVs.InsertNode(S, IP);
2285 S->computeAndSetCanonical(*this);
2286 registerUser(S, Op);
2287 return S;
2288}
2289
2291 Type *Ty) {
2292 switch (Kind) {
2293 case scTruncate:
2294 return getTruncateExpr(Op, Ty);
2295 case scZeroExtend:
2296 return getZeroExtendExpr(Op, Ty);
2297 case scSignExtend:
2298 return getSignExtendExpr(Op, Ty);
2299 case scPtrToInt:
2300 return getPtrToIntExpr(Op, Ty);
2301 default:
2302 llvm_unreachable("Not a SCEV cast expression!");
2303 }
2304}
2305
2306/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2307/// unspecified bits out to the given type.
2309 Type *Ty) {
2310 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2311 "This is not an extending conversion!");
2312 assert(isSCEVable(Ty) &&
2313 "This is not a conversion to a SCEVable type!");
2314 Ty = getEffectiveSCEVType(Ty);
2315
2316 // Sign-extend negative constants.
2317 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2318 if (SC->getAPInt().isNegative())
2319 return getSignExtendExpr(Op, Ty);
2320
2321 // Peel off a truncate cast.
2323 const SCEV *NewOp = T->getOperand();
2324 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2325 return getAnyExtendExpr(NewOp, Ty);
2326 return getTruncateOrNoop(NewOp, Ty);
2327 }
2328
2329 // Next try a zext cast. If the cast is folded, use it.
2330 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2331 if (!isa<SCEVZeroExtendExpr>(ZExt))
2332 return ZExt;
2333
2334 // Next try a sext cast. If the cast is folded, use it.
2335 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2336 if (!isa<SCEVSignExtendExpr>(SExt))
2337 return SExt;
2338
2339 // Force the cast to be folded into the operands of an addrec.
2340 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2342 for (const SCEV *Op : AR->operands())
2343 Ops.push_back(getAnyExtendExpr(Op, Ty));
2344 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2345 }
2346
2347 // If the expression is obviously signed, use the sext cast value.
2348 if (isa<SCEVSMaxExpr>(Op))
2349 return SExt;
2350
2351 // Absent any other information, use the zext cast value.
2352 return ZExt;
2353}
2354
2355/// Process the given Ops list, which is a list of operands to be added under
2356/// the given scale, update the given map. This is a helper function for
2357/// getAddRecExpr. As an example of what it does, given a sequence of operands
2358/// that would form an add expression like this:
2359///
2360/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2361///
2362/// where A and B are constants, update the map with these values:
2363///
2364/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2365///
2366/// and add 13 + A*B*29 to AccumulatedConstant.
2367/// This will allow getAddRecExpr to produce this:
2368///
2369/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2370///
2371/// This form often exposes folding opportunities that are hidden in
2372/// the original operand list.
2373///
2374/// Return true iff it appears that any interesting folding opportunities
2375/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2376/// the common case where no interesting opportunities are present, and
2377/// is also used as a check to avoid infinite recursion.
2380 APInt &AccumulatedConstant,
2382 const APInt &Scale,
2383 ScalarEvolution &SE) {
2384 bool Interesting = false;
2385
2386 // Iterate over the add operands. They are sorted, with constants first.
2387 unsigned i = 0;
2388 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2389 ++i;
2390 // Pull a buried constant out to the outside.
2391 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2392 Interesting = true;
2393 AccumulatedConstant += Scale * C->getAPInt();
2394 }
2395
2396 // Next comes everything else. We're especially interested in multiplies
2397 // here, but they're in the middle, so just visit the rest with one loop.
2398 for (; i != Ops.size(); ++i) {
2400 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2401 APInt NewScale =
2402 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2403 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2404 // A multiplication of a constant with another add; recurse.
2405 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2406 Interesting |= CollectAddOperandsWithScales(
2407 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2408 } else {
2409 // A multiplication of a constant with some other value. Update
2410 // the map.
2411 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2412 const SCEV *Key = SE.getMulExpr(MulOps);
2413 auto Pair = M.insert({Key, NewScale});
2414 if (Pair.second) {
2415 NewOps.push_back(Pair.first->first);
2416 } else {
2417 Pair.first->second += NewScale;
2418 // The map already had an entry for this value, which may indicate
2419 // a folding opportunity.
2420 Interesting = true;
2421 }
2422 }
2423 } else {
2424 // An ordinary operand. Update the map.
2425 auto Pair = M.insert({Ops[i], Scale});
2426 if (Pair.second) {
2427 NewOps.push_back(Pair.first->first);
2428 } else {
2429 Pair.first->second += Scale;
2430 // The map already had an entry for this value, which may indicate
2431 // a folding opportunity.
2432 Interesting = true;
2433 }
2434 }
2435 }
2436
2437 return Interesting;
2438}
2439
2441 const SCEV *LHS, const SCEV *RHS,
2442 const Instruction *CtxI) {
2444 unsigned);
2445 switch (BinOp) {
2446 default:
2447 llvm_unreachable("Unsupported binary op");
2448 case Instruction::Add:
2450 break;
2451 case Instruction::Sub:
2453 break;
2454 case Instruction::Mul:
2456 break;
2457 }
2458
2459 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2462
2463 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2464 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2465 auto *WideTy =
2466 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2467
2468 const SCEV *A = (this->*Extension)(
2469 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2470 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2471 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2472 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2473 if (A == B)
2474 return true;
2475 // Can we use context to prove the fact we need?
2476 if (!CtxI)
2477 return false;
2478 // TODO: Support mul.
2479 if (BinOp == Instruction::Mul)
2480 return false;
2481 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2482 // TODO: Lift this limitation.
2483 if (!RHSC)
2484 return false;
2485 APInt C = RHSC->getAPInt();
2486 unsigned NumBits = C.getBitWidth();
2487 bool IsSub = (BinOp == Instruction::Sub);
2488 bool IsNegativeConst = (Signed && C.isNegative());
2489 // Compute the direction and magnitude by which we need to check overflow.
2490 bool OverflowDown = IsSub ^ IsNegativeConst;
2491 APInt Magnitude = C;
2492 if (IsNegativeConst) {
2493 if (C == APInt::getSignedMinValue(NumBits))
2494 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2495 // want to deal with that.
2496 return false;
2497 Magnitude = -C;
2498 }
2499
2501 if (OverflowDown) {
2502 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2503 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2504 : APInt::getMinValue(NumBits);
2505 APInt Limit = Min + Magnitude;
2506 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2507 } else {
2508 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2509 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2510 : APInt::getMaxValue(NumBits);
2511 APInt Limit = Max - Magnitude;
2512 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2513 }
2514}
2515
2516std::optional<SCEV::NoWrapFlags>
2518 const OverflowingBinaryOperator *OBO) {
2519 // It cannot be done any better.
2520 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2521 return std::nullopt;
2522
2523 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2524
2525 if (OBO->hasNoUnsignedWrap())
2527 if (OBO->hasNoSignedWrap())
2529
2530 bool Deduced = false;
2531
2533 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2534 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2535
2536 bool CanUseNSW = true;
2537 const APInt *ShiftAmt;
2538 // Treat `shl %a, C` as `mul %a, 1 << C`.
2539 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2540 unsigned BitWidth = ShiftAmt->getBitWidth();
2541 if (ShiftAmt->uge(BitWidth))
2542 return std::nullopt;
2543 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2544 // overflows.
2545 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2546 Opcode = Instruction::Mul;
2548 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2549 Opcode != Instruction::Mul) {
2550 return std::nullopt;
2551 }
2552
2553 const Instruction *CtxI =
2555 if (!OBO->hasNoUnsignedWrap() &&
2556 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2558 Deduced = true;
2559 }
2560
2561 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2562 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2564 Deduced = true;
2565 }
2566
2567 if (Deduced)
2568 return Flags;
2569 return std::nullopt;
2570}
2571
2572// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2573// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2574// can't-overflow flags for the operation if possible.
2578 SCEV::NoWrapFlags Flags) {
2579 using namespace std::placeholders;
2580
2581 using OBO = OverflowingBinaryOperator;
2582
2583 bool CanAnalyze =
2585 (void)CanAnalyze;
2586 assert(CanAnalyze && "don't call from other places!");
2587
2588 SCEV::NoWrapFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2589 SCEV::NoWrapFlags SignOrUnsignWrap =
2590 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2591
2592 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2593 auto IsKnownNonNegative = [&](SCEVUse U) {
2594 return SE->isKnownNonNegative(U);
2595 };
2596
2597 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2598 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2599
2600 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2601
2602 if (SignOrUnsignWrap != SignOrUnsignMask &&
2603 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2604 isa<SCEVConstant>(Ops[0])) {
2605
2606 auto Opcode = [&] {
2607 switch (Type) {
2608 case scAddExpr:
2609 return Instruction::Add;
2610 case scMulExpr:
2611 return Instruction::Mul;
2612 default:
2613 llvm_unreachable("Unexpected SCEV op.");
2614 }
2615 }();
2616
2617 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2618
2619 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2620 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2622 Opcode, C, OBO::NoSignedWrap);
2623 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2625 }
2626
2627 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2628 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2630 Opcode, C, OBO::NoUnsignedWrap);
2631 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2633 }
2634 }
2635
2636 // <0,+,nonnegative><nw> is also nuw
2637 // TODO: Add corresponding nsw case
2639 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2640 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2642
2643 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2645 Ops.size() == 2) {
2646 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2647 if (UDiv->getOperand(1) == Ops[1])
2649 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2650 if (UDiv->getOperand(1) == Ops[0])
2652 }
2653
2654 return Flags;
2655}
2656
2658 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2659}
2660
2661/// Get a canonical add expression, or something simpler if possible.
2663 SCEV::NoWrapFlags OrigFlags,
2664 unsigned Depth) {
2665 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2666 "only nuw or nsw allowed");
2667 assert(!Ops.empty() && "Cannot get empty add!");
2668 if (Ops.size() == 1) return Ops[0];
2669#ifndef NDEBUG
2670 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2671 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2672 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2673 "SCEVAddExpr operand types don't match!");
2674 unsigned NumPtrs = count_if(
2675 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2676 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2677#endif
2678
2679 const SCEV *Folded = constantFoldAndGroupOps(
2680 *this, LI, DT, Ops,
2681 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2682 [](const APInt &C) { return C.isZero(); }, // identity
2683 [](const APInt &C) { return false; }); // absorber
2684 if (Folded)
2685 return Folded;
2686
2687 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2688
2689 // Delay expensive flag strengthening until necessary.
2690 auto ComputeFlags = [this, OrigFlags](ArrayRef<SCEVUse> Ops) {
2691 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2692 };
2693
2694 // Limit recursion calls depth.
2696 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2697
2698 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2699 // Don't strengthen flags if we have no new information.
2700 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2701 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2702 Add->setNoWrapFlags(ComputeFlags(Ops));
2703 return S;
2704 }
2705
2706 // Okay, check to see if the same value occurs in the operand list more than
2707 // once. If so, merge them together into an multiply expression. Since we
2708 // sorted the list, these values are required to be adjacent.
2709 Type *Ty = Ops[0]->getType();
2710 bool FoundMatch = false;
2711 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2712 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2713 // Scan ahead to count how many equal operands there are.
2714 unsigned Count = 2;
2715 while (i+Count != e && Ops[i+Count] == Ops[i])
2716 ++Count;
2717 // Merge the values into a multiply.
2718 SCEVUse Scale = getConstant(Ty, Count);
2719 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2720 if (Ops.size() == Count)
2721 return Mul;
2722 Ops[i] = Mul;
2723 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2724 --i; e -= Count - 1;
2725 FoundMatch = true;
2726 }
2727 if (FoundMatch)
2728 return getAddExpr(Ops, OrigFlags, Depth + 1);
2729
2730 // Check for truncates. If all the operands are truncated from the same
2731 // type, see if factoring out the truncate would permit the result to be
2732 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2733 // if the contents of the resulting outer trunc fold to something simple.
2734 auto FindTruncSrcType = [&]() -> Type * {
2735 // We're ultimately looking to fold an addrec of truncs and muls of only
2736 // constants and truncs, so if we find any other types of SCEV
2737 // as operands of the addrec then we bail and return nullptr here.
2738 // Otherwise, we return the type of the operand of a trunc that we find.
2739 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2740 return T->getOperand()->getType();
2741 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2742 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2743 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2744 return T->getOperand()->getType();
2745 }
2746 return nullptr;
2747 };
2748 if (auto *SrcType = FindTruncSrcType()) {
2749 SmallVector<SCEVUse, 8> LargeOps;
2750 bool Ok = true;
2751 // Check all the operands to see if they can be represented in the
2752 // source type of the truncate.
2753 for (const SCEV *Op : Ops) {
2755 if (T->getOperand()->getType() != SrcType) {
2756 Ok = false;
2757 break;
2758 }
2759 LargeOps.push_back(T->getOperand());
2760 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2761 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2762 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2763 SmallVector<SCEVUse, 8> LargeMulOps;
2764 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2765 if (const SCEVTruncateExpr *T =
2766 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2767 if (T->getOperand()->getType() != SrcType) {
2768 Ok = false;
2769 break;
2770 }
2771 LargeMulOps.push_back(T->getOperand());
2772 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2773 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2774 } else {
2775 Ok = false;
2776 break;
2777 }
2778 }
2779 if (Ok)
2780 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2781 } else {
2782 Ok = false;
2783 break;
2784 }
2785 }
2786 if (Ok) {
2787 // Evaluate the expression in the larger type.
2788 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2789 // If it folds to something simple, use it. Otherwise, don't.
2790 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2791 return getTruncateExpr(Fold, Ty);
2792 }
2793 }
2794
2795 if (Ops.size() == 2) {
2796 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2797 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2798 // C1).
2799 const SCEV *A = Ops[0];
2800 const SCEV *B = Ops[1];
2801 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2802 auto *C = dyn_cast<SCEVConstant>(A);
2803 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2804 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2805 auto C2 = C->getAPInt();
2806 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2807
2808 APInt ConstAdd = C1 + C2;
2809 auto AddFlags = AddExpr->getNoWrapFlags();
2810 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2812 ConstAdd.ule(C1)) {
2813 PreservedFlags =
2815 }
2816
2817 // Adding a constant with the same sign and small magnitude is NSW, if the
2818 // original AddExpr was NSW.
2820 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2821 ConstAdd.abs().ule(C1.abs())) {
2822 PreservedFlags =
2824 }
2825
2826 if (PreservedFlags != SCEV::FlagAnyWrap) {
2827 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2828 NewOps[0] = getConstant(ConstAdd);
2829 return getAddExpr(NewOps, PreservedFlags);
2830 }
2831 }
2832
2833 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2834 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2835 const SCEVAddExpr *InnerAdd;
2836 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2837 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2838 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2839 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2840 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2842 SCEV::FlagNUW)) {
2843 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2844 }
2845 }
2846 }
2847
2848 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2849 const SCEV *Y;
2850 if (Ops.size() == 2 &&
2851 match(Ops[0],
2853 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2854 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2855
2856 // Skip past any other cast SCEVs.
2857 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2858 ++Idx;
2859
2860 // If there are add operands they would be next.
2861 if (Idx < Ops.size()) {
2862 bool DeletedAdd = false;
2863 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2864 // common NUW flag for expression after inlining. Other flags cannot be
2865 // preserved, because they may depend on the original order of operations.
2866 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2867 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2868 if (Ops.size() > AddOpsInlineThreshold ||
2869 Add->getNumOperands() > AddOpsInlineThreshold)
2870 break;
2871 // If we have an add, expand the add operands onto the end of the operands
2872 // list.
2873 Ops.erase(Ops.begin()+Idx);
2874 append_range(Ops, Add->operands());
2875 DeletedAdd = true;
2876 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2877 }
2878
2879 // If we deleted at least one add, we added operands to the end of the list,
2880 // and they are not necessarily sorted. Recurse to resort and resimplify
2881 // any operands we just acquired.
2882 if (DeletedAdd)
2883 return getAddExpr(Ops, CommonFlags, Depth + 1);
2884 }
2885
2886 // Skip over the add expression until we get to a multiply.
2887 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2888 ++Idx;
2889
2890 // Check to see if there are any folding opportunities present with
2891 // operands multiplied by constant values.
2892 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2896 APInt AccumulatedConstant(BitWidth, 0);
2897 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2898 Ops, APInt(BitWidth, 1), *this)) {
2899 struct APIntCompare {
2900 bool operator()(const APInt &LHS, const APInt &RHS) const {
2901 return LHS.ult(RHS);
2902 }
2903 };
2904
2905 // Some interesting folding opportunity is present, so its worthwhile to
2906 // re-generate the operands list. Group the operands by constant scale,
2907 // to avoid multiplying by the same constant scale multiple times.
2908 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2909 for (const SCEV *NewOp : NewOps)
2910 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2911 // Re-generate the operands list.
2912 Ops.clear();
2913 if (AccumulatedConstant != 0)
2914 Ops.push_back(getConstant(AccumulatedConstant));
2915 for (auto &MulOp : MulOpLists) {
2916 if (MulOp.first == 1) {
2917 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2918 } else if (MulOp.first != 0) {
2919 Ops.push_back(getMulExpr(
2920 getConstant(MulOp.first),
2921 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2922 SCEV::FlagAnyWrap, Depth + 1));
2923 }
2924 }
2925 if (Ops.empty())
2926 return getZero(Ty);
2927 if (Ops.size() == 1)
2928 return Ops[0];
2929 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2930 }
2931 }
2932
2933 // Given a SCEVMulExpr and an operand index, return the product of all
2934 // operands except the one at OpIdx.
2935 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2936 if (M->getNumOperands() == 2)
2937 return M->getOperand(OpIdx == 0);
2938 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2939 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2940 return getMulExpr(Remaining, SCEV::FlagAnyWrap, Depth + 1);
2941 };
2942
2943 // If we are adding something to a multiply expression, make sure the
2944 // something is not already an operand of the multiply. If so, merge it into
2945 // the multiply.
2946 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2947 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2948 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2949 // Scan all terms to find every occurrence of common factor MulOpSCEV
2950 // and fold them in one shot:
2951 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2952 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2953 if (isa<SCEVConstant>(MulOpSCEV))
2954 continue;
2955
2956 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2957 // remaining product for multiply terms containing MulOpSCEV.
2958 SmallVector<SCEVUse, 4> Cofactors;
2959 SmallVector<unsigned, 4> DeadIndices;
2960 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2961 if (MulOpSCEV == Ops[AddOp]) {
2962 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2963 Cofactors.push_back(getOne(Ty));
2964 DeadIndices.push_back(AddOp);
2965 continue;
2966 }
2967
2968 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2969 continue;
2970
2971 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2972 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2973 ++OMulOp) {
2974 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2975 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2976 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2977 DeadIndices.push_back(AddOp);
2978 break;
2979 }
2980 }
2981 }
2982
2983 // Fold all collected cofactors with the anchor multiply's cofactor:
2984 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2985 if (!Cofactors.empty()) {
2986 Cofactors.push_back(StripFactor(Mul, MulOp));
2987
2988 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagAnyWrap, Depth + 1);
2989 SCEVUse OuterMul =
2990 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagAnyWrap, Depth + 1);
2991
2992 // DeadIndices does not include Idx (the anchor), hence +1.
2993 if (Ops.size() == DeadIndices.size() + 1)
2994 return OuterMul;
2995
2996 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2997 // The -1 adjustment accounts for the shift from removing Idx;
2998 // reverse order means each erasure only shifts later positions,
2999 // which have already been processed.
3000 Ops.erase(Ops.begin() + Idx);
3001 for (unsigned Dead : reverse(DeadIndices))
3002 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
3003
3004 Ops.push_back(OuterMul);
3005 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3006 }
3007 }
3008 }
3009
3010 // If there are any add recurrences in the operands list, see if any other
3011 // added values are loop invariant. If so, we can fold them into the
3012 // recurrence.
3013 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3014 ++Idx;
3015
3016 // Scan over all recurrences, trying to fold loop invariants into them.
3017 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3018 // Scan all of the other operands to this add and add them to the vector if
3019 // they are loop invariant w.r.t. the recurrence.
3021 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3022 const Loop *AddRecLoop = AddRec->getLoop();
3023 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3024 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3025 LIOps.push_back(Ops[i]);
3026 Ops.erase(Ops.begin()+i);
3027 --i; --e;
3028 }
3029
3030 // If we found some loop invariants, fold them into the recurrence.
3031 if (!LIOps.empty()) {
3032 // Compute nowrap flags for the addition of the loop-invariant ops and
3033 // the addrec. Temporarily push it as an operand for that purpose. These
3034 // flags are valid in the scope of the addrec only.
3035 LIOps.push_back(AddRec);
3036 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
3037 LIOps.pop_back();
3038
3039 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
3040 LIOps.push_back(AddRec->getStart());
3041
3042 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
3043
3044 // It is not in general safe to propagate flags valid on an add within
3045 // the addrec scope to one outside it. We must prove that the inner
3046 // scope is guaranteed to execute if the outer one does to be able to
3047 // safely propagate. We know the program is undefined if poison is
3048 // produced on the inner scoped addrec. We also know that *for this use*
3049 // the outer scoped add can't overflow (because of the flags we just
3050 // computed for the inner scoped add) without the program being undefined.
3051 // Proving that entry to the outer scope neccesitates entry to the inner
3052 // scope, thus proves the program undefined if the flags would be violated
3053 // in the outer scope.
3054 SCEV::NoWrapFlags AddFlags = Flags;
3055 if (AddFlags != SCEV::FlagAnyWrap) {
3056 auto *DefI = getDefiningScopeBound(LIOps);
3057 auto *ReachI = &*AddRecLoop->getHeader()->begin();
3058 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
3059 AddFlags = SCEV::FlagAnyWrap;
3060 }
3061 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
3062
3063 // Build the new addrec. Propagate the NUW and NSW flags if both the
3064 // outer add and the inner addrec are guaranteed to have no overflow.
3065 // Always propagate NW.
3066 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
3067 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
3068
3069 // If all of the other operands were loop invariant, we are done.
3070 if (Ops.size() == 1) return NewRec;
3071
3072 // Otherwise, add the folded AddRec by the non-invariant parts.
3073 for (unsigned i = 0;; ++i)
3074 if (Ops[i] == AddRec) {
3075 Ops[i] = NewRec;
3076 break;
3077 }
3078 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3079 }
3080
3081 // Okay, if there weren't any loop invariants to be folded, check to see if
3082 // there are multiple AddRec's with the same loop induction variable being
3083 // added together. If so, we can fold them.
3084 for (unsigned OtherIdx = Idx+1;
3085 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3086 ++OtherIdx) {
3087 // We expect the AddRecExpr's to be sorted in reverse dominance order,
3088 // so that the 1st found AddRecExpr is dominated by all others.
3089 assert(DT.dominates(
3090 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
3091 AddRec->getLoop()->getHeader()) &&
3092 "AddRecExprs are not sorted in reverse dominance order?");
3093 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
3094 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
3095 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
3096 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3097 ++OtherIdx) {
3098 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3099 if (OtherAddRec->getLoop() == AddRecLoop) {
3100 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
3101 i != e; ++i) {
3102 if (i >= AddRecOps.size()) {
3103 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
3104 break;
3105 }
3106 AddRecOps[i] =
3107 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
3109 }
3110 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3111 }
3112 }
3113 // Step size has changed, so we cannot guarantee no self-wraparound.
3114 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
3115 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3116 }
3117 }
3118
3119 // Otherwise couldn't fold anything into this recurrence. Move onto the
3120 // next one.
3121 }
3122
3123 // Okay, it looks like we really DO need an add expr. Check to see if we
3124 // already have one, otherwise create a new one.
3125 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
3126}
3127
3128const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
3129 SCEV::NoWrapFlags Flags) {
3131 ID.AddInteger(scAddExpr);
3132 for (const SCEV *Op : Ops)
3133 ID.AddPointer(Op);
3134 void *IP = nullptr;
3135 SCEVAddExpr *S =
3136 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3137 if (!S) {
3138 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3140 S = new (SCEVAllocator)
3141 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
3142 UniqueSCEVs.InsertNode(S, IP);
3143 S->computeAndSetCanonical(*this);
3144 registerUser(S, Ops);
3145 }
3146 S->setNoWrapFlags(Flags);
3147 return S;
3148}
3149
3150const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
3151 const Loop *L,
3152 SCEV::NoWrapFlags Flags) {
3153 FoldingSetNodeID ID;
3154 ID.AddInteger(scAddRecExpr);
3155 for (const SCEV *Op : Ops)
3156 ID.AddPointer(Op);
3157 ID.AddPointer(L);
3158 void *IP = nullptr;
3159 SCEVAddRecExpr *S =
3160 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3161 if (!S) {
3162 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3164 S = new (SCEVAllocator)
3165 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3166 UniqueSCEVs.InsertNode(S, IP);
3167 S->computeAndSetCanonical(*this);
3168 LoopUsers[L].push_back(S);
3169 registerUser(S, Ops);
3170 }
3171 setNoWrapFlags(S, Flags);
3172 return S;
3173}
3174
3175const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3176 SCEV::NoWrapFlags Flags) {
3177 FoldingSetNodeID ID;
3178 ID.AddInteger(scMulExpr);
3179 for (const SCEV *Op : Ops)
3180 ID.AddPointer(Op);
3181 void *IP = nullptr;
3182 SCEVMulExpr *S =
3183 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3184 if (!S) {
3185 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3187 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3188 O, Ops.size());
3189 UniqueSCEVs.InsertNode(S, IP);
3190 S->computeAndSetCanonical(*this);
3191 registerUser(S, Ops);
3192 }
3193 S->setNoWrapFlags(Flags);
3194 return S;
3195}
3196
3197static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3198 uint64_t k = i*j;
3199 if (j > 1 && k / j != i) Overflow = true;
3200 return k;
3201}
3202
3203/// Compute the result of "n choose k", the binomial coefficient. If an
3204/// intermediate computation overflows, Overflow will be set and the return will
3205/// be garbage. Overflow is not cleared on absence of overflow.
3206static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3207 // We use the multiplicative formula:
3208 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3209 // At each iteration, we take the n-th term of the numeral and divide by the
3210 // (k-n)th term of the denominator. This division will always produce an
3211 // integral result, and helps reduce the chance of overflow in the
3212 // intermediate computations. However, we can still overflow even when the
3213 // final result would fit.
3214
3215 if (n == 0 || n == k) return 1;
3216 if (k > n) return 0;
3217
3218 if (k > n/2)
3219 k = n-k;
3220
3221 uint64_t r = 1;
3222 for (uint64_t i = 1; i <= k; ++i) {
3223 r = umul_ov(r, n-(i-1), Overflow);
3224 r /= i;
3225 }
3226 return r;
3227}
3228
3229/// Determine if any of the operands in this SCEV are a constant or if
3230/// any of the add or multiply expressions in this SCEV contain a constant.
3231static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3232 struct FindConstantInAddMulChain {
3233 bool FoundConstant = false;
3234
3235 bool follow(const SCEV *S) {
3236 FoundConstant |= isa<SCEVConstant>(S);
3237 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3238 }
3239
3240 bool isDone() const {
3241 return FoundConstant;
3242 }
3243 };
3244
3245 FindConstantInAddMulChain F;
3247 ST.visitAll(StartExpr);
3248 return F.FoundConstant;
3249}
3250
3251/// Get a canonical multiply expression, or something simpler if possible.
3253 SCEV::NoWrapFlags OrigFlags,
3254 unsigned Depth) {
3255 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3256 "only nuw or nsw allowed");
3257 assert(!Ops.empty() && "Cannot get empty mul!");
3258 if (Ops.size() == 1) return Ops[0];
3259#ifndef NDEBUG
3260 Type *ETy = Ops[0]->getType();
3261 assert(!ETy->isPointerTy());
3262 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3263 assert(Ops[i]->getType() == ETy &&
3264 "SCEVMulExpr operand types don't match!");
3265#endif
3266
3267 const SCEV *Folded = constantFoldAndGroupOps(
3268 *this, LI, DT, Ops,
3269 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3270 [](const APInt &C) { return C.isOne(); }, // identity
3271 [](const APInt &C) { return C.isZero(); }); // absorber
3272 if (Folded)
3273 return Folded;
3274
3275 // Delay expensive flag strengthening until necessary.
3276 auto ComputeFlags = [this, OrigFlags](const ArrayRef<SCEVUse> Ops) {
3277 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3278 };
3279
3280 // Limit recursion calls depth.
3282 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3283
3284 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3285 // Don't strengthen flags if we have no new information.
3286 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3287 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3288 Mul->setNoWrapFlags(ComputeFlags(Ops));
3289 return S;
3290 }
3291
3292 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3293 if (Ops.size() == 2) {
3294 // C1*(C2+V) -> C1*C2 + C1*V
3295 // If any of Add's ops are Adds or Muls with a constant, apply this
3296 // transformation as well.
3297 //
3298 // TODO: There are some cases where this transformation is not
3299 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3300 // this transformation should be narrowed down.
3301 const SCEV *Op0, *Op1;
3302 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3304 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagAnyWrap, Depth + 1);
3305 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagAnyWrap, Depth + 1);
3306 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3307 }
3308
3309 if (Ops[0]->isAllOnesValue()) {
3310 // If we have a mul by -1 of an add, try distributing the -1 among the
3311 // add operands.
3312 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3314 bool AnyFolded = false;
3315 for (const SCEV *AddOp : Add->operands()) {
3316 const SCEV *Mul = getMulExpr(Ops[0], SCEVUse(AddOp),
3318 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3319 NewOps.push_back(Mul);
3320 }
3321 if (AnyFolded)
3322 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3323 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3324 // Negation preserves a recurrence's no self-wrap property.
3325 SmallVector<SCEVUse, 4> Operands;
3326 for (const SCEV *AddRecOp : AddRec->operands())
3327 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3328 SCEV::FlagAnyWrap, Depth + 1));
3329 // Let M be the minimum representable signed value. AddRec with nsw
3330 // multiplied by -1 can have signed overflow if and only if it takes a
3331 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3332 // maximum signed value. In all other cases signed overflow is
3333 // impossible.
3334 auto FlagsMask = SCEV::FlagNW;
3335 if (AddRec->hasNoSignedWrap()) {
3336 auto MinInt =
3337 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3338 if (getSignedRangeMin(AddRec) != MinInt)
3339 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3340 }
3341 return getAddRecExpr(Operands, AddRec->getLoop(),
3342 AddRec->getNoWrapFlags(FlagsMask));
3343 }
3344 }
3345
3346 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3347 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3348 const SCEVAddExpr *InnerAdd;
3349 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3350 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3351 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3352 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3353 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3355 SCEV::FlagNUW)) {
3356 auto *Res = getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3357 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3358 };
3359 }
3360
3361 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3362 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3363 // of C1, fold to (D /u (C2 /u C1)).
3364 const SCEV *D;
3365 APInt C1V = LHSC->getAPInt();
3366 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3367 // as -1 * 1, as it won't enable additional folds.
3368 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3369 C1V = C1V.abs();
3370 const SCEVConstant *C2;
3371 if (C1V.isPowerOf2() &&
3373 C2->getAPInt().isPowerOf2() &&
3374 C1V.logBase2() <= getMinTrailingZeros(D)) {
3375 const SCEV *NewMul = nullptr;
3376 if (C1V.uge(C2->getAPInt())) {
3377 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3378 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3379 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3380 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3381 }
3382 if (NewMul)
3383 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3384 }
3385 }
3386 }
3387
3388 // Skip over the add expression until we get to a multiply.
3389 unsigned Idx = 0;
3390 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3391 ++Idx;
3392
3393 // If there are mul operands inline them all into this expression.
3394 if (Idx < Ops.size()) {
3395 bool DeletedMul = false;
3396 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3397 if (Ops.size() > MulOpsInlineThreshold)
3398 break;
3399 // If we have an mul, expand the mul operands onto the end of the
3400 // operands list.
3401 Ops.erase(Ops.begin()+Idx);
3402 append_range(Ops, Mul->operands());
3403 DeletedMul = true;
3404 }
3405
3406 // If we deleted at least one mul, we added operands to the end of the
3407 // list, and they are not necessarily sorted. Recurse to resort and
3408 // resimplify any operands we just acquired.
3409 if (DeletedMul)
3410 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3411 }
3412
3413 // If there are any add recurrences in the operands list, see if any other
3414 // added values are loop invariant. If so, we can fold them into the
3415 // recurrence.
3416 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3417 ++Idx;
3418
3419 // Scan over all recurrences, trying to fold loop invariants into them.
3420 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3421 // Scan all of the other operands to this mul and add them to the vector
3422 // if they are loop invariant w.r.t. the recurrence.
3424 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3425 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3426 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3427 LIOps.push_back(Ops[i]);
3428 Ops.erase(Ops.begin()+i);
3429 --i; --e;
3430 }
3431
3432 // If we found some loop invariants, fold them into the recurrence.
3433 if (!LIOps.empty()) {
3434 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3436 NewOps.reserve(AddRec->getNumOperands());
3437 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3438
3439 // If both the mul and addrec are nuw, we can preserve nuw.
3440 // If both the mul and addrec are nsw, we can only preserve nsw if either
3441 // a) they are also nuw, or
3442 // b) all multiplications of addrec operands with scale are nsw.
3443 SCEV::NoWrapFlags Flags =
3444 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3445
3446 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3447 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3448 SCEV::FlagAnyWrap, Depth + 1));
3449
3450 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3452 Instruction::Mul, getSignedRange(Scale),
3454 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3455 Flags = clearFlags(Flags, SCEV::FlagNSW);
3456 }
3457 }
3458
3459 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3460
3461 // If all of the other operands were loop invariant, we are done.
3462 if (Ops.size() == 1) return NewRec;
3463
3464 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3465 for (unsigned i = 0;; ++i)
3466 if (Ops[i] == AddRec) {
3467 Ops[i] = NewRec;
3468 break;
3469 }
3470 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3471 }
3472
3473 // Okay, if there weren't any loop invariants to be folded, check to see
3474 // if there are multiple AddRec's with the same loop induction variable
3475 // being multiplied together. If so, we can fold them.
3476
3477 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3478 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3479 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3480 // ]]],+,...up to x=2n}.
3481 // Note that the arguments to choose() are always integers with values
3482 // known at compile time, never SCEV objects.
3483 //
3484 // The implementation avoids pointless extra computations when the two
3485 // addrec's are of different length (mathematically, it's equivalent to
3486 // an infinite stream of zeros on the right).
3487 bool OpsModified = false;
3488 for (unsigned OtherIdx = Idx+1;
3489 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3490 ++OtherIdx) {
3491 const SCEVAddRecExpr *OtherAddRec =
3492 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3493 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3494 continue;
3495
3496 // Limit max number of arguments to avoid creation of unreasonably big
3497 // SCEVAddRecs with very complex operands.
3498 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3499 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3500 continue;
3501
3502 bool Overflow = false;
3503 Type *Ty = AddRec->getType();
3504 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3505 SmallVector<SCEVUse, 7> AddRecOps;
3506 for (int x = 0, xe = AddRec->getNumOperands() +
3507 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3509 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3510 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3511 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3512 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3513 z < ze && !Overflow; ++z) {
3514 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3515 uint64_t Coeff;
3516 if (LargerThan64Bits)
3517 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3518 else
3519 Coeff = Coeff1*Coeff2;
3520 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3521 const SCEV *Term1 = AddRec->getOperand(y-z);
3522 const SCEV *Term2 = OtherAddRec->getOperand(z);
3523 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3524 SCEV::FlagAnyWrap, Depth + 1));
3525 }
3526 }
3527 if (SumOps.empty())
3528 SumOps.push_back(getZero(Ty));
3529 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3530 }
3531 if (!Overflow) {
3532 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3534 if (Ops.size() == 2) return NewAddRec;
3535 Ops[Idx] = NewAddRec;
3536 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3537 OpsModified = true;
3538 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3539 if (!AddRec)
3540 break;
3541 }
3542 }
3543 if (OpsModified)
3544 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3545
3546 // Otherwise couldn't fold anything into this recurrence. Move onto the
3547 // next one.
3548 }
3549
3550 // Okay, it looks like we really DO need an mul expr. Check to see if we
3551 // already have one, otherwise create a new one.
3552 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3553}
3554
3555/// Represents an unsigned remainder expression based on unsigned division.
3557 assert(getEffectiveSCEVType(LHS->getType()) ==
3558 getEffectiveSCEVType(RHS->getType()) &&
3559 "SCEVURemExpr operand types don't match!");
3560
3561 // Short-circuit easy cases
3562 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3563 // If constant is one, the result is trivial
3564 if (RHSC->getValue()->isOne())
3565 return getZero(LHS->getType()); // X urem 1 --> 0
3566
3567 // If constant is a power of two, fold into a zext(trunc(LHS)).
3568 if (RHSC->getAPInt().isPowerOf2()) {
3569 Type *FullTy = LHS->getType();
3570 Type *TruncTy =
3571 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3572 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3573 }
3574 }
3575
3576 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3577 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3578 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3579 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3580}
3581
3582/// Get a canonical unsigned division expression, or something simpler if
3583/// possible.
3585 assert(!LHS->getType()->isPointerTy() &&
3586 "SCEVUDivExpr operand can't be pointer!");
3587 assert(LHS->getType() == RHS->getType() &&
3588 "SCEVUDivExpr operand types don't match!");
3589
3591 ID.AddInteger(scUDivExpr);
3592 ID.AddPointer(LHS);
3593 ID.AddPointer(RHS);
3594 void *IP = nullptr;
3595 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3596 return S;
3597
3598 // 0 udiv Y == 0
3599 if (match(LHS, m_scev_Zero()))
3600 return LHS;
3601
3602 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3603 if (RHSC->getValue()->isOne())
3604 return LHS; // X udiv 1 --> x
3605 // If the denominator is zero, the result of the udiv is undefined. Don't
3606 // try to analyze it, because the resolution chosen here may differ from
3607 // the resolution chosen in other parts of the compiler.
3608 if (!RHSC->getValue()->isZero()) {
3609 // Determine if the division can be folded into the operands of
3610 // its operands.
3611 // TODO: Generalize this to non-constants by using known-bits information.
3612 Type *Ty = LHS->getType();
3613 unsigned LZ = RHSC->getAPInt().countl_zero();
3614 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3615 // For non-power-of-two values, effectively round the value up to the
3616 // nearest power of two.
3617 if (!RHSC->getAPInt().isPowerOf2())
3618 ++MaxShiftAmt;
3619 IntegerType *ExtTy =
3620 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3621 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3622 if (const SCEVConstant *Step =
3623 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3624 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3625 const APInt &StepInt = Step->getAPInt();
3626 const APInt &DivInt = RHSC->getAPInt();
3627 if (!StepInt.urem(DivInt) &&
3628 getZeroExtendExpr(AR, ExtTy) ==
3629 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3630 getZeroExtendExpr(Step, ExtTy),
3631 AR->getLoop(), SCEV::FlagAnyWrap)) {
3632 SmallVector<SCEVUse, 4> Operands;
3633 for (const SCEV *Op : AR->operands())
3634 Operands.push_back(getUDivExpr(Op, RHS));
3635 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3636 }
3637 /// Get a canonical UDivExpr for a recurrence.
3638 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3639 const APInt *StartRem;
3640 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3641 m_scev_APInt(StartRem))) {
3642 bool NoWrap =
3643 getZeroExtendExpr(AR, ExtTy) ==
3644 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3645 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3647
3648 // With N <= C and both N, C as powers-of-2, the transformation
3649 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3650 // if wrapping occurs, as the division results remain equivalent for
3651 // all offsets in [[(X - X%N), X).
3652 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3653 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3654 // Only fold if the subtraction can be folded in the start
3655 // expression.
3656 const SCEV *NewStart =
3657 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3658 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3659 !isa<SCEVAddExpr>(NewStart)) {
3660 const SCEV *NewLHS =
3661 getAddRecExpr(NewStart, Step, AR->getLoop(),
3662 NoWrap ? SCEV::FlagNW : SCEV::FlagAnyWrap);
3663 if (LHS != NewLHS) {
3664 LHS = NewLHS;
3665
3666 // Reset the ID to include the new LHS, and check if it is
3667 // already cached.
3668 ID.clear();
3669 ID.AddInteger(scUDivExpr);
3670 ID.AddPointer(LHS);
3671 ID.AddPointer(RHS);
3672 IP = nullptr;
3673 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3674 return S;
3675 }
3676 }
3677 }
3678 }
3679 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3680 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3681 SmallVector<SCEVUse, 4> Operands;
3682 for (const SCEV *Op : M->operands())
3683 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3684 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) {
3685 // Find an operand that's safely divisible.
3686 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3687 const SCEV *Op = M->getOperand(i);
3688 const SCEV *Div = getUDivExpr(Op, RHSC);
3689 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3690 Operands = SmallVector<SCEVUse, 4>(M->operands());
3691 Operands[i] = Div;
3692 return getMulExpr(Operands);
3693 }
3694 }
3695
3696 // Even if it's not divisible, try to remove a common factor.
3697 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3698 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3699 RHSC->getAPInt());
3700 if (!Factor.isIntN(1)) {
3701 SmallVector<SCEVUse, 2> NewOperands;
3702 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3703 append_range(NewOperands, M->operands().drop_front());
3704 const SCEV *NewMul = getMulExpr(NewOperands);
3705 return getUDivExpr(NewMul,
3706 getConstant(RHSC->getAPInt().udiv(Factor)));
3707 }
3708 }
3709 }
3710 }
3711
3712 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3713 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3714 if (auto *DivisorConstant =
3715 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3716 bool Overflow = false;
3717 APInt NewRHS =
3718 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3719 if (Overflow) {
3720 return getConstant(RHSC->getType(), 0, false);
3721 }
3722 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3723 }
3724 }
3725
3726 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3727 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3728 SmallVector<SCEVUse, 4> Operands;
3729 for (const SCEV *Op : A->operands())
3730 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3731 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3732 Operands.clear();
3733 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3734 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3735 if (isa<SCEVUDivExpr>(Op) ||
3736 getMulExpr(Op, RHS) != A->getOperand(i))
3737 break;
3738 Operands.push_back(Op);
3739 }
3740 if (Operands.size() == A->getNumOperands())
3741 return getAddExpr(Operands);
3742 }
3743 }
3744
3745 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3746 // This is an idiom for rounding A up to the next multiple of N, where A
3747 // is aready known to be a multiple of M. In this case, instcombine can
3748 // see that some low bits of the added constant are unused, so can clear
3749 // them, but we want to canonicalise to set the low bits. This makes the
3750 // pattern easier to match, without needing to check for known bits in
3751 // A*M.
3752 const APInt &N = RHSC->getAPInt();
3753 const APInt *NMinusM, *M;
3754 const SCEV *A;
3755 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3756 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3757 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3758 *NMinusM == N - *M) {
3759 return getUDivExpr(
3761 RHS);
3762 }
3763 }
3764
3765 // Fold if both operands are constant.
3766 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3767 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3768 }
3769 }
3770
3771 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3772 const APInt *NegC, *C;
3773 if (match(LHS,
3776 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3777 return getZero(LHS->getType());
3778
3779 // (%a * %b)<nuw> / %b -> %a
3780 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3781 if (Mul && Mul->hasNoUnsignedWrap()) {
3782 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3783 if (Mul->getOperand(i) == RHS) {
3784 SmallVector<SCEVUse, 2> Operands;
3785 append_range(Operands, Mul->operands().take_front(i));
3786 append_range(Operands, Mul->operands().drop_front(i + 1));
3787 return getMulExpr(Operands);
3788 }
3789 }
3790 }
3791
3792 // TODO: Generalize to handle any common factors.
3793 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3794 const SCEV *NewLHS, *NewRHS;
3795 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3796 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3797 return getUDivExpr(NewLHS, NewRHS);
3798
3799 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3800 // changes). Make sure we get a new one.
3801 IP = nullptr;
3802 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3803 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3804 LHS, RHS);
3805 UniqueSCEVs.InsertNode(S, IP);
3806 S->computeAndSetCanonical(*this);
3807 registerUser(S, ArrayRef<SCEVUse>({LHS, RHS}));
3808 return S;
3809}
3810
3811APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3812 APInt A = C1->getAPInt().abs();
3813 APInt B = C2->getAPInt().abs();
3814 uint32_t ABW = A.getBitWidth();
3815 uint32_t BBW = B.getBitWidth();
3816
3817 if (ABW > BBW)
3818 B = B.zext(ABW);
3819 else if (ABW < BBW)
3820 A = A.zext(BBW);
3821
3822 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3823}
3824
3825/// Get a canonical unsigned division expression, or something simpler if
3826/// possible. There is no representation for an exact udiv in SCEV IR, but we
3827/// can attempt to optimize it prior to construction.
3829 // Currently there is no exact specific logic.
3830
3831 return getUDivExpr(LHS, RHS);
3832}
3833
3834/// Get an add recurrence expression for the specified loop. Simplify the
3835/// expression as much as possible.
3837 const Loop *L,
3838 SCEV::NoWrapFlags Flags) {
3839 SmallVector<SCEVUse, 4> Operands;
3840 Operands.push_back(Start);
3841 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3842 if (StepChrec->getLoop() == L) {
3843 append_range(Operands, StepChrec->operands());
3844 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3845 }
3846
3847 Operands.push_back(Step);
3848 return getAddRecExpr(Operands, L, Flags);
3849}
3850
3851/// Get an add recurrence expression for the specified loop. Simplify the
3852/// expression as much as possible.
3854 const Loop *L,
3855 SCEV::NoWrapFlags Flags) {
3856 if (Operands.size() == 1) return Operands[0];
3857#ifndef NDEBUG
3858 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3859 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3860 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3861 "SCEVAddRecExpr operand types don't match!");
3862 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3863 }
3864 for (const SCEV *Op : Operands)
3866 "SCEVAddRecExpr operand is not available at loop entry!");
3867#endif
3868
3869 if (Operands.back()->isZero()) {
3870 Operands.pop_back();
3871 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3872 }
3873
3874 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3875 // use that information to infer NUW and NSW flags. However, computing a
3876 // BE count requires calling getAddRecExpr, so we may not yet have a
3877 // meaningful BE count at this point (and if we don't, we'd be stuck
3878 // with a SCEVCouldNotCompute as the cached BE count).
3879
3880 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3881
3882 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3883 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3884 const Loop *NestedLoop = NestedAR->getLoop();
3885 if (L->contains(NestedLoop)
3886 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3887 : (!NestedLoop->contains(L) &&
3888 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3889 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3890 Operands[0] = NestedAR->getStart();
3891 // AddRecs require their operands be loop-invariant with respect to their
3892 // loops. Don't perform this transformation if it would break this
3893 // requirement.
3894 bool AllInvariant = all_of(
3895 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3896
3897 if (AllInvariant) {
3898 // Create a recurrence for the outer loop with the same step size.
3899 //
3900 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3901 // inner recurrence has the same property.
3902 SCEV::NoWrapFlags OuterFlags =
3903 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3904
3905 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3906 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3907 return isLoopInvariant(Op, NestedLoop);
3908 });
3909
3910 if (AllInvariant) {
3911 // Ok, both add recurrences are valid after the transformation.
3912 //
3913 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3914 // the outer recurrence has the same property.
3915 SCEV::NoWrapFlags InnerFlags =
3916 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3917 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3918 }
3919 }
3920 // Reset Operands to its original state.
3921 Operands[0] = NestedAR;
3922 }
3923 }
3924
3925 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3926 // already have one, otherwise create a new one.
3927 return getOrCreateAddRecExpr(Operands, L, Flags);
3928}
3929
3931 ArrayRef<SCEVUse> IndexExprs) {
3932 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3933 // getSCEV(Base)->getType() has the same address space as Base->getType()
3934 // because SCEV::getType() preserves the address space.
3935 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3936 if (NW != GEPNoWrapFlags::none()) {
3937 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3938 // but to do that, we have to ensure that said flag is valid in the entire
3939 // defined scope of the SCEV.
3940 // TODO: non-instructions have global scope. We might be able to prove
3941 // some global scope cases
3942 auto *GEPI = dyn_cast<Instruction>(GEP);
3943 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3944 NW = GEPNoWrapFlags::none();
3945 }
3946
3947 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3948}
3949
3951 ArrayRef<SCEVUse> IndexExprs,
3952 Type *SrcElementTy, GEPNoWrapFlags NW) {
3954 if (NW.hasNoUnsignedSignedWrap())
3955 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3956 if (NW.hasNoUnsignedWrap())
3957 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3958
3959 Type *CurTy = BaseExpr->getType();
3960 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3961 bool FirstIter = true;
3963 for (SCEVUse IndexExpr : IndexExprs) {
3964 // Compute the (potentially symbolic) offset in bytes for this index.
3965 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3966 // For a struct, add the member offset.
3967 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3968 unsigned FieldNo = Index->getZExtValue();
3969 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3970 Offsets.push_back(FieldOffset);
3971
3972 // Update CurTy to the type of the field at Index.
3973 CurTy = STy->getTypeAtIndex(Index);
3974 } else {
3975 // Update CurTy to its element type.
3976 if (FirstIter) {
3977 assert(isa<PointerType>(CurTy) &&
3978 "The first index of a GEP indexes a pointer");
3979 CurTy = SrcElementTy;
3980 FirstIter = false;
3981 } else {
3983 }
3984 // For an array, add the element offset, explicitly scaled.
3985 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3986 // Getelementptr indices are signed.
3987 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3988
3989 // Multiply the index by the element size to compute the element offset.
3990 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3991 Offsets.push_back(LocalOffset);
3992 }
3993 }
3994
3995 // Handle degenerate case of GEP without offsets.
3996 if (Offsets.empty())
3997 return BaseExpr;
3998
3999 // Add the offsets together, assuming nsw if inbounds.
4000 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
4001 // Add the base address and the offset. We cannot use the nsw flag, as the
4002 // base address is unsigned. However, if we know that the offset is
4003 // non-negative, we can use nuw.
4004 bool NUW = NW.hasNoUnsignedWrap() ||
4007 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
4008 assert(BaseExpr->getType() == GEPExpr->getType() &&
4009 "GEP should not change type mid-flight.");
4010 return GEPExpr;
4011}
4012
4013SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
4016 ID.AddInteger(SCEVType);
4017 for (const SCEV *Op : Ops)
4018 ID.AddPointer(Op);
4019 void *IP = nullptr;
4020 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4021}
4022
4023SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
4026 ID.AddInteger(SCEVType);
4027 for (const SCEV *Op : Ops)
4028 ID.AddPointer(Op);
4029 void *IP = nullptr;
4030 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4031}
4032
4033const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
4035 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
4036}
4037
4040 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
4041 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4042 if (Ops.size() == 1) return Ops[0];
4043#ifndef NDEBUG
4044 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4045 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4046 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4047 "Operand types don't match!");
4048 assert(Ops[0]->getType()->isPointerTy() ==
4049 Ops[i]->getType()->isPointerTy() &&
4050 "min/max should be consistently pointerish");
4051 }
4052#endif
4053
4054 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
4055 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
4056
4057 const SCEV *Folded = constantFoldAndGroupOps(
4058 *this, LI, DT, Ops,
4059 [&](const APInt &C1, const APInt &C2) {
4060 switch (Kind) {
4061 case scSMaxExpr:
4062 return APIntOps::smax(C1, C2);
4063 case scSMinExpr:
4064 return APIntOps::smin(C1, C2);
4065 case scUMaxExpr:
4066 return APIntOps::umax(C1, C2);
4067 case scUMinExpr:
4068 return APIntOps::umin(C1, C2);
4069 default:
4070 llvm_unreachable("Unknown SCEV min/max opcode");
4071 }
4072 },
4073 [&](const APInt &C) {
4074 // identity
4075 if (IsMax)
4076 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
4077 else
4078 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
4079 },
4080 [&](const APInt &C) {
4081 // absorber
4082 if (IsMax)
4083 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
4084 else
4085 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
4086 });
4087 if (Folded)
4088 return Folded;
4089
4090 // Check if we have created the same expression before.
4091 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
4092 return S;
4093 }
4094
4095 // Find the first operation of the same kind
4096 unsigned Idx = 0;
4097 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
4098 ++Idx;
4099
4100 // Check to see if one of the operands is of the same kind. If so, expand its
4101 // operands onto our operand list, and recurse to simplify.
4102 if (Idx < Ops.size()) {
4103 bool DeletedAny = false;
4104 while (Ops[Idx]->getSCEVType() == Kind) {
4105 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
4106 Ops.erase(Ops.begin()+Idx);
4107 append_range(Ops, SMME->operands());
4108 DeletedAny = true;
4109 }
4110
4111 if (DeletedAny)
4112 return getMinMaxExpr(Kind, Ops);
4113 }
4114
4115 // Okay, check to see if the same value occurs in the operand list twice. If
4116 // so, delete one. Since we sorted the list, these values are required to
4117 // be adjacent.
4122 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
4123 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
4124 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
4125 if (Ops[i] == Ops[i + 1] ||
4126 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
4127 // X op Y op Y --> X op Y
4128 // X op Y --> X, if we know X, Y are ordered appropriately
4129 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
4130 --i;
4131 --e;
4132 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
4133 Ops[i + 1])) {
4134 // X op Y --> Y, if we know X, Y are ordered appropriately
4135 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
4136 --i;
4137 --e;
4138 }
4139 }
4140
4141 if (Ops.size() == 1) return Ops[0];
4142
4143 assert(!Ops.empty() && "Reduced smax down to nothing!");
4144
4145 // Okay, it looks like we really DO need an expr. Check to see if we
4146 // already have one, otherwise create a new one.
4148 ID.AddInteger(Kind);
4149 for (const SCEV *Op : Ops)
4150 ID.AddPointer(Op);
4151 void *IP = nullptr;
4152 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4153 if (ExistingSCEV)
4154 return ExistingSCEV;
4155 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4157 SCEV *S = new (SCEVAllocator)
4158 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4159
4160 UniqueSCEVs.InsertNode(S, IP);
4161 S->computeAndSetCanonical(*this);
4162 registerUser(S, Ops);
4163 return S;
4164}
4165
4166namespace {
4167
4168class SCEVSequentialMinMaxDeduplicatingVisitor final
4169 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
4170 std::optional<const SCEV *>> {
4171 using RetVal = std::optional<const SCEV *>;
4173
4174 ScalarEvolution &SE;
4175 const SCEVTypes RootKind; // Must be a sequential min/max expression.
4176 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
4178
4179 bool canRecurseInto(SCEVTypes Kind) const {
4180 // We can only recurse into the SCEV expression of the same effective type
4181 // as the type of our root SCEV expression.
4182 return RootKind == Kind || NonSequentialRootKind == Kind;
4183 };
4184
4185 RetVal visitAnyMinMaxExpr(const SCEV *S) {
4187 "Only for min/max expressions.");
4188 SCEVTypes Kind = S->getSCEVType();
4189
4190 if (!canRecurseInto(Kind))
4191 return S;
4192
4193 auto *NAry = cast<SCEVNAryExpr>(S);
4194 SmallVector<SCEVUse> NewOps;
4195 bool Changed = visit(Kind, NAry->operands(), NewOps);
4196
4197 if (!Changed)
4198 return S;
4199 if (NewOps.empty())
4200 return std::nullopt;
4201
4203 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4204 : SE.getMinMaxExpr(Kind, NewOps);
4205 }
4206
4207 RetVal visit(const SCEV *S) {
4208 // Has the whole operand been seen already?
4209 if (!SeenOps.insert(S).second)
4210 return std::nullopt;
4211 return Base::visit(S);
4212 }
4213
4214public:
4215 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4216 SCEVTypes RootKind)
4217 : SE(SE), RootKind(RootKind),
4218 NonSequentialRootKind(
4219 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4220 RootKind)) {}
4221
4222 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4223 SmallVectorImpl<SCEVUse> &NewOps) {
4224 bool Changed = false;
4226 Ops.reserve(OrigOps.size());
4227
4228 for (const SCEV *Op : OrigOps) {
4229 RetVal NewOp = visit(Op);
4230 if (NewOp != Op)
4231 Changed = true;
4232 if (NewOp)
4233 Ops.emplace_back(*NewOp);
4234 }
4235
4236 if (Changed)
4237 NewOps = std::move(Ops);
4238 return Changed;
4239 }
4240
4241 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4242
4243 RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4244
4245 RetVal visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) { return Expr; }
4246
4247 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
4248
4249 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4250
4251 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4252
4253 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4254
4255 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4256
4257 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4258
4259 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4260
4261 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4262
4263 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4264 return visitAnyMinMaxExpr(Expr);
4265 }
4266
4267 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4268 return visitAnyMinMaxExpr(Expr);
4269 }
4270
4271 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4272 return visitAnyMinMaxExpr(Expr);
4273 }
4274
4275 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4276 return visitAnyMinMaxExpr(Expr);
4277 }
4278
4279 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4280 return visitAnyMinMaxExpr(Expr);
4281 }
4282
4283 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4284
4285 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4286};
4287
4288} // namespace
4289
4291 switch (Kind) {
4292 case scConstant:
4293 case scVScale:
4294 case scTruncate:
4295 case scZeroExtend:
4296 case scSignExtend:
4297 case scPtrToAddr:
4298 case scPtrToInt:
4299 case scAddExpr:
4300 case scMulExpr:
4301 case scUDivExpr:
4302 case scAddRecExpr:
4303 case scUMaxExpr:
4304 case scSMaxExpr:
4305 case scUMinExpr:
4306 case scSMinExpr:
4307 case scUnknown:
4308 // If any operand is poison, the whole expression is poison.
4309 return true;
4311 // FIXME: if the *first* operand is poison, the whole expression is poison.
4312 return false; // Pessimistically, say that it does not propagate poison.
4313 case scCouldNotCompute:
4314 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4315 }
4316 llvm_unreachable("Unknown SCEV kind!");
4317}
4318
4319namespace {
4320// The only way poison may be introduced in a SCEV expression is from a
4321// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4322// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4323// introduce poison -- they encode guaranteed, non-speculated knowledge.
4324//
4325// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4326// with the notable exception of umin_seq, where only poison from the first
4327// operand is (unconditionally) propagated.
4328struct SCEVPoisonCollector {
4329 bool LookThroughMaybePoisonBlocking;
4330 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4331 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4332 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4333
4334 bool follow(const SCEV *S) {
4335 if (!LookThroughMaybePoisonBlocking &&
4337 return false;
4338
4339 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4340 if (!isGuaranteedNotToBePoison(SU->getValue()))
4341 MaybePoison.insert(SU);
4342 }
4343 return true;
4344 }
4345 bool isDone() const { return false; }
4346};
4347} // namespace
4348
4349/// Return true if V is poison given that AssumedPoison is already poison.
4350static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4351 // First collect all SCEVs that might result in AssumedPoison to be poison.
4352 // We need to look through potentially poison-blocking operations here,
4353 // because we want to find all SCEVs that *might* result in poison, not only
4354 // those that are *required* to.
4355 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4356 visitAll(AssumedPoison, PC1);
4357
4358 // AssumedPoison is never poison. As the assumption is false, the implication
4359 // is true. Don't bother walking the other SCEV in this case.
4360 if (PC1.MaybePoison.empty())
4361 return true;
4362
4363 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4364 // as well. We cannot look through potentially poison-blocking operations
4365 // here, as their arguments only *may* make the result poison.
4366 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4367 visitAll(S, PC2);
4368
4369 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4370 // it will also make S poison by being part of PC2.MaybePoison.
4371 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4372}
4373
4375 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4376 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4377 visitAll(S, PC);
4378 for (const SCEVUnknown *SU : PC.MaybePoison)
4379 Result.insert(SU->getValue());
4380}
4381
4383 const SCEV *S, Instruction *I,
4384 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4385 // If the instruction cannot be poison, it's always safe to reuse.
4387 return true;
4388
4389 // Otherwise, it is possible that I is more poisonous that S. Collect the
4390 // poison-contributors of S, and then check whether I has any additional
4391 // poison-contributors. Poison that is contributed through poison-generating
4392 // flags is handled by dropping those flags instead.
4394 getPoisonGeneratingValues(PoisonVals, S);
4395
4396 SmallVector<Value *> Worklist;
4398 Worklist.push_back(I);
4399 while (!Worklist.empty()) {
4400 Value *V = Worklist.pop_back_val();
4401 if (!Visited.insert(V).second)
4402 continue;
4403
4404 // Avoid walking large instruction graphs.
4405 if (Visited.size() > 16)
4406 return false;
4407
4408 // Either the value can't be poison, or the S would also be poison if it
4409 // is.
4410 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4411 continue;
4412
4413 auto *I = dyn_cast<Instruction>(V);
4414 if (!I)
4415 return false;
4416
4417 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4418 // can't replace an arbitrary add with disjoint or, even if we drop the
4419 // flag. We would need to convert the or into an add.
4420 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4421 if (PDI->isDisjoint())
4422 return false;
4423
4424 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4425 // because SCEV currently assumes it can't be poison. Remove this special
4426 // case once we proper model when vscale can be poison.
4427 if (auto *II = dyn_cast<IntrinsicInst>(I);
4428 II && II->getIntrinsicID() == Intrinsic::vscale)
4429 continue;
4430
4431 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4432 return false;
4433
4434 // If the instruction can't create poison, we can recurse to its operands.
4435 if (I->hasPoisonGeneratingAnnotations())
4436 DropPoisonGeneratingInsts.push_back(I);
4437
4438 llvm::append_range(Worklist, I->operands());
4439 }
4440 return true;
4441}
4442
4443const SCEV *
4446 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4447 "Not a SCEVSequentialMinMaxExpr!");
4448 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4449 if (Ops.size() == 1)
4450 return Ops[0];
4451#ifndef NDEBUG
4452 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4453 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4454 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4455 "Operand types don't match!");
4456 assert(Ops[0]->getType()->isPointerTy() ==
4457 Ops[i]->getType()->isPointerTy() &&
4458 "min/max should be consistently pointerish");
4459 }
4460#endif
4461
4462 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4463 // so we can *NOT* do any kind of sorting of the expressions!
4464
4465 // Check if we have created the same expression before.
4466 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4467 return S;
4468
4469 // FIXME: there are *some* simplifications that we can do here.
4470
4471 // Keep only the first instance of an operand.
4472 {
4473 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4474 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4475 if (Changed)
4476 return getSequentialMinMaxExpr(Kind, Ops);
4477 }
4478
4479 // Check to see if one of the operands is of the same kind. If so, expand its
4480 // operands onto our operand list, and recurse to simplify.
4481 {
4482 unsigned Idx = 0;
4483 bool DeletedAny = false;
4484 while (Idx < Ops.size()) {
4485 if (Ops[Idx]->getSCEVType() != Kind) {
4486 ++Idx;
4487 continue;
4488 }
4489 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4490 Ops.erase(Ops.begin() + Idx);
4491 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4492 SMME->operands().end());
4493 DeletedAny = true;
4494 }
4495
4496 if (DeletedAny)
4497 return getSequentialMinMaxExpr(Kind, Ops);
4498 }
4499
4500 const SCEV *SaturationPoint;
4502 switch (Kind) {
4504 SaturationPoint = getZero(Ops[0]->getType());
4505 Pred = ICmpInst::ICMP_ULE;
4506 break;
4507 default:
4508 llvm_unreachable("Not a sequential min/max type.");
4509 }
4510
4511 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4512 if (!isGuaranteedNotToCauseUB(Ops[i]))
4513 continue;
4514 // We can replace %x umin_seq %y with %x umin %y if either:
4515 // * %y being poison implies %x is also poison.
4516 // * %x cannot be the saturating value (e.g. zero for umin).
4517 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4518 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4519 SaturationPoint)) {
4520 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4521 Ops[i - 1] = getMinMaxExpr(
4523 SeqOps);
4524 Ops.erase(Ops.begin() + i);
4525 return getSequentialMinMaxExpr(Kind, Ops);
4526 }
4527 // Fold %x umin_seq %y to %x if %x ule %y.
4528 // TODO: We might be able to prove the predicate for a later operand.
4529 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4530 Ops.erase(Ops.begin() + i);
4531 return getSequentialMinMaxExpr(Kind, Ops);
4532 }
4533 }
4534
4535 // Okay, it looks like we really DO need an expr. Check to see if we
4536 // already have one, otherwise create a new one.
4538 ID.AddInteger(Kind);
4539 for (const SCEV *Op : Ops)
4540 ID.AddPointer(Op);
4541 void *IP = nullptr;
4542 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4543 if (ExistingSCEV)
4544 return ExistingSCEV;
4545
4546 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4548 SCEV *S = new (SCEVAllocator)
4549 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4550
4551 UniqueSCEVs.InsertNode(S, IP);
4552 S->computeAndSetCanonical(*this);
4553 registerUser(S, Ops);
4554 return S;
4555}
4556
4561
4565
4570
4574
4579
4583
4585 bool Sequential) {
4586 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4587 return getUMinExpr(Ops, Sequential);
4588}
4589
4595
4596const SCEV *
4598 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4599 if (Size.isScalable())
4600 Res = getMulExpr(Res, getVScale(IntTy));
4601 return Res;
4602}
4603
4605 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4606}
4607
4609 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4610}
4611
4613 StructType *STy,
4614 unsigned FieldNo) {
4615 // We can bypass creating a target-independent constant expression and then
4616 // folding it back into a ConstantInt. This is just a compile-time
4617 // optimization.
4618 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4619 assert(!SL->getSizeInBits().isScalable() &&
4620 "Cannot get offset for structure containing scalable vector types");
4621 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4622}
4623
4625 // Don't attempt to do anything other than create a SCEVUnknown object
4626 // here. createSCEV only calls getUnknown after checking for all other
4627 // interesting possibilities, and any other code that calls getUnknown
4628 // is doing so in order to hide a value from SCEV canonicalization.
4629
4631 ID.AddInteger(scUnknown);
4632 ID.AddPointer(V);
4633 void *IP = nullptr;
4634 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4635 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4636 "Stale SCEVUnknown in uniquing map!");
4637 return S;
4638 }
4639 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4640 FirstUnknown);
4641 FirstUnknown = cast<SCEVUnknown>(S);
4642 UniqueSCEVs.InsertNode(S, IP);
4643 S->computeAndSetCanonical(*this);
4644 return S;
4645}
4646
4647//===----------------------------------------------------------------------===//
4648// Basic SCEV Analysis and PHI Idiom Recognition Code
4649//
4650
4651/// Test if values of the given type are analyzable within the SCEV
4652/// framework. This primarily includes integer types, and it can optionally
4653/// include pointer types if the ScalarEvolution class has access to
4654/// target-specific information.
4656 // Integers and pointers are always SCEVable.
4657 return Ty->isIntOrPtrTy();
4658}
4659
4660/// Return the size in bits of the specified type, for which isSCEVable must
4661/// return true.
4663 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4664 if (Ty->isPointerTy())
4666 return getDataLayout().getTypeSizeInBits(Ty);
4667}
4668
4669/// Return a type with the same bitwidth as the given type and which represents
4670/// how SCEV will treat the given type, for which isSCEVable must return
4671/// true. For pointer types, this is the pointer index sized integer type.
4673 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4674
4675 if (Ty->isIntegerTy())
4676 return Ty;
4677
4678 // The only other support type is pointer.
4679 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4680 return getDataLayout().getIndexType(Ty);
4681}
4682
4684 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4685}
4686
4688 const SCEV *B) {
4689 /// For a valid use point to exist, the defining scope of one operand
4690 /// must dominate the other.
4691 bool PreciseA, PreciseB;
4692 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4693 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4694 if (!PreciseA || !PreciseB)
4695 // Can't tell.
4696 return false;
4697 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4698 DT.dominates(ScopeB, ScopeA);
4699}
4700
4702 return CouldNotCompute.get();
4703}
4704
4705bool ScalarEvolution::checkValidity(const SCEV *S) const {
4706 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4707 auto *SU = dyn_cast<SCEVUnknown>(S);
4708 return SU && SU->getValue() == nullptr;
4709 });
4710
4711 return !ContainsNulls;
4712}
4713
4715 HasRecMapType::iterator I = HasRecMap.find(S);
4716 if (I != HasRecMap.end())
4717 return I->second;
4718
4719 bool FoundAddRec =
4720 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4721 HasRecMap.insert({S, FoundAddRec});
4722 return FoundAddRec;
4723}
4724
4725/// Return the ValueOffsetPair set for \p S. \p S can be represented
4726/// by the value and offset from any ValueOffsetPair in the set.
4727ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4728 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4729 if (SI == ExprValueMap.end())
4730 return {};
4731 return SI->second.getArrayRef();
4732}
4733
4734/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4735/// cannot be used separately. eraseValueFromMap should be used to remove
4736/// V from ValueExprMap and ExprValueMap at the same time.
4737void ScalarEvolution::eraseValueFromMap(Value *V) {
4738 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4739 if (I != ValueExprMap.end()) {
4740 auto EVIt = ExprValueMap.find(I->second);
4741 bool Removed = EVIt->second.remove(V);
4742 (void) Removed;
4743 assert(Removed && "Value not in ExprValueMap?");
4744 ValueExprMap.erase(I);
4745 }
4746}
4747
4748void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4749 // A recursive query may have already computed the SCEV. It should be
4750 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4751 // inferred nowrap flags.
4752 auto It = ValueExprMap.find_as(V);
4753 if (It == ValueExprMap.end()) {
4754 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4755 ExprValueMap[S].insert(V);
4756 }
4757}
4758
4759/// Return an existing SCEV if it exists, otherwise analyze the expression and
4760/// create a new one.
4762 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4763
4764 if (const SCEV *S = getExistingSCEV(V))
4765 return S;
4766 return createSCEVIter(V);
4767}
4768
4770 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4771
4772 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4773 if (I != ValueExprMap.end()) {
4774 const SCEV *S = I->second;
4775 assert(checkValidity(S) &&
4776 "existing SCEV has not been properly invalidated");
4777 return S;
4778 }
4779 return nullptr;
4780}
4781
4782/// Return a SCEV corresponding to -V = -1*V
4784 SCEV::NoWrapFlags Flags) {
4785 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4786 return getConstant(
4787 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4788
4789 Type *Ty = V->getType();
4790 Ty = getEffectiveSCEVType(Ty);
4791 return getMulExpr(V, getMinusOne(Ty), Flags);
4792}
4793
4794/// If Expr computes ~A, return A else return nullptr
4795static const SCEV *MatchNotExpr(const SCEV *Expr) {
4796 const SCEV *MulOp;
4797 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4798 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4799 return MulOp;
4800 return nullptr;
4801}
4802
4803/// Return a SCEV corresponding to ~V = -1-V
4805 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4806
4807 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4808 return getConstant(
4809 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4810
4811 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4812 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4813 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4814 SmallVector<SCEVUse, 2> MatchedOperands;
4815 for (const SCEV *Operand : MME->operands()) {
4816 const SCEV *Matched = MatchNotExpr(Operand);
4817 if (!Matched)
4818 return (const SCEV *)nullptr;
4819 MatchedOperands.push_back(Matched);
4820 }
4821 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4822 MatchedOperands);
4823 };
4824 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4825 return Replaced;
4826 }
4827
4828 Type *Ty = V->getType();
4829 Ty = getEffectiveSCEVType(Ty);
4830 return getMinusSCEV(getMinusOne(Ty), V);
4831}
4832
4834 assert(P->getType()->isPointerTy());
4835
4836 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4837 // The base of an AddRec is the first operand.
4838 SmallVector<SCEVUse> Ops{AddRec->operands()};
4839 Ops[0] = removePointerBase(Ops[0]);
4840 // Don't try to transfer nowrap flags for now. We could in some cases
4841 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4842 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4843 }
4844 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4845 // The base of an Add is the pointer operand.
4846 SmallVector<SCEVUse> Ops{Add->operands()};
4847 SCEVUse *PtrOp = nullptr;
4848 for (SCEVUse &AddOp : Ops) {
4849 if (AddOp->getType()->isPointerTy()) {
4850 assert(!PtrOp && "Cannot have multiple pointer ops");
4851 PtrOp = &AddOp;
4852 }
4853 }
4854 *PtrOp = removePointerBase(*PtrOp);
4855 // Don't try to transfer nowrap flags for now. We could in some cases
4856 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4857 return getAddExpr(Ops);
4858 }
4859 // Any other expression must be a pointer base.
4860 return getZero(P->getType());
4861}
4862
4864 SCEV::NoWrapFlags Flags,
4865 unsigned Depth) {
4866 // Fast path: X - X --> 0.
4867 if (LHS == RHS)
4868 return getZero(LHS->getType());
4869
4870 // If we subtract two pointers with different pointer bases, bail.
4871 // Eventually, we're going to add an assertion to getMulExpr that we
4872 // can't multiply by a pointer.
4873 if (RHS->getType()->isPointerTy()) {
4874 if (!LHS->getType()->isPointerTy() ||
4875 getPointerBase(LHS) != getPointerBase(RHS))
4876 return getCouldNotCompute();
4877 LHS = removePointerBase(LHS);
4878 RHS = removePointerBase(RHS);
4879 }
4880
4881 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4882 // makes it so that we cannot make much use of NUW.
4883 auto AddFlags = SCEV::FlagAnyWrap;
4884 const bool RHSIsNotMinSigned =
4886 if (hasFlags(Flags, SCEV::FlagNSW)) {
4887 // Let M be the minimum representable signed value. Then (-1)*RHS
4888 // signed-wraps if and only if RHS is M. That can happen even for
4889 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4890 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4891 // (-1)*RHS, we need to prove that RHS != M.
4892 //
4893 // If LHS is non-negative and we know that LHS - RHS does not
4894 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4895 // either by proving that RHS > M or that LHS >= 0.
4896 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4897 AddFlags = SCEV::FlagNSW;
4898 }
4899 }
4900
4901 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4902 // RHS is NSW and LHS >= 0.
4903 //
4904 // The difficulty here is that the NSW flag may have been proven
4905 // relative to a loop that is to be found in a recurrence in LHS and
4906 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4907 // larger scope than intended.
4908 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4909
4910 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4911}
4912
4914 unsigned Depth) {
4915 Type *SrcTy = V->getType();
4916 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4917 "Cannot truncate or zero extend with non-integer arguments!");
4918 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4919 return V; // No conversion
4920 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4921 return getTruncateExpr(V, Ty, Depth);
4922 return getZeroExtendExpr(V, Ty, Depth);
4923}
4924
4926 unsigned Depth) {
4927 Type *SrcTy = V->getType();
4928 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4929 "Cannot truncate or zero extend with non-integer arguments!");
4930 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4931 return V; // No conversion
4932 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4933 return getTruncateExpr(V, Ty, Depth);
4934 return getSignExtendExpr(V, Ty, Depth);
4935}
4936
4937const SCEV *
4939 Type *SrcTy = V->getType();
4940 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4941 "Cannot noop or zero extend with non-integer arguments!");
4943 "getNoopOrZeroExtend cannot truncate!");
4944 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4945 return V; // No conversion
4946 return getZeroExtendExpr(V, Ty);
4947}
4948
4949const SCEV *
4951 Type *SrcTy = V->getType();
4952 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4953 "Cannot noop or sign extend with non-integer arguments!");
4955 "getNoopOrSignExtend cannot truncate!");
4956 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4957 return V; // No conversion
4958 return getSignExtendExpr(V, Ty);
4959}
4960
4961const SCEV *
4963 Type *SrcTy = V->getType();
4964 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4965 "Cannot noop or any extend with non-integer arguments!");
4967 "getNoopOrAnyExtend cannot truncate!");
4968 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4969 return V; // No conversion
4970 return getAnyExtendExpr(V, Ty);
4971}
4972
4973const SCEV *
4975 Type *SrcTy = V->getType();
4976 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4977 "Cannot truncate or noop with non-integer arguments!");
4979 "getTruncateOrNoop cannot extend!");
4980 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4981 return V; // No conversion
4982 return getTruncateExpr(V, Ty);
4983}
4984
4986 const SCEV *RHS) {
4987 const SCEV *PromotedLHS = LHS;
4988 const SCEV *PromotedRHS = RHS;
4989
4990 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4991 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4992 else
4993 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4994
4995 return getUMaxExpr(PromotedLHS, PromotedRHS);
4996}
4997
4999 const SCEV *RHS,
5000 bool Sequential) {
5001 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
5002 return getUMinFromMismatchedTypes(Ops, Sequential);
5003}
5004
5005const SCEV *
5007 bool Sequential) {
5008 assert(!Ops.empty() && "At least one operand must be!");
5009 // Trivial case.
5010 if (Ops.size() == 1)
5011 return Ops[0];
5012
5013 // Find the max type first.
5014 Type *MaxType = nullptr;
5015 for (SCEVUse S : Ops)
5016 if (MaxType)
5017 MaxType = getWiderType(MaxType, S->getType());
5018 else
5019 MaxType = S->getType();
5020 assert(MaxType && "Failed to find maximum type!");
5021
5022 // Extend all ops to max type.
5023 SmallVector<SCEVUse, 2> PromotedOps;
5024 for (SCEVUse S : Ops)
5025 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
5026
5027 // Generate umin.
5028 return getUMinExpr(PromotedOps, Sequential);
5029}
5030
5032 // A pointer operand may evaluate to a nonpointer expression, such as null.
5033 if (!V->getType()->isPointerTy())
5034 return V;
5035
5036 while (true) {
5037 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
5038 V = AddRec->getStart();
5039 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
5040 const SCEV *PtrOp = nullptr;
5041 for (const SCEV *AddOp : Add->operands()) {
5042 if (AddOp->getType()->isPointerTy()) {
5043 assert(!PtrOp && "Cannot have multiple pointer ops");
5044 PtrOp = AddOp;
5045 }
5046 }
5047 assert(PtrOp && "Must have pointer op");
5048 V = PtrOp;
5049 } else // Not something we can look further into.
5050 return V;
5051 }
5052}
5053
5054/// Push users of the given Instruction onto the given Worklist.
5058 // Push the def-use children onto the Worklist stack.
5059 for (User *U : I->users()) {
5060 auto *UserInsn = cast<Instruction>(U);
5061 if (Visited.insert(UserInsn).second)
5062 Worklist.push_back(UserInsn);
5063 }
5064}
5065
5066namespace {
5067
5068/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
5069/// expression in case its Loop is L. If it is not L then
5070/// if IgnoreOtherLoops is true then use AddRec itself
5071/// otherwise rewrite cannot be done.
5072/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
5073class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
5074public:
5075 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
5076 bool IgnoreOtherLoops = true) {
5077 SCEVInitRewriter Rewriter(L, SE);
5078 const SCEV *Result = Rewriter.visit(S);
5079 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
5080 return SE.getCouldNotCompute();
5081 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
5082 ? SE.getCouldNotCompute()
5083 : Result;
5084 }
5085
5086 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5087 if (!SE.isLoopInvariant(Expr, L))
5088 SeenLoopVariantSCEVUnknown = true;
5089 return Expr;
5090 }
5091
5092 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5093 // Only re-write AddRecExprs for this loop.
5094 if (Expr->getLoop() == L)
5095 return Expr->getStart();
5096 SeenOtherLoops = true;
5097 return Expr;
5098 }
5099
5100 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
5101
5102 bool hasSeenOtherLoops() { return SeenOtherLoops; }
5103
5104private:
5105 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
5106 : SCEVRewriteVisitor(SE), L(L) {}
5107
5108 const Loop *L;
5109 bool SeenLoopVariantSCEVUnknown = false;
5110 bool SeenOtherLoops = false;
5111};
5112
5113/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
5114/// increment expression in case its Loop is L. If it is not L then
5115/// use AddRec itself.
5116/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
5117class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
5118public:
5119 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
5120 SCEVPostIncRewriter Rewriter(L, SE);
5121 const SCEV *Result = Rewriter.visit(S);
5122 return Rewriter.hasSeenLoopVariantSCEVUnknown()
5123 ? SE.getCouldNotCompute()
5124 : Result;
5125 }
5126
5127 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5128 if (!SE.isLoopInvariant(Expr, L))
5129 SeenLoopVariantSCEVUnknown = true;
5130 return Expr;
5131 }
5132
5133 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5134 // Only re-write AddRecExprs for this loop.
5135 if (Expr->getLoop() == L)
5136 return Expr->getPostIncExpr(SE);
5137 SeenOtherLoops = true;
5138 return Expr;
5139 }
5140
5141 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
5142
5143 bool hasSeenOtherLoops() { return SeenOtherLoops; }
5144
5145private:
5146 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
5147 : SCEVRewriteVisitor(SE), L(L) {}
5148
5149 const Loop *L;
5150 bool SeenLoopVariantSCEVUnknown = false;
5151 bool SeenOtherLoops = false;
5152};
5153
5154/// This class evaluates the compare condition by matching it against the
5155/// condition of loop latch. If there is a match we assume a true value
5156/// for the condition while building SCEV nodes.
5157class SCEVBackedgeConditionFolder
5158 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
5159public:
5160 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5161 ScalarEvolution &SE) {
5162 bool IsPosBECond = false;
5163 Value *BECond = nullptr;
5164 if (BasicBlock *Latch = L->getLoopLatch()) {
5165 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
5166 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
5167 "Both outgoing branches should not target same header!");
5168 BECond = BI->getCondition();
5169 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
5170 } else {
5171 return S;
5172 }
5173 }
5174 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
5175 return Rewriter.visit(S);
5176 }
5177
5178 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5179 const SCEV *Result = Expr;
5180 bool InvariantF = SE.isLoopInvariant(Expr, L);
5181
5182 if (!InvariantF) {
5184 switch (I->getOpcode()) {
5185 case Instruction::Select: {
5186 SelectInst *SI = cast<SelectInst>(I);
5187 std::optional<const SCEV *> Res =
5188 compareWithBackedgeCondition(SI->getCondition());
5189 if (Res) {
5190 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
5191 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
5192 }
5193 break;
5194 }
5195 default: {
5196 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
5197 if (Res)
5198 Result = *Res;
5199 break;
5200 }
5201 }
5202 }
5203 return Result;
5204 }
5205
5206private:
5207 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
5208 bool IsPosBECond, ScalarEvolution &SE)
5209 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
5210 IsPositiveBECond(IsPosBECond) {}
5211
5212 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
5213
5214 const Loop *L;
5215 /// Loop back condition.
5216 Value *BackedgeCond = nullptr;
5217 /// Set to true if loop back is on positive branch condition.
5218 bool IsPositiveBECond;
5219};
5220
5221std::optional<const SCEV *>
5222SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
5223
5224 // If value matches the backedge condition for loop latch,
5225 // then return a constant evolution node based on loopback
5226 // branch taken.
5227 if (BackedgeCond == IC)
5228 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
5230 return std::nullopt;
5231}
5232
5233class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5234public:
5235 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5236 ScalarEvolution &SE) {
5237 SCEVShiftRewriter Rewriter(L, SE);
5238 const SCEV *Result = Rewriter.visit(S);
5239 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5240 }
5241
5242 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5243 // Only allow AddRecExprs for this loop.
5244 if (!SE.isLoopInvariant(Expr, L))
5245 Valid = false;
5246 return Expr;
5247 }
5248
5249 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5250 if (Expr->getLoop() == L && Expr->isAffine())
5251 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5252 Valid = false;
5253 return Expr;
5254 }
5255
5256 bool isValid() { return Valid; }
5257
5258private:
5259 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5260 : SCEVRewriteVisitor(SE), L(L) {}
5261
5262 const Loop *L;
5263 bool Valid = true;
5264};
5265
5266} // end anonymous namespace
5267
5268void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5269 if (!AR->isAffine())
5270 return;
5271
5272 // Force computation of ranges, which will also perform range-based flag
5273 // inference.
5274 if (!AR->hasNoSignedWrap())
5275 (void)getSignedRange(AR);
5276
5277 if (!AR->hasNoUnsignedWrap())
5278 (void)getUnsignedRange(AR);
5279
5280 if (!AR->hasNoSelfWrap()) {
5281 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5282 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5283 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5284 const APInt &BECountAP = BECountMax->getAPInt();
5285 unsigned NoOverflowBitWidth =
5286 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5287 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5288 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5289 }
5290 }
5291}
5292
5294ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5296
5297 if (AR->hasNoSignedWrap())
5298 return Result;
5299
5300 if (!AR->isAffine())
5301 return Result;
5302
5303 // This function can be expensive, only try to prove NSW once per AddRec.
5304 if (!SignedWrapViaInductionTried.insert(AR).second)
5305 return Result;
5306
5307 const SCEV *Step = AR->getStepRecurrence(*this);
5308 const Loop *L = AR->getLoop();
5309
5310 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5311 // Note that this serves two purposes: It filters out loops that are
5312 // simply not analyzable, and it covers the case where this code is
5313 // being called from within backedge-taken count analysis, such that
5314 // attempting to ask for the backedge-taken count would likely result
5315 // in infinite recursion. In the later case, the analysis code will
5316 // cope with a conservative value, and it will take care to purge
5317 // that value once it has finished.
5318 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5319
5320 // Normally, in the cases we can prove no-overflow via a
5321 // backedge guarding condition, we can also compute a backedge
5322 // taken count for the loop. The exceptions are assumptions and
5323 // guards present in the loop -- SCEV is not great at exploiting
5324 // these to compute max backedge taken counts, but can still use
5325 // these to prove lack of overflow. Use this fact to avoid
5326 // doing extra work that may not pay off.
5327
5328 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5329 AC.assumptions().empty())
5330 return Result;
5331
5332 // If the backedge is guarded by a comparison with the pre-inc value the
5333 // addrec is safe. Also, if the entry is guarded by a comparison with the
5334 // start value and the backedge is guarded by a comparison with the post-inc
5335 // value, the addrec is safe.
5337 const SCEV *OverflowLimit =
5338 getSignedOverflowLimitForStep(Step, &Pred, this);
5339 if (OverflowLimit &&
5340 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5341 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5342 Result = setFlags(Result, SCEV::FlagNSW);
5343 }
5344 return Result;
5345}
5347ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5349
5350 if (AR->hasNoUnsignedWrap())
5351 return Result;
5352
5353 if (!AR->isAffine())
5354 return Result;
5355
5356 // This function can be expensive, only try to prove NUW once per AddRec.
5357 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5358 return Result;
5359
5360 const SCEV *Step = AR->getStepRecurrence(*this);
5361 unsigned BitWidth = getTypeSizeInBits(AR->getType());
5362 const Loop *L = AR->getLoop();
5363
5364 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5365 // Note that this serves two purposes: It filters out loops that are
5366 // simply not analyzable, and it covers the case where this code is
5367 // being called from within backedge-taken count analysis, such that
5368 // attempting to ask for the backedge-taken count would likely result
5369 // in infinite recursion. In the later case, the analysis code will
5370 // cope with a conservative value, and it will take care to purge
5371 // that value once it has finished.
5372 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5373
5374 // Normally, in the cases we can prove no-overflow via a
5375 // backedge guarding condition, we can also compute a backedge
5376 // taken count for the loop. The exceptions are assumptions and
5377 // guards present in the loop -- SCEV is not great at exploiting
5378 // these to compute max backedge taken counts, but can still use
5379 // these to prove lack of overflow. Use this fact to avoid
5380 // doing extra work that may not pay off.
5381
5382 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5383 AC.assumptions().empty())
5384 return Result;
5385
5386 // If the backedge is guarded by a comparison with the pre-inc value the
5387 // addrec is safe. Also, if the entry is guarded by a comparison with the
5388 // start value and the backedge is guarded by a comparison with the post-inc
5389 // value, the addrec is safe.
5390 if (isKnownPositive(Step)) {
5391 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
5392 getUnsignedRangeMax(Step));
5395 Result = setFlags(Result, SCEV::FlagNUW);
5396 }
5397 }
5398
5399 return Result;
5400}
5401
5402namespace {
5403
5404/// Represents an abstract binary operation. This may exist as a
5405/// normal instruction or constant expression, or may have been
5406/// derived from an expression tree.
5407struct BinaryOp {
5408 unsigned Opcode;
5409 Value *LHS;
5410 Value *RHS;
5411 bool IsNSW = false;
5412 bool IsNUW = false;
5413
5414 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5415 /// constant expression.
5416 Operator *Op = nullptr;
5417
5418 explicit BinaryOp(Operator *Op)
5419 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5420 Op(Op) {
5421 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5422 IsNSW = OBO->hasNoSignedWrap();
5423 IsNUW = OBO->hasNoUnsignedWrap();
5424 }
5425 }
5426
5427 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5428 bool IsNUW = false)
5429 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5430};
5431
5432} // end anonymous namespace
5433
5434/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5435static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5436 AssumptionCache &AC,
5437 const DominatorTree &DT,
5438 const Instruction *CxtI) {
5439 auto *Op = dyn_cast<Operator>(V);
5440 if (!Op)
5441 return std::nullopt;
5442
5443 // Implementation detail: all the cleverness here should happen without
5444 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5445 // SCEV expressions when possible, and we should not break that.
5446
5447 switch (Op->getOpcode()) {
5448 case Instruction::Add:
5449 case Instruction::Sub:
5450 case Instruction::Mul:
5451 case Instruction::UDiv:
5452 case Instruction::URem:
5453 case Instruction::And:
5454 case Instruction::AShr:
5455 case Instruction::Shl:
5456 return BinaryOp(Op);
5457
5458 case Instruction::Or: {
5459 // Convert or disjoint into add nuw nsw.
5460 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5461 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5462 /*IsNSW=*/true, /*IsNUW=*/true);
5463 // Keep the reference to the original instruction so that we can later
5464 // check whether it can produce poison value or not.
5465 BinOp.Op = Op;
5466 return BinOp;
5467 }
5468 return BinaryOp(Op);
5469 }
5470
5471 case Instruction::Xor:
5472 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5473 // If the RHS of the xor is a signmask, then this is just an add.
5474 // Instcombine turns add of signmask into xor as a strength reduction step.
5475 if (RHSC->getValue().isSignMask())
5476 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5477 // Binary `xor` is a bit-wise `add`.
5478 if (V->getType()->isIntegerTy(1))
5479 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5480 return BinaryOp(Op);
5481
5482 case Instruction::LShr:
5483 // Turn logical shift right of a constant into a unsigned divide.
5484 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5485 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5486
5487 // If the shift count is not less than the bitwidth, the result of
5488 // the shift is undefined. Don't try to analyze it, because the
5489 // resolution chosen here may differ from the resolution chosen in
5490 // other parts of the compiler.
5491 if (SA->getValue().ult(BitWidth)) {
5492 Constant *X =
5493 ConstantInt::get(SA->getContext(),
5494 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5495 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5496 }
5497 }
5498 return BinaryOp(Op);
5499
5500 case Instruction::ExtractValue: {
5501 auto *EVI = cast<ExtractValueInst>(Op);
5502 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5503 break;
5504
5505 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5506 if (!WO)
5507 break;
5508
5509 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5510 bool Signed = WO->isSigned();
5511 // TODO: Should add nuw/nsw flags for mul as well.
5512 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5513 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5514
5515 // Now that we know that all uses of the arithmetic-result component of
5516 // CI are guarded by the overflow check, we can go ahead and pretend
5517 // that the arithmetic is non-overflowing.
5518 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5519 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5520 }
5521
5522 default:
5523 break;
5524 }
5525
5526 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5527 // semantics as a Sub, return a binary sub expression.
5528 if (auto *II = dyn_cast<IntrinsicInst>(V))
5529 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5530 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5531
5532 return std::nullopt;
5533}
5534
5535/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5536/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5537/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5538/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5539/// follows one of the following patterns:
5540/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5541/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5542/// If the SCEV expression of \p Op conforms with one of the expected patterns
5543/// we return the type of the truncation operation, and indicate whether the
5544/// truncated type should be treated as signed/unsigned by setting
5545/// \p Signed to true/false, respectively.
5546static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5547 bool &Signed, ScalarEvolution &SE) {
5548 // The case where Op == SymbolicPHI (that is, with no type conversions on
5549 // the way) is handled by the regular add recurrence creating logic and
5550 // would have already been triggered in createAddRecForPHI. Reaching it here
5551 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5552 // because one of the other operands of the SCEVAddExpr updating this PHI is
5553 // not invariant).
5554 //
5555 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5556 // this case predicates that allow us to prove that Op == SymbolicPHI will
5557 // be added.
5558 if (Op == SymbolicPHI)
5559 return nullptr;
5560
5561 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5562 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5563 if (SourceBits != NewBits)
5564 return nullptr;
5565
5566 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5567 Signed = true;
5568 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5569 }
5570 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5571 Signed = false;
5572 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5573 }
5574 return nullptr;
5575}
5576
5577static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5578 if (!PN->getType()->isIntegerTy())
5579 return nullptr;
5580 const Loop *L = LI.getLoopFor(PN->getParent());
5581 if (!L || L->getHeader() != PN->getParent())
5582 return nullptr;
5583 return L;
5584}
5585
5586// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5587// computation that updates the phi follows the following pattern:
5588// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5589// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5590// If so, try to see if it can be rewritten as an AddRecExpr under some
5591// Predicates. If successful, return them as a pair. Also cache the results
5592// of the analysis.
5593//
5594// Example usage scenario:
5595// Say the Rewriter is called for the following SCEV:
5596// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5597// where:
5598// %X = phi i64 (%Start, %BEValue)
5599// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5600// and call this function with %SymbolicPHI = %X.
5601//
5602// The analysis will find that the value coming around the backedge has
5603// the following SCEV:
5604// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5605// Upon concluding that this matches the desired pattern, the function
5606// will return the pair {NewAddRec, SmallPredsVec} where:
5607// NewAddRec = {%Start,+,%Step}
5608// SmallPredsVec = {P1, P2, P3} as follows:
5609// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5610// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5611// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5612// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5613// under the predicates {P1,P2,P3}.
5614// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5615// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5616//
5617// TODO's:
5618//
5619// 1) Extend the Induction descriptor to also support inductions that involve
5620// casts: When needed (namely, when we are called in the context of the
5621// vectorizer induction analysis), a Set of cast instructions will be
5622// populated by this method, and provided back to isInductionPHI. This is
5623// needed to allow the vectorizer to properly record them to be ignored by
5624// the cost model and to avoid vectorizing them (otherwise these casts,
5625// which are redundant under the runtime overflow checks, will be
5626// vectorized, which can be costly).
5627//
5628// 2) Support additional induction/PHISCEV patterns: We also want to support
5629// inductions where the sext-trunc / zext-trunc operations (partly) occur
5630// after the induction update operation (the induction increment):
5631//
5632// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5633// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5634//
5635// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5636// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5637//
5638// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5639std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5640ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5642
5643 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5644 // return an AddRec expression under some predicate.
5645
5646 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5647 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5648 assert(L && "Expecting an integer loop header phi");
5649
5650 // The loop may have multiple entrances or multiple exits; we can analyze
5651 // this phi as an addrec if it has a unique entry value and a unique
5652 // backedge value.
5653 Value *BEValueV = nullptr, *StartValueV = nullptr;
5654 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5655 Value *V = PN->getIncomingValue(i);
5656 if (L->contains(PN->getIncomingBlock(i))) {
5657 if (!BEValueV) {
5658 BEValueV = V;
5659 } else if (BEValueV != V) {
5660 BEValueV = nullptr;
5661 break;
5662 }
5663 } else if (!StartValueV) {
5664 StartValueV = V;
5665 } else if (StartValueV != V) {
5666 StartValueV = nullptr;
5667 break;
5668 }
5669 }
5670 if (!BEValueV || !StartValueV)
5671 return std::nullopt;
5672
5673 const SCEV *BEValue = getSCEV(BEValueV);
5674
5675 // If the value coming around the backedge is an add with the symbolic
5676 // value we just inserted, possibly with casts that we can ignore under
5677 // an appropriate runtime guard, then we found a simple induction variable!
5678 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5679 if (!Add)
5680 return std::nullopt;
5681
5682 // If there is a single occurrence of the symbolic value, possibly
5683 // casted, replace it with a recurrence.
5684 unsigned FoundIndex = Add->getNumOperands();
5685 Type *TruncTy = nullptr;
5686 bool Signed;
5687 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5688 if ((TruncTy =
5689 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5690 if (FoundIndex == e) {
5691 FoundIndex = i;
5692 break;
5693 }
5694
5695 if (FoundIndex == Add->getNumOperands())
5696 return std::nullopt;
5697
5698 // Create an add with everything but the specified operand.
5700 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5701 if (i != FoundIndex)
5702 Ops.push_back(Add->getOperand(i));
5703 const SCEV *Accum = getAddExpr(Ops);
5704
5705 // The runtime checks will not be valid if the step amount is
5706 // varying inside the loop.
5707 if (!isLoopInvariant(Accum, L))
5708 return std::nullopt;
5709
5710 // *** Part2: Create the predicates
5711
5712 // Analysis was successful: we have a phi-with-cast pattern for which we
5713 // can return an AddRec expression under the following predicates:
5714 //
5715 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5716 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5717 // P2: An Equal predicate that guarantees that
5718 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5719 // P3: An Equal predicate that guarantees that
5720 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5721 //
5722 // As we next prove, the above predicates guarantee that:
5723 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5724 //
5725 //
5726 // More formally, we want to prove that:
5727 // Expr(i+1) = Start + (i+1) * Accum
5728 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5729 //
5730 // Given that:
5731 // 1) Expr(0) = Start
5732 // 2) Expr(1) = Start + Accum
5733 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5734 // 3) Induction hypothesis (step i):
5735 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5736 //
5737 // Proof:
5738 // Expr(i+1) =
5739 // = Start + (i+1)*Accum
5740 // = (Start + i*Accum) + Accum
5741 // = Expr(i) + Accum
5742 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5743 // :: from step i
5744 //
5745 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5746 //
5747 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5748 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5749 // + Accum :: from P3
5750 //
5751 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5752 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5753 //
5754 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5755 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5756 //
5757 // By induction, the same applies to all iterations 1<=i<n:
5758 //
5759
5760 // Create a truncated addrec for which we will add a no overflow check (P1).
5761 const SCEV *StartVal = getSCEV(StartValueV);
5762 const SCEV *PHISCEV =
5763 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5764 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5765
5766 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5767 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5768 // will be constant.
5769 //
5770 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5771 // add P1.
5772 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5776 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5777 Predicates.push_back(AddRecPred);
5778 }
5779
5780 // Create the Equal Predicates P2,P3:
5781
5782 // It is possible that the predicates P2 and/or P3 are computable at
5783 // compile time due to StartVal and/or Accum being constants.
5784 // If either one is, then we can check that now and escape if either P2
5785 // or P3 is false.
5786
5787 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5788 // for each of StartVal and Accum
5789 auto getExtendedExpr = [&](const SCEV *Expr,
5790 bool CreateSignExtend) -> const SCEV * {
5791 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5792 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5793 const SCEV *ExtendedExpr =
5794 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5795 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5796 return ExtendedExpr;
5797 };
5798
5799 // Given:
5800 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5801 // = getExtendedExpr(Expr)
5802 // Determine whether the predicate P: Expr == ExtendedExpr
5803 // is known to be false at compile time
5804 auto PredIsKnownFalse = [&](const SCEV *Expr,
5805 const SCEV *ExtendedExpr) -> bool {
5806 return Expr != ExtendedExpr &&
5807 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5808 };
5809
5810 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5811 if (PredIsKnownFalse(StartVal, StartExtended)) {
5812 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5813 return std::nullopt;
5814 }
5815
5816 // The Step is always Signed (because the overflow checks are either
5817 // NSSW or NUSW)
5818 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5819 if (PredIsKnownFalse(Accum, AccumExtended)) {
5820 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5821 return std::nullopt;
5822 }
5823
5824 auto AppendPredicate = [&](const SCEV *Expr,
5825 const SCEV *ExtendedExpr) -> void {
5826 if (Expr != ExtendedExpr &&
5827 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5828 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5829 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5830 Predicates.push_back(Pred);
5831 }
5832 };
5833
5834 AppendPredicate(StartVal, StartExtended);
5835 AppendPredicate(Accum, AccumExtended);
5836
5837 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5838 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5839 // into NewAR if it will also add the runtime overflow checks specified in
5840 // Predicates.
5841 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5842
5843 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5844 std::make_pair(NewAR, Predicates);
5845 // Remember the result of the analysis for this SCEV at this locayyytion.
5846 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5847 return PredRewrite;
5848}
5849
5850std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5852 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5853 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5854 if (!L)
5855 return std::nullopt;
5856
5857 // Check to see if we already analyzed this PHI.
5858 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5859 if (I != PredicatedSCEVRewrites.end()) {
5860 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5861 I->second;
5862 // Analysis was done before and failed to create an AddRec:
5863 if (Rewrite.first == SymbolicPHI)
5864 return std::nullopt;
5865 // Analysis was done before and succeeded to create an AddRec under
5866 // a predicate:
5867 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5868 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5869 return Rewrite;
5870 }
5871
5872 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5873 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5874
5875 // Record in the cache that the analysis failed
5876 if (!Rewrite) {
5878 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5879 return std::nullopt;
5880 }
5881
5882 return Rewrite;
5883}
5884
5885// FIXME: This utility is currently required because the Rewriter currently
5886// does not rewrite this expression:
5887// {0, +, (sext ix (trunc iy to ix) to iy)}
5888// into {0, +, %step},
5889// even when the following Equal predicate exists:
5890// "%step == (sext ix (trunc iy to ix) to iy)".
5892 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5893 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5894 if (AR1 == AR2)
5895 return true;
5896
5897 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5898 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5899 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5900 if (Expr1 != Expr2 &&
5901 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5902 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5903 return false;
5904 return true;
5905 };
5906
5907 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5908 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5909 return false;
5910 return true;
5911}
5912
5913/// A helper function for createAddRecFromPHI to handle simple cases.
5914///
5915/// This function tries to find an AddRec expression for the simplest (yet most
5916/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5917/// If it fails, createAddRecFromPHI will use a more general, but slow,
5918/// technique for finding the AddRec expression.
5919const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5920 Value *BEValueV,
5921 Value *StartValueV) {
5922 const Loop *L = LI.getLoopFor(PN->getParent());
5923 assert(L && L->getHeader() == PN->getParent());
5924 assert(BEValueV && StartValueV);
5925
5926 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5927 if (!BO)
5928 return nullptr;
5929
5930 if (BO->Opcode != Instruction::Add)
5931 return nullptr;
5932
5933 const SCEV *Accum = nullptr;
5934 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5935 Accum = getSCEV(BO->RHS);
5936 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5937 Accum = getSCEV(BO->LHS);
5938
5939 if (!Accum)
5940 return nullptr;
5941
5943 if (BO->IsNUW)
5944 Flags = setFlags(Flags, SCEV::FlagNUW);
5945 if (BO->IsNSW)
5946 Flags = setFlags(Flags, SCEV::FlagNSW);
5947
5948 const SCEV *StartVal = getSCEV(StartValueV);
5949 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5950 insertValueToMap(PN, PHISCEV);
5951
5952 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5953 inferNoWrapViaConstantRanges(AR);
5954
5955 // We can add Flags to the post-inc expression only if we
5956 // know that it is *undefined behavior* for BEValueV to
5957 // overflow.
5958 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5959 assert(isLoopInvariant(Accum, L) &&
5960 "Accum is defined outside L, but is not invariant?");
5961 if (isAddRecNeverPoison(BEInst, L))
5962 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5963 }
5964
5965 return PHISCEV;
5966}
5967
5968const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5969 const Loop *L = LI.getLoopFor(PN->getParent());
5970 if (!L || L->getHeader() != PN->getParent())
5971 return nullptr;
5972
5973 // The loop may have multiple entrances or multiple exits; we can analyze
5974 // this phi as an addrec if it has a unique entry value and a unique
5975 // backedge value.
5976 Value *BEValueV = nullptr, *StartValueV = nullptr;
5977 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5978 Value *V = PN->getIncomingValue(i);
5979 if (L->contains(PN->getIncomingBlock(i))) {
5980 if (!BEValueV) {
5981 BEValueV = V;
5982 } else if (BEValueV != V) {
5983 BEValueV = nullptr;
5984 break;
5985 }
5986 } else if (!StartValueV) {
5987 StartValueV = V;
5988 } else if (StartValueV != V) {
5989 StartValueV = nullptr;
5990 break;
5991 }
5992 }
5993 if (!BEValueV || !StartValueV)
5994 return nullptr;
5995
5996 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5997 "PHI node already processed?");
5998
5999 // First, try to find AddRec expression without creating a fictituos symbolic
6000 // value for PN.
6001 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
6002 return S;
6003
6004 // Handle PHI node value symbolically.
6005 const SCEV *SymbolicName = getUnknown(PN);
6006 insertValueToMap(PN, SymbolicName);
6007
6008 // Using this symbolic name for the PHI, analyze the value coming around
6009 // the back-edge.
6010 const SCEV *BEValue = getSCEV(BEValueV);
6011
6012 // NOTE: If BEValue is loop invariant, we know that the PHI node just
6013 // has a special value for the first iteration of the loop.
6014
6015 // If the value coming around the backedge is an add with the symbolic
6016 // value we just inserted, then we found a simple induction variable!
6017 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
6018 // If there is a single occurrence of the symbolic value, replace it
6019 // with a recurrence.
6020 unsigned FoundIndex = Add->getNumOperands();
6021 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
6022 if (Add->getOperand(i) == SymbolicName)
6023 if (FoundIndex == e) {
6024 FoundIndex = i;
6025 break;
6026 }
6027
6028 if (FoundIndex != Add->getNumOperands()) {
6029 // Create an add with everything but the specified operand.
6031 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
6032 if (i != FoundIndex)
6033 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
6034 L, *this));
6035 const SCEV *Accum = getAddExpr(Ops);
6036
6037 // This is not a valid addrec if the step amount is varying each
6038 // loop iteration, but is not itself an addrec in this loop.
6039 if (isLoopInvariant(Accum, L) ||
6040 (isa<SCEVAddRecExpr>(Accum) &&
6041 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
6043
6044 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
6045 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
6046 if (BO->IsNUW)
6047 Flags = setFlags(Flags, SCEV::FlagNUW);
6048 if (BO->IsNSW)
6049 Flags = setFlags(Flags, SCEV::FlagNSW);
6050 }
6051 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
6052 if (GEP->getOperand(0) == PN) {
6053 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
6054 // If the increment has any nowrap flags, then we know the address
6055 // space cannot be wrapped around.
6056 if (NW != GEPNoWrapFlags::none())
6057 Flags = setFlags(Flags, SCEV::FlagNW);
6058 // If the GEP is nuw or nusw with non-negative offset, we know that
6059 // no unsigned wrap occurs. We cannot set the nsw flag as only the
6060 // offset is treated as signed, while the base is unsigned.
6061 if (NW.hasNoUnsignedWrap() ||
6063 Flags = setFlags(Flags, SCEV::FlagNUW);
6064 }
6065
6066 // We cannot transfer nuw and nsw flags from subtraction
6067 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
6068 // for instance.
6069 }
6070
6071 const SCEV *StartVal = getSCEV(StartValueV);
6072 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
6073
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, PHISCEV);
6079
6080 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
6081 inferNoWrapViaConstantRanges(AR);
6082
6083 // We can add Flags to the post-inc expression only if we
6084 // know that it is *undefined behavior* for BEValueV to
6085 // overflow.
6086 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
6087 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
6088 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
6089
6090 return PHISCEV;
6091 }
6092 }
6093 } else {
6094 // Otherwise, this could be a loop like this:
6095 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
6096 // In this case, j = {1,+,1} and BEValue is j.
6097 // Because the other in-value of i (0) fits the evolution of BEValue
6098 // i really is an addrec evolution.
6099 //
6100 // We can generalize this saying that i is the shifted value of BEValue
6101 // by one iteration:
6102 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
6103
6104 // Do not allow refinement in rewriting of BEValue.
6105 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
6106 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
6107 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
6108 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
6109 const SCEV *StartVal = getSCEV(StartValueV);
6110 if (Start == StartVal) {
6111 // Okay, for the entire analysis of this edge we assumed the PHI
6112 // to be symbolic. We now need to go back and purge all of the
6113 // entries for the scalars that use the symbolic expression.
6114 forgetMemoizedResults({SymbolicName});
6115 insertValueToMap(PN, Shifted);
6116 return Shifted;
6117 }
6118 }
6119 }
6120
6121 // Remove the temporary PHI node SCEV that has been inserted while intending
6122 // to create an AddRecExpr for this PHI node. We can not keep this temporary
6123 // as it will prevent later (possibly simpler) SCEV expressions to be added
6124 // to the ValueExprMap.
6125 eraseValueFromMap(PN);
6126
6127 return nullptr;
6128}
6129
6130// Try to match a control flow sequence that branches out at BI and merges back
6131// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
6132// match.
6134 Value *&C, Value *&LHS, Value *&RHS) {
6135 C = BI->getCondition();
6136
6137 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
6138 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
6139
6140 Use &LeftUse = Merge->getOperandUse(0);
6141 Use &RightUse = Merge->getOperandUse(1);
6142
6143 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
6144 LHS = LeftUse;
6145 RHS = RightUse;
6146 return true;
6147 }
6148
6149 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
6150 LHS = RightUse;
6151 RHS = LeftUse;
6152 return true;
6153 }
6154
6155 return false;
6156}
6157
6159 Value *&Cond, Value *&LHS,
6160 Value *&RHS) {
6161 auto IsReachable =
6162 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
6163 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
6164 // Try to match
6165 //
6166 // br %cond, label %left, label %right
6167 // left:
6168 // br label %merge
6169 // right:
6170 // br label %merge
6171 // merge:
6172 // V = phi [ %x, %left ], [ %y, %right ]
6173 //
6174 // as "select %cond, %x, %y"
6175
6176 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
6177 assert(IDom && "At least the entry block should dominate PN");
6178
6179 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
6180 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
6181 }
6182 return false;
6183}
6184
6185const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
6186 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6187 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
6190 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
6191
6192 return nullptr;
6193}
6194
6196 BinaryOperator *CommonInst = nullptr;
6197 // Check if instructions are identical.
6198 for (Value *Incoming : PN->incoming_values()) {
6199 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
6200 if (!IncomingInst)
6201 return nullptr;
6202 if (CommonInst) {
6203 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
6204 return nullptr; // Not identical, give up
6205 } else {
6206 // Remember binary operator
6207 CommonInst = IncomingInst;
6208 }
6209 }
6210 return CommonInst;
6211}
6212
6213/// Returns SCEV for the first operand of a phi if all phi operands have
6214/// identical opcodes and operands
6215/// eg.
6216/// a: %add = %a + %b
6217/// br %c
6218/// b: %add1 = %a + %b
6219/// br %c
6220/// c: %phi = phi [%add, a], [%add1, b]
6221/// scev(%phi) => scev(%add)
6222const SCEV *
6223ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6224 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6225 if (!CommonInst)
6226 return nullptr;
6227
6228 // Check if SCEV exprs for instructions are identical.
6229 const SCEV *CommonSCEV = getSCEV(CommonInst);
6230 bool SCEVExprsIdentical =
6232 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6233 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6234}
6235
6236const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6237 if (const SCEV *S = createAddRecFromPHI(PN))
6238 return S;
6239
6240 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6241 // phi node for X.
6242 if (Value *V = simplifyInstruction(
6243 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6244 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6245 return getSCEV(V);
6246
6247 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6248 return S;
6249
6250 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6251 return S;
6252
6253 // If it's not a loop phi, we can't handle it yet.
6254 return getUnknown(PN);
6255}
6256
6257bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6258 SCEVTypes RootKind) {
6259 struct FindClosure {
6260 const SCEV *OperandToFind;
6261 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6262 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6263
6264 bool Found = false;
6265
6266 bool canRecurseInto(SCEVTypes Kind) const {
6267 // We can only recurse into the SCEV expression of the same effective type
6268 // as the type of our root SCEV expression, and into zero-extensions.
6269 return RootKind == Kind || NonSequentialRootKind == Kind ||
6270 scZeroExtend == Kind;
6271 };
6272
6273 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6274 : OperandToFind(OperandToFind), RootKind(RootKind),
6275 NonSequentialRootKind(
6277 RootKind)) {}
6278
6279 bool follow(const SCEV *S) {
6280 Found = S == OperandToFind;
6281
6282 return !isDone() && canRecurseInto(S->getSCEVType());
6283 }
6284
6285 bool isDone() const { return Found; }
6286 };
6287
6288 FindClosure FC(OperandToFind, RootKind);
6289 visitAll(Root, FC);
6290 return FC.Found;
6291}
6292
6293std::optional<const SCEV *>
6294ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6295 ICmpInst *Cond,
6296 Value *TrueVal,
6297 Value *FalseVal) {
6298 // Try to match some simple smax or umax patterns.
6299 auto *ICI = Cond;
6300
6301 Value *LHS = ICI->getOperand(0);
6302 Value *RHS = ICI->getOperand(1);
6303
6304 switch (ICI->getPredicate()) {
6305 case ICmpInst::ICMP_SLT:
6306 case ICmpInst::ICMP_SLE:
6307 case ICmpInst::ICMP_ULT:
6308 case ICmpInst::ICMP_ULE:
6309 std::swap(LHS, RHS);
6310 [[fallthrough]];
6311 case ICmpInst::ICMP_SGT:
6312 case ICmpInst::ICMP_SGE:
6313 case ICmpInst::ICMP_UGT:
6314 case ICmpInst::ICMP_UGE:
6315 // a > b ? a+x : b+x -> max(a, b)+x
6316 // a > b ? b+x : a+x -> min(a, b)+x
6318 bool Signed = ICI->isSigned();
6319 const SCEV *LA = getSCEV(TrueVal);
6320 const SCEV *RA = getSCEV(FalseVal);
6321 const SCEV *LS = getSCEV(LHS);
6322 const SCEV *RS = getSCEV(RHS);
6323 if (LA->getType()->isPointerTy()) {
6324 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6325 // Need to make sure we can't produce weird expressions involving
6326 // negated pointers.
6327 if (LA == LS && RA == RS)
6328 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6329 if (LA == RS && RA == LS)
6330 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6331 }
6332 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6333 if (Op->getType()->isPointerTy()) {
6336 return Op;
6337 }
6338 if (Signed)
6339 Op = getNoopOrSignExtend(Op, Ty);
6340 else
6341 Op = getNoopOrZeroExtend(Op, Ty);
6342 return Op;
6343 };
6344 LS = CoerceOperand(LS);
6345 RS = CoerceOperand(RS);
6347 break;
6348 const SCEV *LDiff = getMinusSCEV(LA, LS);
6349 const SCEV *RDiff = getMinusSCEV(RA, RS);
6350 if (LDiff == RDiff)
6351 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6352 LDiff);
6353 LDiff = getMinusSCEV(LA, RS);
6354 RDiff = getMinusSCEV(RA, LS);
6355 if (LDiff == RDiff)
6356 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6357 LDiff);
6358 }
6359 break;
6360 case ICmpInst::ICMP_NE:
6361 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6362 std::swap(TrueVal, FalseVal);
6363 [[fallthrough]];
6364 case ICmpInst::ICMP_EQ:
6365 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6368 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6369 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6370 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6371 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6372 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6373 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6374 return getAddExpr(getUMaxExpr(X, C), Y);
6375 }
6376 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6377 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6378 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6379 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6381 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6382 const SCEV *X = getSCEV(LHS);
6383 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6384 X = ZExt->getOperand();
6385 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6386 const SCEV *FalseValExpr = getSCEV(FalseVal);
6387 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6388 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6389 /*Sequential=*/true);
6390 }
6391 }
6392 break;
6393 default:
6394 break;
6395 }
6396
6397 return std::nullopt;
6398}
6399
6400static std::optional<const SCEV *>
6402 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6403 assert(CondExpr->getType()->isIntegerTy(1) &&
6404 TrueExpr->getType() == FalseExpr->getType() &&
6405 TrueExpr->getType()->isIntegerTy(1) &&
6406 "Unexpected operands of a select.");
6407
6408 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6409 // --> C + (umin_seq cond, x - C)
6410 //
6411 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6412 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6413 // --> C + (umin_seq ~cond, x - C)
6414
6415 // FIXME: while we can't legally model the case where both of the hands
6416 // are fully variable, we only require that the *difference* is constant.
6417 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6418 return std::nullopt;
6419
6420 const SCEV *X, *C;
6421 if (isa<SCEVConstant>(TrueExpr)) {
6422 CondExpr = SE->getNotSCEV(CondExpr);
6423 X = FalseExpr;
6424 C = TrueExpr;
6425 } else {
6426 X = TrueExpr;
6427 C = FalseExpr;
6428 }
6429 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6430 /*Sequential=*/true));
6431}
6432
6433static std::optional<const SCEV *>
6435 Value *FalseVal) {
6436 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6437 return std::nullopt;
6438
6439 const auto *SECond = SE->getSCEV(Cond);
6440 const auto *SETrue = SE->getSCEV(TrueVal);
6441 const auto *SEFalse = SE->getSCEV(FalseVal);
6442 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6443}
6444
6445const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6446 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6447 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6448 assert(TrueVal->getType() == FalseVal->getType() &&
6449 V->getType() == TrueVal->getType() &&
6450 "Types of select hands and of the result must match.");
6451
6452 // For now, only deal with i1-typed `select`s.
6453 if (!V->getType()->isIntegerTy(1))
6454 return getUnknown(V);
6455
6456 if (std::optional<const SCEV *> S =
6457 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6458 return *S;
6459
6460 return getUnknown(V);
6461}
6462
6463const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6464 Value *TrueVal,
6465 Value *FalseVal) {
6466 // Handle "constant" branch or select. This can occur for instance when a
6467 // loop pass transforms an inner loop and moves on to process the outer loop.
6468 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6469 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6470
6471 if (auto *I = dyn_cast<Instruction>(V)) {
6472 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6473 if (std::optional<const SCEV *> S =
6474 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6475 TrueVal, FalseVal))
6476 return *S;
6477 }
6478 }
6479
6480 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6481}
6482
6483/// Expand GEP instructions into add and multiply operations. This allows them
6484/// to be analyzed by regular SCEV code.
6485const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6486 assert(GEP->getSourceElementType()->isSized() &&
6487 "GEP source element type must be sized");
6488
6489 SmallVector<SCEVUse, 4> IndexExprs;
6490 for (Value *Index : GEP->indices())
6491 IndexExprs.push_back(getSCEV(Index));
6492 return getGEPExpr(GEP, IndexExprs);
6493}
6494
6495APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6496 const Instruction *CtxI) {
6497 uint64_t BitWidth = getTypeSizeInBits(S->getType());
6498 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6499 return TrailingZeros >= BitWidth
6501 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6502 };
6503 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6504 // The result is GCD of all operands results.
6505 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6506 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6508 Res, getConstantMultiple(N->getOperand(I), CtxI));
6509 return Res;
6510 };
6511
6512 switch (S->getSCEVType()) {
6513 case scConstant:
6514 return cast<SCEVConstant>(S)->getAPInt();
6515 case scPtrToAddr:
6516 case scPtrToInt:
6517 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6518 case scUDivExpr:
6519 case scVScale:
6520 return APInt(BitWidth, 1);
6521 case scTruncate: {
6522 // Only multiples that are a power of 2 will hold after truncation.
6523 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6524 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6525 return GetShiftedByZeros(TZ);
6526 }
6527 case scZeroExtend: {
6528 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6529 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6530 }
6531 case scSignExtend: {
6532 // Only multiples that are a power of 2 will hold after sext.
6533 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6534 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6535 return GetShiftedByZeros(TZ);
6536 }
6537 case scMulExpr: {
6538 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6539 if (M->hasNoUnsignedWrap()) {
6540 // The result is the product of all operand results.
6541 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6542 for (const SCEV *Operand : M->operands().drop_front())
6543 Res = Res * getConstantMultiple(Operand, CtxI);
6544 return Res;
6545 }
6546
6547 // If there are no wrap guarentees, find the trailing zeros, which is the
6548 // sum of trailing zeros for all its operands.
6549 uint32_t TZ = 0;
6550 for (const SCEV *Operand : M->operands())
6551 TZ += getMinTrailingZeros(Operand, CtxI);
6552 return GetShiftedByZeros(TZ);
6553 }
6554 case scAddExpr:
6555 case scAddRecExpr: {
6556 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6557 if (N->hasNoUnsignedWrap())
6558 return GetGCDMultiple(N);
6559 // Find the trailing bits, which is the minimum of its operands.
6560 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6561 for (const SCEV *Operand : N->operands().drop_front())
6562 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6563 return GetShiftedByZeros(TZ);
6564 }
6565 case scUMaxExpr:
6566 case scSMaxExpr:
6567 case scUMinExpr:
6568 case scSMinExpr:
6570 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6571 case scUnknown: {
6572 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6573 // the point their underlying IR instruction has been defined. If CtxI was
6574 // not provided, use:
6575 // * the first instruction in the entry block if it is an argument
6576 // * the instruction itself otherwise.
6577 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6578 if (!CtxI) {
6579 if (isa<Argument>(U->getValue()))
6580 CtxI = &*F.getEntryBlock().begin();
6581 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6582 CtxI = I;
6583 }
6584 unsigned Known =
6585 computeKnownBits(U->getValue(),
6586 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6587 .allowEphemerals(true))
6588 .countMinTrailingZeros();
6589 return GetShiftedByZeros(Known);
6590 }
6591 case scCouldNotCompute:
6592 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6593 }
6594 llvm_unreachable("Unknown SCEV kind!");
6595}
6596
6598 const Instruction *CtxI) {
6599 // Skip looking up and updating the cache if there is a context instruction,
6600 // as the result will only be valid in the specified context.
6601 if (CtxI)
6602 return getConstantMultipleImpl(S, CtxI);
6603
6604 auto I = ConstantMultipleCache.find(S);
6605 if (I != ConstantMultipleCache.end())
6606 return I->second;
6607
6608 APInt Result = getConstantMultipleImpl(S, CtxI);
6609 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6610 assert(InsertPair.second && "Should insert a new key");
6611 return InsertPair.first->second;
6612}
6613
6615 APInt Multiple = getConstantMultiple(S);
6616 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6617}
6618
6620 const Instruction *CtxI) {
6621 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6622 (unsigned)getTypeSizeInBits(S->getType()));
6623}
6624
6625/// Helper method to assign a range to V from metadata present in the IR.
6626static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6628 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6629 return getConstantRangeFromMetadata(*MD);
6630 if (const auto *CB = dyn_cast<CallBase>(V))
6631 if (std::optional<ConstantRange> Range = CB->getRange())
6632 return Range;
6633 }
6634 if (auto *A = dyn_cast<Argument>(V))
6635 if (std::optional<ConstantRange> Range = A->getRange())
6636 return Range;
6637
6638 return std::nullopt;
6639}
6640
6642 SCEV::NoWrapFlags Flags) {
6643 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6644 AddRec->setNoWrapFlags(Flags);
6645 UnsignedRanges.erase(AddRec);
6646 SignedRanges.erase(AddRec);
6647 ConstantMultipleCache.erase(AddRec);
6648 }
6649}
6650
6651ConstantRange ScalarEvolution::
6652getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6653 const DataLayout &DL = getDataLayout();
6654
6655 unsigned BitWidth = getTypeSizeInBits(U->getType());
6656 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6657
6658 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6659 // use information about the trip count to improve our available range. Note
6660 // that the trip count independent cases are already handled by known bits.
6661 // WARNING: The definition of recurrence used here is subtly different than
6662 // the one used by AddRec (and thus most of this file). Step is allowed to
6663 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6664 // and other addrecs in the same loop (for non-affine addrecs). The code
6665 // below intentionally handles the case where step is not loop invariant.
6666 auto *P = dyn_cast<PHINode>(U->getValue());
6667 if (!P)
6668 return FullSet;
6669
6670 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6671 // even the values that are not available in these blocks may come from them,
6672 // and this leads to false-positive recurrence test.
6673 for (auto *Pred : predecessors(P->getParent()))
6674 if (!DT.isReachableFromEntry(Pred))
6675 return FullSet;
6676
6677 BinaryOperator *BO;
6678 Value *Start, *Step;
6679 if (!matchSimpleRecurrence(P, BO, Start, Step))
6680 return FullSet;
6681
6682 // If we found a recurrence in reachable code, we must be in a loop. Note
6683 // that BO might be in some subloop of L, and that's completely okay.
6684 auto *L = LI.getLoopFor(P->getParent());
6685 assert(L && L->getHeader() == P->getParent());
6686 if (!L->contains(BO->getParent()))
6687 // NOTE: This bailout should be an assert instead. However, asserting
6688 // the condition here exposes a case where LoopFusion is querying SCEV
6689 // with malformed loop information during the midst of the transform.
6690 // There doesn't appear to be an obvious fix, so for the moment bailout
6691 // until the caller issue can be fixed. PR49566 tracks the bug.
6692 return FullSet;
6693
6694 // TODO: Extend to other opcodes such as mul, and div
6695 switch (BO->getOpcode()) {
6696 default:
6697 return FullSet;
6698 case Instruction::AShr:
6699 case Instruction::LShr:
6700 case Instruction::Shl:
6701 break;
6702 };
6703
6704 if (BO->getOperand(0) != P)
6705 // TODO: Handle the power function forms some day.
6706 return FullSet;
6707
6708 unsigned TC = getSmallConstantMaxTripCount(L);
6709 if (!TC || TC >= BitWidth)
6710 return FullSet;
6711
6712 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6713 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6714 assert(KnownStart.getBitWidth() == BitWidth &&
6715 KnownStep.getBitWidth() == BitWidth);
6716
6717 // Compute total shift amount, being careful of overflow and bitwidths.
6718 auto MaxShiftAmt = KnownStep.getMaxValue();
6719 APInt TCAP(BitWidth, TC-1);
6720 bool Overflow = false;
6721 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6722 if (Overflow)
6723 return FullSet;
6724
6725 switch (BO->getOpcode()) {
6726 default:
6727 llvm_unreachable("filtered out above");
6728 case Instruction::AShr: {
6729 // For each ashr, three cases:
6730 // shift = 0 => unchanged value
6731 // saturation => 0 or -1
6732 // other => a value closer to zero (of the same sign)
6733 // Thus, the end value is closer to zero than the start.
6734 auto KnownEnd = KnownBits::ashr(KnownStart,
6735 KnownBits::makeConstant(TotalShift));
6736 if (KnownStart.isNonNegative())
6737 // Analogous to lshr (simply not yet canonicalized)
6738 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6739 KnownStart.getMaxValue() + 1);
6740 if (KnownStart.isNegative())
6741 // End >=u Start && End <=s Start
6742 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6743 KnownEnd.getMaxValue() + 1);
6744 break;
6745 }
6746 case Instruction::LShr: {
6747 // For each lshr, three cases:
6748 // shift = 0 => unchanged value
6749 // saturation => 0
6750 // other => a smaller positive number
6751 // Thus, the low end of the unsigned range is the last value produced.
6752 auto KnownEnd = KnownBits::lshr(KnownStart,
6753 KnownBits::makeConstant(TotalShift));
6754 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6755 KnownStart.getMaxValue() + 1);
6756 }
6757 case Instruction::Shl: {
6758 // Iff no bits are shifted out, value increases on every shift.
6759 auto KnownEnd = KnownBits::shl(KnownStart,
6760 KnownBits::makeConstant(TotalShift));
6761 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6762 return ConstantRange(KnownStart.getMinValue(),
6763 KnownEnd.getMaxValue() + 1);
6764 break;
6765 }
6766 };
6767 return FullSet;
6768}
6769
6770// The goal of this function is to check if recursively visiting the operands
6771// of this PHI might lead to an infinite loop. If we do see such a loop,
6772// there's no good way to break it, so we avoid analyzing such cases.
6773//
6774// getRangeRef previously used a visited set to avoid infinite loops, but this
6775// caused other issues: the result was dependent on the order of getRangeRef
6776// calls, and the interaction with createSCEVIter could cause a stack overflow
6777// in some cases (see issue #148253).
6778//
6779// FIXME: The way this is implemented is overly conservative; this checks
6780// for a few obviously safe patterns, but anything that doesn't lead to
6781// recursion is fine.
6783 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6785 return true;
6786
6787 if (all_of(PHI->operands(),
6788 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6789 return true;
6790
6791 return false;
6792}
6793
6794const ConstantRange &
6795ScalarEvolution::getRangeRefIter(const SCEV *S,
6796 ScalarEvolution::RangeSignHint SignHint) {
6797 DenseMap<const SCEV *, ConstantRange> &Cache =
6798 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6799 : SignedRanges;
6800 SmallVector<SCEVUse> WorkList;
6801 SmallPtrSet<const SCEV *, 8> Seen;
6802
6803 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6804 // SCEVUnknown PHI node.
6805 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6806 if (!Seen.insert(Expr).second)
6807 return;
6808 if (Cache.contains(Expr))
6809 return;
6810 switch (Expr->getSCEVType()) {
6811 case scUnknown:
6813 break;
6814 [[fallthrough]];
6815 case scConstant:
6816 case scVScale:
6817 case scTruncate:
6818 case scZeroExtend:
6819 case scSignExtend:
6820 case scPtrToAddr:
6821 case scPtrToInt:
6822 case scAddExpr:
6823 case scMulExpr:
6824 case scUDivExpr:
6825 case scAddRecExpr:
6826 case scUMaxExpr:
6827 case scSMaxExpr:
6828 case scUMinExpr:
6829 case scSMinExpr:
6831 WorkList.push_back(Expr);
6832 break;
6833 case scCouldNotCompute:
6834 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6835 }
6836 };
6837 AddToWorklist(S);
6838
6839 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6840 for (unsigned I = 0; I != WorkList.size(); ++I) {
6841 const SCEV *P = WorkList[I];
6842 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6843 // If it is not a `SCEVUnknown`, just recurse into operands.
6844 if (!UnknownS) {
6845 for (const SCEV *Op : P->operands())
6846 AddToWorklist(Op);
6847 continue;
6848 }
6849 // `SCEVUnknown`'s require special treatment.
6850 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6851 if (!RangeRefPHIAllowedOperands(DT, P))
6852 continue;
6853 for (auto &Op : reverse(P->operands()))
6854 AddToWorklist(getSCEV(Op));
6855 }
6856 }
6857
6858 if (!WorkList.empty()) {
6859 // Use getRangeRef to compute ranges for items in the worklist in reverse
6860 // order. This will force ranges for earlier operands to be computed before
6861 // their users in most cases.
6862 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6863 getRangeRef(P, SignHint);
6864 }
6865 }
6866
6867 return getRangeRef(S, SignHint, 0);
6868}
6869
6870/// Determine the range for a particular SCEV. If SignHint is
6871/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6872/// with a "cleaner" unsigned (resp. signed) representation.
6873const ConstantRange &ScalarEvolution::getRangeRef(
6874 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6875 DenseMap<const SCEV *, ConstantRange> &Cache =
6876 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6877 : SignedRanges;
6879 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6881
6882 // See if we've computed this range already.
6883 auto I = Cache.find(S);
6884 if (I != Cache.end())
6885 return I->second;
6886
6887 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6888 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6889
6890 // Switch to iteratively computing the range for S, if it is part of a deeply
6891 // nested expression.
6893 return getRangeRefIter(S, SignHint);
6894
6895 unsigned BitWidth = getTypeSizeInBits(S->getType());
6896 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6897 using OBO = OverflowingBinaryOperator;
6898
6899 // If the value has known zeros, the maximum value will have those known zeros
6900 // as well.
6901 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6902 APInt Multiple = getNonZeroConstantMultiple(S);
6903 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6904 if (!Remainder.isZero())
6905 ConservativeResult =
6906 ConstantRange(APInt::getMinValue(BitWidth),
6907 APInt::getMaxValue(BitWidth) - Remainder + 1);
6908 }
6909 else {
6910 uint32_t TZ = getMinTrailingZeros(S);
6911 if (TZ != 0) {
6912 ConservativeResult = ConstantRange(
6914 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6915 }
6916 }
6917
6918 switch (S->getSCEVType()) {
6919 case scConstant:
6920 llvm_unreachable("Already handled above.");
6921 case scVScale:
6922 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6923 case scTruncate: {
6924 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6925 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6926 return setRange(
6927 Trunc, SignHint,
6928 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6929 }
6930 case scZeroExtend: {
6931 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6932 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6933 return setRange(
6934 ZExt, SignHint,
6935 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6936 }
6937 case scSignExtend: {
6938 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6939 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6940 return setRange(
6941 SExt, SignHint,
6942 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6943 }
6944 case scPtrToAddr:
6945 case scPtrToInt: {
6946 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6947 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6948 return setRange(Cast, SignHint, X);
6949 }
6950 case scAddExpr: {
6951 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6952 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6953 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6954 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6955 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6956 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6957 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6958 ConservativeResult =
6959 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6960 }
6961 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6962 unsigned WrapType = OBO::AnyWrap;
6963 if (Add->hasNoSignedWrap())
6964 WrapType |= OBO::NoSignedWrap;
6965 if (Add->hasNoUnsignedWrap())
6966 WrapType |= OBO::NoUnsignedWrap;
6967 for (const SCEV *Op : drop_begin(Add->operands()))
6968 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6969 RangeType);
6970 return setRange(Add, SignHint,
6971 ConservativeResult.intersectWith(X, RangeType));
6972 }
6973 case scMulExpr: {
6974 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6975 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6976 for (const SCEV *Op : drop_begin(Mul->operands()))
6977 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6978 return setRange(Mul, SignHint,
6979 ConservativeResult.intersectWith(X, RangeType));
6980 }
6981 case scUDivExpr: {
6982 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6983 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6984 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6985 return setRange(UDiv, SignHint,
6986 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6987 }
6988 case scAddRecExpr: {
6989 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6990 // If there's no unsigned wrap, the value will never be less than its
6991 // initial value.
6992 if (AddRec->hasNoUnsignedWrap()) {
6993 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6994 if (!UnsignedMinValue.isZero())
6995 ConservativeResult = ConservativeResult.intersectWith(
6996 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6997 }
6998
6999 // If there's no signed wrap, and all the operands except initial value have
7000 // the same sign or zero, the value won't ever be:
7001 // 1: smaller than initial value if operands are non negative,
7002 // 2: bigger than initial value if operands are non positive.
7003 // For both cases, value can not cross signed min/max boundary.
7004 if (AddRec->hasNoSignedWrap()) {
7005 bool AllNonNeg = true;
7006 bool AllNonPos = true;
7007 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
7008 if (!isKnownNonNegative(AddRec->getOperand(i)))
7009 AllNonNeg = false;
7010 if (!isKnownNonPositive(AddRec->getOperand(i)))
7011 AllNonPos = false;
7012 }
7013 if (AllNonNeg)
7014 ConservativeResult = ConservativeResult.intersectWith(
7017 RangeType);
7018 else if (AllNonPos)
7019 ConservativeResult = ConservativeResult.intersectWith(
7021 getSignedRangeMax(AddRec->getStart()) +
7022 1),
7023 RangeType);
7024 }
7025
7026 // TODO: non-affine addrec
7027 if (AddRec->isAffine()) {
7028 const SCEV *MaxBEScev =
7030 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
7031 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
7032
7033 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
7034 // MaxBECount's active bits are all <= AddRec's bit width.
7035 if (MaxBECount.getBitWidth() > BitWidth &&
7036 MaxBECount.getActiveBits() <= BitWidth)
7037 MaxBECount = MaxBECount.trunc(BitWidth);
7038 else if (MaxBECount.getBitWidth() < BitWidth)
7039 MaxBECount = MaxBECount.zext(BitWidth);
7040
7041 if (MaxBECount.getBitWidth() == BitWidth) {
7042 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
7043 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
7044 ConservativeResult =
7045 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
7046 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
7047
7048 auto RangeFromFactoring = getRangeViaFactoring(
7049 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
7050 ConservativeResult =
7051 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
7052 }
7053 }
7054
7055 // Now try symbolic BE count and more powerful methods.
7057 const SCEV *SymbolicMaxBECount =
7059 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
7060 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
7061 AddRec->hasNoSelfWrap()) {
7062 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
7063 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
7064 ConservativeResult =
7065 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
7066 }
7067 }
7068 }
7069
7070 return setRange(AddRec, SignHint, std::move(ConservativeResult));
7071 }
7072 case scUMaxExpr:
7073 case scSMaxExpr:
7074 case scUMinExpr:
7075 case scSMinExpr:
7076 case scSequentialUMinExpr: {
7078 switch (S->getSCEVType()) {
7079 case scUMaxExpr:
7080 ID = Intrinsic::umax;
7081 break;
7082 case scSMaxExpr:
7083 ID = Intrinsic::smax;
7084 break;
7085 case scUMinExpr:
7087 ID = Intrinsic::umin;
7088 break;
7089 case scSMinExpr:
7090 ID = Intrinsic::smin;
7091 break;
7092 default:
7093 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
7094 }
7095
7096 const auto *NAry = cast<SCEVNAryExpr>(S);
7097 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
7098 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
7099 X = X.intrinsic(
7100 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
7101 return setRange(S, SignHint,
7102 ConservativeResult.intersectWith(X, RangeType));
7103 }
7104 case scUnknown: {
7105 const SCEVUnknown *U = cast<SCEVUnknown>(S);
7106 Value *V = U->getValue();
7107
7108 // Check if the IR explicitly contains !range metadata.
7109 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
7110 if (MDRange)
7111 ConservativeResult =
7112 ConservativeResult.intersectWith(*MDRange, RangeType);
7113
7114 // Use facts about recurrences in the underlying IR. Note that add
7115 // recurrences are AddRecExprs and thus don't hit this path. This
7116 // primarily handles shift recurrences.
7117 auto CR = getRangeForUnknownRecurrence(U);
7118 ConservativeResult = ConservativeResult.intersectWith(CR);
7119
7120 // See if ValueTracking can give us a useful range.
7121 const DataLayout &DL = getDataLayout();
7122 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
7123 if (Known.getBitWidth() != BitWidth)
7124 Known = Known.zextOrTrunc(BitWidth);
7125
7126 // ValueTracking may be able to compute a tighter result for the number of
7127 // sign bits than for the value of those sign bits.
7128 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
7129 if (U->getType()->isPointerTy()) {
7130 // If the pointer size is larger than the index size type, this can cause
7131 // NS to be larger than BitWidth. So compensate for this.
7132 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
7133 int ptrIdxDiff = ptrSize - BitWidth;
7134 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
7135 NS -= ptrIdxDiff;
7136 }
7137
7138 if (NS > 1) {
7139 // If we know any of the sign bits, we know all of the sign bits.
7140 if (!Known.Zero.getHiBits(NS).isZero())
7141 Known.Zero.setHighBits(NS);
7142 if (!Known.One.getHiBits(NS).isZero())
7143 Known.One.setHighBits(NS);
7144 }
7145
7146 if (Known.getMinValue() != Known.getMaxValue() + 1)
7147 ConservativeResult = ConservativeResult.intersectWith(
7148 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
7149 RangeType);
7150 if (NS > 1)
7151 ConservativeResult = ConservativeResult.intersectWith(
7152 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
7153 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
7154 RangeType);
7155
7156 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
7157 // Strengthen the range if the underlying IR value is a
7158 // global/alloca/heap allocation using the size of the object.
7159 bool CanBeNull;
7160 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
7161 DL, CanBeNull, /*CanBeFreed=*/nullptr);
7162 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
7163 // The highest address the object can start is DerefBytes bytes before
7164 // the end (unsigned max value). If this value is not a multiple of the
7165 // alignment, the last possible start value is the next lowest multiple
7166 // of the alignment. Note: The computations below cannot overflow,
7167 // because if they would there's no possible start address for the
7168 // object.
7169 APInt MaxVal =
7170 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
7171 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
7172 uint64_t Rem = MaxVal.urem(Align);
7173 MaxVal -= APInt(BitWidth, Rem);
7174 APInt MinVal = APInt::getZero(BitWidth);
7175 if (llvm::isKnownNonZero(V, DL))
7176 MinVal = Align;
7177 ConservativeResult = ConservativeResult.intersectWith(
7178 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
7179 }
7180 }
7181
7182 // A range of Phi is a subset of union of all ranges of its input.
7183 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
7184 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
7185 // AddRecs; return the range for the corresponding AddRec.
7186 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
7187 return getRangeRef(AR, SignHint, Depth + 1);
7188
7189 // Make sure that we do not run over cycled Phis.
7190 if (RangeRefPHIAllowedOperands(DT, Phi)) {
7191 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
7192
7193 for (const auto &Op : Phi->operands()) {
7194 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
7195 RangeFromOps = RangeFromOps.unionWith(OpRange);
7196 // No point to continue if we already have a full set.
7197 if (RangeFromOps.isFullSet())
7198 break;
7199 }
7200 ConservativeResult =
7201 ConservativeResult.intersectWith(RangeFromOps, RangeType);
7202 }
7203 }
7204
7205 // vscale can't be equal to zero
7206 if (const auto *II = dyn_cast<IntrinsicInst>(V))
7207 if (II->getIntrinsicID() == Intrinsic::vscale) {
7208 ConstantRange Disallowed = APInt::getZero(BitWidth);
7209 ConservativeResult = ConservativeResult.difference(Disallowed);
7210 }
7211
7212 return setRange(U, SignHint, std::move(ConservativeResult));
7213 }
7214 case scCouldNotCompute:
7215 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7216 }
7217
7218 return setRange(S, SignHint, std::move(ConservativeResult));
7219}
7220
7221// Given a StartRange, Step and MaxBECount for an expression compute a range of
7222// values that the expression can take. Initially, the expression has a value
7223// from StartRange and then is changed by Step up to MaxBECount times. Signed
7224// argument defines if we treat Step as signed or unsigned. The second return
7225// value indicates that no wrapping occurred.
7226static std::pair<ConstantRange, bool>
7228 const APInt &MaxBECount, bool Signed) {
7229 unsigned BitWidth = Step.getBitWidth();
7230 assert(BitWidth == StartRange.getBitWidth() &&
7231 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7232 // If either Step or MaxBECount is 0, then the expression won't change, and we
7233 // just need to return the initial range.
7234 if (Step == 0 || MaxBECount == 0)
7235 return {StartRange, true};
7236
7237 // If we don't know anything about the initial value (i.e. StartRange is
7238 // FullRange), then we don't know anything about the final range either.
7239 // Return FullRange.
7240 if (StartRange.isFullSet())
7241 return {ConstantRange::getFull(BitWidth), false};
7242
7243 // If Step is signed and negative, then we use its absolute value, but we also
7244 // note that we're moving in the opposite direction.
7245 bool Descending = Signed && Step.isNegative();
7246
7247 if (Signed)
7248 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7249 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7250 // This equations hold true due to the well-defined wrap-around behavior of
7251 // APInt.
7252 Step = Step.abs();
7253
7254 // Check if Offset is more than full span of BitWidth. If it is, the
7255 // expression is guaranteed to overflow.
7256 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7257 return {ConstantRange::getFull(BitWidth), false};
7258
7259 // Offset is by how much the expression can change. Checks above guarantee no
7260 // overflow here.
7261 APInt Offset = Step * MaxBECount;
7262
7263 // Minimum value of the final range will match the minimal value of StartRange
7264 // if the expression is increasing and will be decreased by Offset otherwise.
7265 // Maximum value of the final range will match the maximal value of StartRange
7266 // if the expression is decreasing and will be increased by Offset otherwise.
7267 APInt StartLower = StartRange.getLower();
7268 APInt StartUpper = StartRange.getUpper() - 1;
7269 bool Overflow;
7270 APInt MovedBoundary;
7271 if (Signed) {
7272 // This does not use sadd_ov, as we want to check overflow for a signed
7273 // start with an unsigned offset.
7274 if (Descending) {
7275 MovedBoundary = StartLower - std::move(Offset);
7276 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7277 } else {
7278 MovedBoundary = StartUpper + std::move(Offset);
7279 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7280 }
7281 } else {
7282 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7283 Overflow |= StartRange.isWrappedSet();
7284 }
7285
7286 // It's possible that the new minimum/maximum value will fall into the initial
7287 // range (due to wrap around). This means that the expression can take any
7288 // value in this bitwidth, and we have to return full range.
7289 if (StartRange.contains(MovedBoundary))
7290 return {ConstantRange::getFull(BitWidth), false};
7291
7292 APInt NewLower =
7293 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7294 APInt NewUpper =
7295 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7296 NewUpper += 1;
7297
7298 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7299 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7300 !Overflow};
7301}
7302
7303std::pair<ConstantRange, SCEV::NoWrapFlags>
7304ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7305 const APInt &MaxBECount) {
7306 assert(getTypeSizeInBits(Start->getType()) ==
7307 getTypeSizeInBits(Step->getType()) &&
7308 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7309 "mismatched bit widths");
7310
7311 // First, consider step signed.
7312 ConstantRange StartSRange = getSignedRange(Start);
7313 ConstantRange StepSRange = getSignedRange(Step);
7314
7315 // If Step can be both positive and negative, we need to find ranges for the
7316 // maximum absolute step values in both directions and union them.
7317 auto [SR1, NSW1] = getRangeForAffineARHelper(
7318 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7319 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7320 StartSRange, MaxBECount,
7321 /*Signed=*/true);
7322 ConstantRange SR = SR1.unionWith(SR2);
7323
7324 // Next, consider step unsigned.
7325 auto [UR, NUW] = getRangeForAffineARHelper(
7326 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7327 /*Signed=*/false);
7328
7330 if (NUW)
7332 if (NSW1 && NSW2)
7334
7335 // Finally, intersect signed and unsigned ranges.
7337}
7338
7339ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7340 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7341 ScalarEvolution::RangeSignHint SignHint) {
7342 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7343 assert(AddRec->hasNoSelfWrap() &&
7344 "This only works for non-self-wrapping AddRecs!");
7345 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7346 const SCEV *Step = AddRec->getStepRecurrence(*this);
7347 // Only deal with constant step to save compile time.
7348 if (!isa<SCEVConstant>(Step))
7349 return ConstantRange::getFull(BitWidth);
7350 // Let's make sure that we can prove that we do not self-wrap during
7351 // MaxBECount iterations. We need this because MaxBECount is a maximum
7352 // iteration count estimate, and we might infer nw from some exit for which we
7353 // do not know max exit count (or any other side reasoning).
7354 // TODO: Turn into assert at some point.
7355 if (getTypeSizeInBits(MaxBECount->getType()) >
7356 getTypeSizeInBits(AddRec->getType()))
7357 return ConstantRange::getFull(BitWidth);
7358 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7359 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7360 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7361 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7362 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7363 MaxItersWithoutWrap))
7364 return ConstantRange::getFull(BitWidth);
7365
7366 ICmpInst::Predicate LEPred =
7368 ICmpInst::Predicate GEPred =
7370 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7371
7372 // We know that there is no self-wrap. Let's take Start and End values and
7373 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7374 // the iteration. They either lie inside the range [Min(Start, End),
7375 // Max(Start, End)] or outside it:
7376 //
7377 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7378 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7379 //
7380 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7381 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7382 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7383 // Start <= End and step is positive, or Start >= End and step is negative.
7384 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7385 ConstantRange StartRange = getRangeRef(Start, SignHint);
7386 ConstantRange EndRange = getRangeRef(End, SignHint);
7387 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7388 // If they already cover full iteration space, we will know nothing useful
7389 // even if we prove what we want to prove.
7390 if (RangeBetween.isFullSet())
7391 return RangeBetween;
7392 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7393 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7394 : RangeBetween.isWrappedSet();
7395 if (IsWrappedSet)
7396 return ConstantRange::getFull(BitWidth);
7397
7398 if (isKnownPositive(Step) &&
7399 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7400 return RangeBetween;
7401 if (isKnownNegative(Step) &&
7402 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7403 return RangeBetween;
7404 return ConstantRange::getFull(BitWidth);
7405}
7406
7407ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7408 const SCEV *Step,
7409 const APInt &MaxBECount) {
7410 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7411 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7412
7413 unsigned BitWidth = MaxBECount.getBitWidth();
7414 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7415 getTypeSizeInBits(Step->getType()) == BitWidth &&
7416 "mismatched bit widths");
7417
7418 struct SelectPattern {
7419 Value *Condition = nullptr;
7420 APInt TrueValue;
7421 APInt FalseValue;
7422
7423 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7424 const SCEV *S) {
7425 std::optional<unsigned> CastOp;
7426 APInt Offset(BitWidth, 0);
7427
7429 "Should be!");
7430
7431 // Peel off a constant offset. In the future we could consider being
7432 // smarter here and handle {Start+Step,+,Step} too.
7433 const APInt *Off;
7434 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7435 Offset = *Off;
7436
7437 // Peel off a cast operation
7438 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7439 CastOp = SCast->getSCEVType();
7440 S = SCast->getOperand();
7441 }
7442
7443 using namespace llvm::PatternMatch;
7444
7445 auto *SU = dyn_cast<SCEVUnknown>(S);
7446 const APInt *TrueVal, *FalseVal;
7447 if (!SU ||
7448 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7449 m_APInt(FalseVal)))) {
7450 Condition = nullptr;
7451 return;
7452 }
7453
7454 TrueValue = *TrueVal;
7455 FalseValue = *FalseVal;
7456
7457 // Re-apply the cast we peeled off earlier
7458 if (CastOp)
7459 switch (*CastOp) {
7460 default:
7461 llvm_unreachable("Unknown SCEV cast type!");
7462
7463 case scTruncate:
7464 TrueValue = TrueValue.trunc(BitWidth);
7465 FalseValue = FalseValue.trunc(BitWidth);
7466 break;
7467 case scZeroExtend:
7468 TrueValue = TrueValue.zext(BitWidth);
7469 FalseValue = FalseValue.zext(BitWidth);
7470 break;
7471 case scSignExtend:
7472 TrueValue = TrueValue.sext(BitWidth);
7473 FalseValue = FalseValue.sext(BitWidth);
7474 break;
7475 }
7476
7477 // Re-apply the constant offset we peeled off earlier
7478 TrueValue += Offset;
7479 FalseValue += Offset;
7480 }
7481
7482 bool isRecognized() { return Condition != nullptr; }
7483 };
7484
7485 SelectPattern StartPattern(*this, BitWidth, Start);
7486 if (!StartPattern.isRecognized())
7487 return ConstantRange::getFull(BitWidth);
7488
7489 SelectPattern StepPattern(*this, BitWidth, Step);
7490 if (!StepPattern.isRecognized())
7491 return ConstantRange::getFull(BitWidth);
7492
7493 if (StartPattern.Condition != StepPattern.Condition) {
7494 // We don't handle this case today; but we could, by considering four
7495 // possibilities below instead of two. I'm not sure if there are cases where
7496 // that will help over what getRange already does, though.
7497 return ConstantRange::getFull(BitWidth);
7498 }
7499
7500 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7501 // construct arbitrary general SCEV expressions here. This function is called
7502 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7503 // say) can end up caching a suboptimal value.
7504
7505 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7506 // C2352 and C2512 (otherwise it isn't needed).
7507
7508 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7509 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7510 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7511 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7512
7513 ConstantRange TrueRange =
7514 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7515 ConstantRange FalseRange =
7516 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7517
7518 return TrueRange.unionWith(FalseRange);
7519}
7520
7521SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7522 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7523 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7524
7525 // Return early if there are no flags to propagate to the SCEV.
7527 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7528 PDI && PDI->isDisjoint()) {
7530 } else {
7531 if (BinOp->hasNoUnsignedWrap())
7533 if (BinOp->hasNoSignedWrap())
7535 }
7536 if (Flags == SCEV::FlagAnyWrap)
7537 return SCEV::FlagAnyWrap;
7538
7539 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7540}
7541
7542const Instruction *
7543ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7544 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7545 return &*AddRec->getLoop()->getHeader()->begin();
7546 if (auto *U = dyn_cast<SCEVUnknown>(S))
7547 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7548 return I;
7549 return nullptr;
7550}
7551
7552const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7553 bool &Precise) {
7554 Precise = true;
7555 // Do a bounded search of the def relation of the requested SCEVs.
7556 SmallPtrSet<const SCEV *, 16> Visited;
7557 SmallVector<SCEVUse> Worklist;
7558 auto pushOp = [&](const SCEV *S) {
7559 if (!Visited.insert(S).second)
7560 return;
7561 // Threshold of 30 here is arbitrary.
7562 if (Visited.size() > 30) {
7563 Precise = false;
7564 return;
7565 }
7566 Worklist.push_back(S);
7567 };
7568
7569 for (SCEVUse S : Ops)
7570 pushOp(S);
7571
7572 const Instruction *Bound = nullptr;
7573 while (!Worklist.empty()) {
7574 SCEVUse S = Worklist.pop_back_val();
7575 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7576 if (!Bound || DT.dominates(Bound, DefI))
7577 Bound = DefI;
7578 } else {
7579 for (SCEVUse Op : S->operands())
7580 pushOp(Op);
7581 }
7582 }
7583 return Bound ? Bound : &*F.getEntryBlock().begin();
7584}
7585
7586const Instruction *
7587ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7588 bool Discard;
7589 return getDefiningScopeBound(Ops, Discard);
7590}
7591
7592bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7593 const Instruction *B) {
7594 if (A->getParent() == B->getParent() &&
7596 B->getIterator()))
7597 return true;
7598
7599 auto *BLoop = LI.getLoopFor(B->getParent());
7600 if (BLoop && BLoop->getHeader() == B->getParent() &&
7601 BLoop->getLoopPreheader() == A->getParent() &&
7603 A->getParent()->end()) &&
7604 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7605 B->getIterator()))
7606 return true;
7607 return false;
7608}
7609
7611 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7612 visitAll(Op, PC);
7613 return PC.MaybePoison.empty();
7614}
7615
7616bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7617 return !SCEVExprContains(Op, [this](const SCEV *S) {
7618 const SCEV *Op1;
7619 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7620 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7621 // is a non-zero constant, we have to assume the UDiv may be UB.
7622 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7623 });
7624}
7625
7626bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7627 // Only proceed if we can prove that I does not yield poison.
7629 return false;
7630
7631 // At this point we know that if I is executed, then it does not wrap
7632 // according to at least one of NSW or NUW. If I is not executed, then we do
7633 // not know if the calculation that I represents would wrap. Multiple
7634 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7635 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7636 // derived from other instructions that map to the same SCEV. We cannot make
7637 // that guarantee for cases where I is not executed. So we need to find a
7638 // upper bound on the defining scope for the SCEV, and prove that I is
7639 // executed every time we enter that scope. When the bounding scope is a
7640 // loop (the common case), this is equivalent to proving I executes on every
7641 // iteration of that loop.
7642 SmallVector<SCEVUse> SCEVOps;
7643 for (const Use &Op : I->operands()) {
7644 // I could be an extractvalue from a call to an overflow intrinsic.
7645 // TODO: We can do better here in some cases.
7646 if (isSCEVable(Op->getType()))
7647 SCEVOps.push_back(getSCEV(Op));
7648 }
7649 auto *DefI = getDefiningScopeBound(SCEVOps);
7650 return isGuaranteedToTransferExecutionTo(DefI, I);
7651}
7652
7653bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7654 // If we know that \c I can never be poison period, then that's enough.
7655 if (isSCEVExprNeverPoison(I))
7656 return true;
7657
7658 // If the loop only has one exit, then we know that, if the loop is entered,
7659 // any instruction dominating that exit will be executed. If any such
7660 // instruction would result in UB, the addrec cannot be poison.
7661 //
7662 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7663 // also handles uses outside the loop header (they just need to dominate the
7664 // single exit).
7665
7666 auto *ExitingBB = L->getExitingBlock();
7667 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7668 return false;
7669
7670 SmallPtrSet<const Value *, 16> KnownPoison;
7672
7673 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7674 // things that are known to be poison under that assumption go on the
7675 // Worklist.
7676 KnownPoison.insert(I);
7677 Worklist.push_back(I);
7678
7679 while (!Worklist.empty()) {
7680 const Instruction *Poison = Worklist.pop_back_val();
7681
7682 for (const Use &U : Poison->uses()) {
7683 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7684 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7685 DT.dominates(PoisonUser->getParent(), ExitingBB))
7686 return true;
7687
7688 if (propagatesPoison(U) && L->contains(PoisonUser))
7689 if (KnownPoison.insert(PoisonUser).second)
7690 Worklist.push_back(PoisonUser);
7691 }
7692 }
7693
7694 return false;
7695}
7696
7697ScalarEvolution::LoopProperties
7698ScalarEvolution::getLoopProperties(const Loop *L) {
7699 using LoopProperties = ScalarEvolution::LoopProperties;
7700
7701 auto Itr = LoopPropertiesCache.find(L);
7702 if (Itr == LoopPropertiesCache.end()) {
7703 auto HasSideEffects = [](Instruction *I) {
7704 if (auto *SI = dyn_cast<StoreInst>(I))
7705 return !SI->isSimple();
7706
7707 if (I->mayThrow())
7708 return true;
7709
7710 // Non-volatile memset / memcpy do not count as side-effect for forward
7711 // progress.
7712 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7713 return false;
7714
7715 return I->mayWriteToMemory();
7716 };
7717
7718 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7719 /*HasNoSideEffects*/ true};
7720
7721 for (auto *BB : L->getBlocks())
7722 for (auto &I : *BB) {
7724 LP.HasNoAbnormalExits = false;
7725 if (HasSideEffects(&I))
7726 LP.HasNoSideEffects = false;
7727 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7728 break; // We're already as pessimistic as we can get.
7729 }
7730
7731 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7732 assert(InsertPair.second && "We just checked!");
7733 Itr = InsertPair.first;
7734 }
7735
7736 return Itr->second;
7737}
7738
7740 // A mustprogress loop without side effects must be finite.
7741 // TODO: The check used here is very conservative. It's only *specific*
7742 // side effects which are well defined in infinite loops.
7743 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7744}
7745
7746const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7747 // Worklist item with a Value and a bool indicating whether all operands have
7748 // been visited already.
7751
7752 Stack.emplace_back(V, false);
7753 while (!Stack.empty()) {
7754 auto E = Stack.back();
7755 Value *CurV = E.getPointer();
7756
7757 if (getExistingSCEV(CurV)) {
7758 Stack.pop_back();
7759 continue;
7760 }
7761
7763 const SCEV *CreatedSCEV = nullptr;
7764 // If all operands have been visited already, create the SCEV.
7765 if (E.getInt()) {
7766 CreatedSCEV = createSCEV(CurV);
7767 } else {
7768 // Otherwise get the operands we need to create SCEV's for before creating
7769 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7770 // just use it.
7771 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7772 }
7773
7774 if (CreatedSCEV) {
7775 insertValueToMap(CurV, CreatedSCEV);
7776 Stack.pop_back();
7777 } else {
7778 Stack.back().setInt(true);
7779 // Queue its operands which need to be constructed.
7780 for (Value *Op : Ops)
7781 Stack.emplace_back(Op, false);
7782 }
7783 }
7784
7785 return getExistingSCEV(V);
7786}
7787
7788const SCEV *
7789ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7790 if (!isSCEVable(V->getType()))
7791 return getUnknown(V);
7792
7793 if (Instruction *I = dyn_cast<Instruction>(V)) {
7794 // Don't attempt to analyze instructions in blocks that aren't
7795 // reachable. Such instructions don't matter, and they aren't required
7796 // to obey basic rules for definitions dominating uses which this
7797 // analysis depends on.
7798 if (!DT.isReachableFromEntry(I->getParent()))
7799 return getUnknown(PoisonValue::get(V->getType()));
7800 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7801 return getConstant(CI);
7802 else if (isa<GlobalAlias>(V))
7803 return getUnknown(V);
7804 else if (!isa<ConstantExpr>(V))
7805 return getUnknown(V);
7806
7808 if (auto BO =
7810 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7811 switch (BO->Opcode) {
7812 case Instruction::Add:
7813 case Instruction::Mul: {
7814 // For additions and multiplications, traverse add/mul chains for which we
7815 // can potentially create a single SCEV, to reduce the number of
7816 // get{Add,Mul}Expr calls.
7817 do {
7818 if (BO->Op) {
7819 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7820 Ops.push_back(BO->Op);
7821 break;
7822 }
7823 }
7824 Ops.push_back(BO->RHS);
7825 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7827 if (!NewBO ||
7828 (BO->Opcode == Instruction::Add &&
7829 (NewBO->Opcode != Instruction::Add &&
7830 NewBO->Opcode != Instruction::Sub)) ||
7831 (BO->Opcode == Instruction::Mul &&
7832 NewBO->Opcode != Instruction::Mul)) {
7833 Ops.push_back(BO->LHS);
7834 break;
7835 }
7836 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7837 // requires a SCEV for the LHS.
7838 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7839 auto *I = dyn_cast<Instruction>(BO->Op);
7840 if (I && programUndefinedIfPoison(I)) {
7841 Ops.push_back(BO->LHS);
7842 break;
7843 }
7844 }
7845 BO = NewBO;
7846 } while (true);
7847 return nullptr;
7848 }
7849 case Instruction::Sub:
7850 case Instruction::UDiv:
7851 case Instruction::URem:
7852 break;
7853 case Instruction::AShr:
7854 case Instruction::Shl:
7855 case Instruction::Xor:
7856 if (!IsConstArg)
7857 return nullptr;
7858 break;
7859 case Instruction::And:
7860 case Instruction::Or:
7861 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7862 return nullptr;
7863 break;
7864 case Instruction::LShr:
7865 return getUnknown(V);
7866 default:
7867 llvm_unreachable("Unhandled binop");
7868 break;
7869 }
7870
7871 Ops.push_back(BO->LHS);
7872 Ops.push_back(BO->RHS);
7873 return nullptr;
7874 }
7875
7876 switch (U->getOpcode()) {
7877 case Instruction::Trunc:
7878 case Instruction::ZExt:
7879 case Instruction::SExt:
7880 case Instruction::PtrToAddr:
7881 case Instruction::PtrToInt:
7882 Ops.push_back(U->getOperand(0));
7883 return nullptr;
7884
7885 case Instruction::BitCast:
7886 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7887 Ops.push_back(U->getOperand(0));
7888 return nullptr;
7889 }
7890 return getUnknown(V);
7891
7892 case Instruction::SDiv:
7893 case Instruction::SRem:
7894 Ops.push_back(U->getOperand(0));
7895 Ops.push_back(U->getOperand(1));
7896 return nullptr;
7897
7898 case Instruction::GetElementPtr:
7899 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7900 "GEP source element type must be sized");
7901 llvm::append_range(Ops, U->operands());
7902 return nullptr;
7903
7904 case Instruction::IntToPtr:
7905 return getUnknown(V);
7906
7907 case Instruction::PHI:
7908 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7909 // relevant nodes for each of them.
7910 //
7911 // The first is just to call simplifyInstruction, and get something back
7912 // that isn't a PHI.
7913 if (Value *V = simplifyInstruction(
7914 cast<PHINode>(U),
7915 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7916 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7917 assert(V);
7918 Ops.push_back(V);
7919 return nullptr;
7920 }
7921 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7922 // operands which all perform the same operation, but haven't been
7923 // CSE'ed for whatever reason.
7924 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7925 assert(BO);
7926 Ops.push_back(BO);
7927 return nullptr;
7928 }
7929 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7930 // is equivalent to a select, and analyzes it like a select.
7931 {
7932 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7934 assert(Cond);
7935 assert(LHS);
7936 assert(RHS);
7937 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7938 Ops.push_back(CondICmp->getOperand(0));
7939 Ops.push_back(CondICmp->getOperand(1));
7940 }
7941 Ops.push_back(Cond);
7942 Ops.push_back(LHS);
7943 Ops.push_back(RHS);
7944 return nullptr;
7945 }
7946 }
7947 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7948 // so just construct it recursively.
7949 //
7950 // In addition to getNodeForPHI, also construct nodes which might be needed
7951 // by getRangeRef.
7953 for (Value *V : cast<PHINode>(U)->operands())
7954 Ops.push_back(V);
7955 return nullptr;
7956 }
7957 return nullptr;
7958
7959 case Instruction::Select: {
7960 // Check if U is a select that can be simplified to a SCEVUnknown.
7961 auto CanSimplifyToUnknown = [this, U]() {
7962 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7963 return false;
7964
7965 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7966 if (!ICI)
7967 return false;
7968 Value *LHS = ICI->getOperand(0);
7969 Value *RHS = ICI->getOperand(1);
7970 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7971 ICI->getPredicate() == CmpInst::ICMP_NE) {
7973 return true;
7974 } else if (getTypeSizeInBits(LHS->getType()) >
7975 getTypeSizeInBits(U->getType()))
7976 return true;
7977 return false;
7978 };
7979 if (CanSimplifyToUnknown())
7980 return getUnknown(U);
7981
7982 llvm::append_range(Ops, U->operands());
7983 return nullptr;
7984 break;
7985 }
7986 case Instruction::Call:
7987 case Instruction::Invoke:
7988 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7989 Ops.push_back(RV);
7990 return nullptr;
7991 }
7992
7993 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7994 switch (II->getIntrinsicID()) {
7995 case Intrinsic::abs:
7996 Ops.push_back(II->getArgOperand(0));
7997 return nullptr;
7998 case Intrinsic::umax:
7999 case Intrinsic::umin:
8000 case Intrinsic::smax:
8001 case Intrinsic::smin:
8002 case Intrinsic::usub_sat:
8003 case Intrinsic::uadd_sat:
8004 Ops.push_back(II->getArgOperand(0));
8005 Ops.push_back(II->getArgOperand(1));
8006 return nullptr;
8007 case Intrinsic::start_loop_iterations:
8008 case Intrinsic::annotation:
8009 case Intrinsic::ptr_annotation:
8010 Ops.push_back(II->getArgOperand(0));
8011 return nullptr;
8012 default:
8013 break;
8014 }
8015 }
8016 break;
8017 }
8018
8019 return nullptr;
8020}
8021
8022const SCEV *ScalarEvolution::createSCEV(Value *V) {
8023 if (!isSCEVable(V->getType()))
8024 return getUnknown(V);
8025
8026 if (Instruction *I = dyn_cast<Instruction>(V)) {
8027 // Don't attempt to analyze instructions in blocks that aren't
8028 // reachable. Such instructions don't matter, and they aren't required
8029 // to obey basic rules for definitions dominating uses which this
8030 // analysis depends on.
8031 if (!DT.isReachableFromEntry(I->getParent()))
8032 return getUnknown(PoisonValue::get(V->getType()));
8033 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
8034 return getConstant(CI);
8035 else if (isa<GlobalAlias>(V))
8036 return getUnknown(V);
8037 else if (!isa<ConstantExpr>(V))
8038 return getUnknown(V);
8039
8040 const SCEV *LHS;
8041 const SCEV *RHS;
8042
8044 if (auto BO =
8046 switch (BO->Opcode) {
8047 case Instruction::Add: {
8048 // The simple thing to do would be to just call getSCEV on both operands
8049 // and call getAddExpr with the result. However if we're looking at a
8050 // bunch of things all added together, this can be quite inefficient,
8051 // because it leads to N-1 getAddExpr calls for N ultimate operands.
8052 // Instead, gather up all the operands and make a single getAddExpr call.
8053 // LLVM IR canonical form means we need only traverse the left operands.
8055 do {
8056 if (BO->Op) {
8057 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
8058 AddOps.push_back(OpSCEV);
8059 break;
8060 }
8061
8062 // If a NUW or NSW flag can be applied to the SCEV for this
8063 // addition, then compute the SCEV for this addition by itself
8064 // with a separate call to getAddExpr. We need to do that
8065 // instead of pushing the operands of the addition onto AddOps,
8066 // since the flags are only known to apply to this particular
8067 // addition - they may not apply to other additions that can be
8068 // formed with operands from AddOps.
8069 const SCEV *RHS = getSCEV(BO->RHS);
8070 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
8071 if (Flags != SCEV::FlagAnyWrap) {
8072 const SCEV *LHS = getSCEV(BO->LHS);
8073 if (BO->Opcode == Instruction::Sub)
8074 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
8075 else
8076 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
8077 break;
8078 }
8079 }
8080
8081 if (BO->Opcode == Instruction::Sub)
8082 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
8083 else
8084 AddOps.push_back(getSCEV(BO->RHS));
8085
8086 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
8088 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
8089 NewBO->Opcode != Instruction::Sub)) {
8090 AddOps.push_back(getSCEV(BO->LHS));
8091 break;
8092 }
8093 BO = NewBO;
8094 } while (true);
8095
8096 return getAddExpr(AddOps);
8097 }
8098
8099 case Instruction::Mul: {
8101 do {
8102 if (BO->Op) {
8103 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
8104 MulOps.push_back(OpSCEV);
8105 break;
8106 }
8107
8108 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
8109 if (Flags != SCEV::FlagAnyWrap) {
8110 LHS = getSCEV(BO->LHS);
8111 RHS = getSCEV(BO->RHS);
8112 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
8113 break;
8114 }
8115 }
8116
8117 MulOps.push_back(getSCEV(BO->RHS));
8118 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
8120 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
8121 MulOps.push_back(getSCEV(BO->LHS));
8122 break;
8123 }
8124 BO = NewBO;
8125 } while (true);
8126
8127 return getMulExpr(MulOps);
8128 }
8129 case Instruction::UDiv:
8130 LHS = getSCEV(BO->LHS);
8131 RHS = getSCEV(BO->RHS);
8132 return getUDivExpr(LHS, RHS);
8133 case Instruction::URem:
8134 LHS = getSCEV(BO->LHS);
8135 RHS = getSCEV(BO->RHS);
8136 return getURemExpr(LHS, RHS);
8137 case Instruction::Sub: {
8139 if (BO->Op)
8140 Flags = getNoWrapFlagsFromUB(BO->Op);
8141 LHS = getSCEV(BO->LHS);
8142 RHS = getSCEV(BO->RHS);
8143 return getMinusSCEV(LHS, RHS, Flags);
8144 }
8145 case Instruction::And:
8146 // For an expression like x&255 that merely masks off the high bits,
8147 // use zext(trunc(x)) as the SCEV expression.
8148 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8149 if (CI->isZero())
8150 return getSCEV(BO->RHS);
8151 if (CI->isMinusOne())
8152 return getSCEV(BO->LHS);
8153 const APInt &A = CI->getValue();
8154
8155 // Instcombine's ShrinkDemandedConstant may strip bits out of
8156 // constants, obscuring what would otherwise be a low-bits mask.
8157 // Use computeKnownBits to compute what ShrinkDemandedConstant
8158 // knew about to reconstruct a low-bits mask value.
8159 unsigned LZ = A.countl_zero();
8160 unsigned TZ = A.countr_zero();
8161 unsigned BitWidth = A.getBitWidth();
8162 KnownBits Known(BitWidth);
8163 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
8164
8165 APInt EffectiveMask =
8166 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
8167 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
8168 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
8169 const SCEV *LHS = getSCEV(BO->LHS);
8170 const SCEV *ShiftedLHS = nullptr;
8171 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
8172 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
8173 // For an expression like (x * 8) & 8, simplify the multiply.
8174 unsigned MulZeros = OpC->getAPInt().countr_zero();
8175 unsigned GCD = std::min(MulZeros, TZ);
8176 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
8178 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
8179 append_range(MulOps, LHSMul->operands().drop_front());
8180 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
8181 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
8182 }
8183 }
8184 if (!ShiftedLHS)
8185 ShiftedLHS = getUDivExpr(LHS, MulCount);
8186 return getMulExpr(
8188 getTruncateExpr(ShiftedLHS,
8189 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
8190 BO->LHS->getType()),
8191 MulCount);
8192 }
8193 }
8194 // Binary `and` is a bit-wise `umin`.
8195 if (BO->LHS->getType()->isIntegerTy(1)) {
8196 LHS = getSCEV(BO->LHS);
8197 RHS = getSCEV(BO->RHS);
8198 return getUMinExpr(LHS, RHS);
8199 }
8200 break;
8201
8202 case Instruction::Or:
8203 // Binary `or` is a bit-wise `umax`.
8204 if (BO->LHS->getType()->isIntegerTy(1)) {
8205 LHS = getSCEV(BO->LHS);
8206 RHS = getSCEV(BO->RHS);
8207 return getUMaxExpr(LHS, RHS);
8208 }
8209 break;
8210
8211 case Instruction::Xor:
8212 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8213 // If the RHS of xor is -1, then this is a not operation.
8214 if (CI->isMinusOne())
8215 return getNotSCEV(getSCEV(BO->LHS));
8216
8217 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8218 // This is a variant of the check for xor with -1, and it handles
8219 // the case where instcombine has trimmed non-demanded bits out
8220 // of an xor with -1.
8221 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8222 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8223 if (LBO->getOpcode() == Instruction::And &&
8224 LCI->getValue() == CI->getValue())
8225 if (const SCEVZeroExtendExpr *Z =
8227 Type *UTy = BO->LHS->getType();
8228 const SCEV *Z0 = Z->getOperand();
8229 Type *Z0Ty = Z0->getType();
8230 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8231
8232 // If C is a low-bits mask, the zero extend is serving to
8233 // mask off the high bits. Complement the operand and
8234 // re-apply the zext.
8235 if (CI->getValue().isMask(Z0TySize))
8236 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8237
8238 // If C is a single bit, it may be in the sign-bit position
8239 // before the zero-extend. In this case, represent the xor
8240 // using an add, which is equivalent, and re-apply the zext.
8241 APInt Trunc = CI->getValue().trunc(Z0TySize);
8242 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8243 Trunc.isSignMask())
8244 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8245 UTy);
8246 }
8247 }
8248 break;
8249
8250 case Instruction::Shl:
8251 // Turn shift left of a constant amount into a multiply.
8252 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8253 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8254
8255 // If the shift count is not less than the bitwidth, the result of
8256 // the shift is undefined. Don't try to analyze it, because the
8257 // resolution chosen here may differ from the resolution chosen in
8258 // other parts of the compiler.
8259 if (SA->getValue().uge(BitWidth))
8260 break;
8261
8262 // We can safely preserve the nuw flag in all cases. It's also safe to
8263 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8264 // requires special handling. It can be preserved as long as we're not
8265 // left shifting by bitwidth - 1.
8266 auto Flags = SCEV::FlagAnyWrap;
8267 if (BO->Op) {
8268 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8269 if (any(MulFlags & SCEV::FlagNSW) &&
8270 (any(MulFlags & SCEV::FlagNUW) ||
8271 SA->getValue().ult(BitWidth - 1)))
8273 if (any(MulFlags & SCEV::FlagNUW))
8275 }
8276
8277 ConstantInt *X = ConstantInt::get(
8278 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8279 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8280 }
8281 break;
8282
8283 case Instruction::AShr:
8284 // AShr X, C, where C is a constant.
8285 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8286 if (!CI)
8287 break;
8288
8289 Type *OuterTy = BO->LHS->getType();
8290 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
8291 // If the shift count is not less than the bitwidth, the result of
8292 // the shift is undefined. Don't try to analyze it, because the
8293 // resolution chosen here may differ from the resolution chosen in
8294 // other parts of the compiler.
8295 if (CI->getValue().uge(BitWidth))
8296 break;
8297
8298 if (CI->isZero())
8299 return getSCEV(BO->LHS); // shift by zero --> noop
8300
8301 uint64_t AShrAmt = CI->getZExtValue();
8302 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8303
8304 Operator *L = dyn_cast<Operator>(BO->LHS);
8305 const SCEV *AddTruncateExpr = nullptr;
8306 ConstantInt *ShlAmtCI = nullptr;
8307 const SCEV *AddConstant = nullptr;
8308
8309 if (L && L->getOpcode() == Instruction::Add) {
8310 // X = Shl A, n
8311 // Y = Add X, c
8312 // Z = AShr Y, m
8313 // n, c and m are constants.
8314
8315 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8316 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8317 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8318 if (AddOperandCI) {
8319 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8320 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8321 // since we truncate to TruncTy, the AddConstant should be of the
8322 // same type, so create a new Constant with type same as TruncTy.
8323 // Also, the Add constant should be shifted right by AShr amount.
8324 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8325 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8326 // we model the expression as sext(add(trunc(A), c << n)), since the
8327 // sext(trunc) part is already handled below, we create a
8328 // AddExpr(TruncExp) which will be used later.
8329 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8330 }
8331 }
8332 } else if (L && L->getOpcode() == Instruction::Shl) {
8333 // X = Shl A, n
8334 // Y = AShr X, m
8335 // Both n and m are constant.
8336
8337 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8338 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8339 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8340 }
8341
8342 if (AddTruncateExpr && ShlAmtCI) {
8343 // We can merge the two given cases into a single SCEV statement,
8344 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8345 // a simpler case. The following code handles the two cases:
8346 //
8347 // 1) For a two-shift sext-inreg, i.e. n = m,
8348 // use sext(trunc(x)) as the SCEV expression.
8349 //
8350 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8351 // expression. We already checked that ShlAmt < BitWidth, so
8352 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8353 // ShlAmt - AShrAmt < Amt.
8354 const APInt &ShlAmt = ShlAmtCI->getValue();
8355 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8356 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8357 ShlAmtCI->getZExtValue() - AShrAmt);
8358 const SCEV *CompositeExpr =
8359 getMulExpr(AddTruncateExpr, getConstant(Mul));
8360 if (L->getOpcode() != Instruction::Shl)
8361 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8362
8363 return getSignExtendExpr(CompositeExpr, OuterTy);
8364 }
8365 }
8366 break;
8367 }
8368 }
8369
8370 switch (U->getOpcode()) {
8371 case Instruction::Trunc:
8372 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8373
8374 case Instruction::ZExt:
8375 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8376
8377 case Instruction::SExt:
8378 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8380 // The NSW flag of a subtract does not always survive the conversion to
8381 // A + (-1)*B. By pushing sign extension onto its operands we are much
8382 // more likely to preserve NSW and allow later AddRec optimisations.
8383 //
8384 // NOTE: This is effectively duplicating this logic from getSignExtend:
8385 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8386 // but by that point the NSW information has potentially been lost.
8387 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8388 Type *Ty = U->getType();
8389 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8390 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8391 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8392 }
8393 }
8394 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8395
8396 case Instruction::BitCast:
8397 // BitCasts are no-op casts so we just eliminate the cast.
8398 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8399 return getSCEV(U->getOperand(0));
8400 break;
8401
8402 case Instruction::PtrToAddr: {
8403 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8404 if (isa<SCEVCouldNotCompute>(IntOp))
8405 return getUnknown(V);
8406 return IntOp;
8407 }
8408
8409 case Instruction::PtrToInt: {
8410 // Pointer to integer cast is straight-forward, so do model it.
8411 const SCEV *Op = getSCEV(U->getOperand(0));
8412 Type *DstIntTy = U->getType();
8413 // But only if effective SCEV (integer) type is wide enough to represent
8414 // all possible pointer values.
8415 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
8416 if (isa<SCEVCouldNotCompute>(IntOp))
8417 return getUnknown(V);
8418 return IntOp;
8419 }
8420 case Instruction::IntToPtr:
8421 // Just don't deal with inttoptr casts.
8422 return getUnknown(V);
8423
8424 case Instruction::SDiv:
8425 // If both operands are non-negative, this is just an udiv.
8426 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8427 isKnownNonNegative(getSCEV(U->getOperand(1))))
8428 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8429 break;
8430
8431 case Instruction::SRem:
8432 // If both operands are non-negative, this is just an urem.
8433 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8434 isKnownNonNegative(getSCEV(U->getOperand(1))))
8435 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8436 break;
8437
8438 case Instruction::GetElementPtr:
8439 return createNodeForGEP(cast<GEPOperator>(U));
8440
8441 case Instruction::PHI:
8442 return createNodeForPHI(cast<PHINode>(U));
8443
8444 case Instruction::Select:
8445 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8446 U->getOperand(2));
8447
8448 case Instruction::Call:
8449 case Instruction::Invoke:
8450 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8451 return getSCEV(RV);
8452
8453 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8454 switch (II->getIntrinsicID()) {
8455 case Intrinsic::abs:
8456 return getAbsExpr(
8457 getSCEV(II->getArgOperand(0)),
8458 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8459 case Intrinsic::umax:
8460 LHS = getSCEV(II->getArgOperand(0));
8461 RHS = getSCEV(II->getArgOperand(1));
8462 return getUMaxExpr(LHS, RHS);
8463 case Intrinsic::umin:
8464 LHS = getSCEV(II->getArgOperand(0));
8465 RHS = getSCEV(II->getArgOperand(1));
8466 return getUMinExpr(LHS, RHS);
8467 case Intrinsic::smax:
8468 LHS = getSCEV(II->getArgOperand(0));
8469 RHS = getSCEV(II->getArgOperand(1));
8470 return getSMaxExpr(LHS, RHS);
8471 case Intrinsic::smin:
8472 LHS = getSCEV(II->getArgOperand(0));
8473 RHS = getSCEV(II->getArgOperand(1));
8474 return getSMinExpr(LHS, RHS);
8475 case Intrinsic::usub_sat: {
8476 const SCEV *X = getSCEV(II->getArgOperand(0));
8477 const SCEV *Y = getSCEV(II->getArgOperand(1));
8478 const SCEV *ClampedY = getUMinExpr(X, Y);
8479 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8480 }
8481 case Intrinsic::uadd_sat: {
8482 const SCEV *X = getSCEV(II->getArgOperand(0));
8483 const SCEV *Y = getSCEV(II->getArgOperand(1));
8484 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8485 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8486 }
8487 case Intrinsic::start_loop_iterations:
8488 case Intrinsic::annotation:
8489 case Intrinsic::ptr_annotation:
8490 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8491 // just eqivalent to the first operand for SCEV purposes.
8492 return getSCEV(II->getArgOperand(0));
8493 case Intrinsic::vscale:
8494 return getVScale(II->getType());
8495 default:
8496 break;
8497 }
8498 }
8499 break;
8500 }
8501
8502 return getUnknown(V);
8503}
8504
8505//===----------------------------------------------------------------------===//
8506// Iteration Count Computation Code
8507//
8508
8510 if (isa<SCEVCouldNotCompute>(ExitCount))
8511 return getCouldNotCompute();
8512
8513 auto *ExitCountType = ExitCount->getType();
8514 assert(ExitCountType->isIntegerTy());
8515 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8516 1 + ExitCountType->getScalarSizeInBits());
8517 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8518}
8519
8521 Type *EvalTy,
8522 const Loop *L) {
8523 if (isa<SCEVCouldNotCompute>(ExitCount))
8524 return getCouldNotCompute();
8525
8526 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8527 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8528
8529 auto CanAddOneWithoutOverflow = [&]() {
8530 ConstantRange ExitCountRange =
8531 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8532 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8533 return true;
8534
8535 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8536 getMinusOne(ExitCount->getType()));
8537 };
8538
8539 // If we need to zero extend the backedge count, check if we can add one to
8540 // it prior to zero extending without overflow. Provided this is safe, it
8541 // allows better simplification of the +1.
8542 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8543 return getZeroExtendExpr(
8544 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8545
8546 // Get the total trip count from the count by adding 1. This may wrap.
8547 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8548}
8549
8550static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8551 if (!ExitCount)
8552 return 0;
8553
8554 ConstantInt *ExitConst = ExitCount->getValue();
8555
8556 // Guard against huge trip counts.
8557 if (ExitConst->getValue().getActiveBits() > 32)
8558 return 0;
8559
8560 // In case of integer overflow, this returns 0, which is correct.
8561 return ((unsigned)ExitConst->getZExtValue()) + 1;
8562}
8563
8565 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8566 return getConstantTripCount(ExitCount);
8567}
8568
8569unsigned
8571 const BasicBlock *ExitingBlock) {
8572 assert(ExitingBlock && "Must pass a non-null exiting block!");
8573 assert(L->isLoopExiting(ExitingBlock) &&
8574 "Exiting block must actually branch out of the loop!");
8575 const SCEVConstant *ExitCount =
8576 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8577 return getConstantTripCount(ExitCount);
8578}
8579
8581 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8582
8583 const auto *MaxExitCount =
8584 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8586 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8587}
8588
8590 SmallVector<BasicBlock *, 8> ExitingBlocks;
8591 L->getExitingBlocks(ExitingBlocks);
8592
8593 std::optional<unsigned> Res;
8594 for (auto *ExitingBB : ExitingBlocks) {
8595 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
8596 if (!Res)
8597 Res = Multiple;
8598 Res = std::gcd(*Res, Multiple);
8599 }
8600 return Res.value_or(1);
8601}
8602
8604 const SCEV *ExitCount) {
8605 if (isa<SCEVCouldNotCompute>(ExitCount))
8606 return 1;
8607
8608 // Get the trip count
8609 const SCEV *TCExpr = getTripCountFromExitCount(applyLoopGuards(ExitCount, L));
8610
8611 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8612 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8613 // the greatest power of 2 divisor less than 2^32.
8614 return Multiple.getActiveBits() > 32
8615 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8616 : (unsigned)Multiple.getZExtValue();
8617}
8618
8619/// Returns the largest constant divisor of the trip count of this loop as a
8620/// normal unsigned value, if possible. This means that the actual trip count is
8621/// always a multiple of the returned value (don't forget the trip count could
8622/// very well be zero as well!).
8623///
8624/// Returns 1 if the trip count is unknown or not guaranteed to be the
8625/// multiple of a constant (which is also the case if the trip count is simply
8626/// constant, use getSmallConstantTripCount for that case), Will also return 1
8627/// if the trip count is very large (>= 2^32).
8628///
8629/// As explained in the comments for getSmallConstantTripCount, this assumes
8630/// that control exits the loop via ExitingBlock.
8631unsigned
8633 const BasicBlock *ExitingBlock) {
8634 assert(ExitingBlock && "Must pass a non-null exiting block!");
8635 assert(L->isLoopExiting(ExitingBlock) &&
8636 "Exiting block must actually branch out of the loop!");
8637 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8638 return getSmallConstantTripMultiple(L, ExitCount);
8639}
8640
8642 const BasicBlock *ExitingBlock,
8643 ExitCountKind Kind) {
8644 switch (Kind) {
8645 case Exact:
8646 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8647 case SymbolicMaximum:
8648 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8649 case ConstantMaximum:
8650 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8651 };
8652 llvm_unreachable("Invalid ExitCountKind!");
8653}
8654
8656 const Loop *L, const BasicBlock *ExitingBlock,
8658 switch (Kind) {
8659 case Exact:
8660 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8661 Predicates);
8662 case SymbolicMaximum:
8663 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8664 Predicates);
8665 case ConstantMaximum:
8666 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8667 Predicates);
8668 };
8669 llvm_unreachable("Invalid ExitCountKind!");
8670}
8671
8674 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8675}
8676
8678 ExitCountKind Kind) {
8679 switch (Kind) {
8680 case Exact:
8681 return getBackedgeTakenInfo(L).getExact(L, this);
8682 case ConstantMaximum:
8683 return getBackedgeTakenInfo(L).getConstantMax(this);
8684 case SymbolicMaximum:
8685 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8686 };
8687 llvm_unreachable("Invalid ExitCountKind!");
8688}
8689
8692 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8693}
8694
8697 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8698}
8699
8701 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8702}
8703
8704ScalarEvolution::BackedgeTakenInfo &
8705ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8706 auto &BTI = getBackedgeTakenInfo(L);
8707 if (BTI.hasFullInfo())
8708 return BTI;
8709
8710 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8711
8712 if (!Pair.second)
8713 return Pair.first->second;
8714
8715 BackedgeTakenInfo Result =
8716 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8717
8718 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8719}
8720
8721ScalarEvolution::BackedgeTakenInfo &
8722ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8723 // Initially insert an invalid entry for this loop. If the insertion
8724 // succeeds, proceed to actually compute a backedge-taken count and
8725 // update the value. The temporary CouldNotCompute value tells SCEV
8726 // code elsewhere that it shouldn't attempt to request a new
8727 // backedge-taken count, which could result in infinite recursion.
8728 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8729 BackedgeTakenCounts.try_emplace(L);
8730 if (!Pair.second)
8731 return Pair.first->second;
8732
8733 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8734 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8735 // must be cleared in this scope.
8736 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8737
8738 // Now that we know more about the trip count for this loop, forget any
8739 // existing SCEV values for PHI nodes in this loop since they are only
8740 // conservative estimates made without the benefit of trip count
8741 // information. This invalidation is not necessary for correctness, and is
8742 // only done to produce more precise results.
8743 if (Result.hasAnyInfo()) {
8744 // Invalidate any expression using an addrec in this loop.
8745 SmallVector<SCEVUse, 8> ToForget;
8746 auto LoopUsersIt = LoopUsers.find(L);
8747 if (LoopUsersIt != LoopUsers.end())
8748 append_range(ToForget, LoopUsersIt->second);
8749 forgetMemoizedResults(ToForget);
8750
8751 // Invalidate constant-evolved loop header phis.
8752 for (PHINode &PN : L->getHeader()->phis())
8753 ConstantEvolutionLoopExitValue.erase(&PN);
8754 }
8755
8756 // Re-lookup the insert position, since the call to
8757 // computeBackedgeTakenCount above could result in a
8758 // recusive call to getBackedgeTakenInfo (on a different
8759 // loop), which would invalidate the iterator computed
8760 // earlier.
8761 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8762}
8763
8765 // This method is intended to forget all info about loops. It should
8766 // invalidate caches as if the following happened:
8767 // - The trip counts of all loops have changed arbitrarily
8768 // - Every llvm::Value has been updated in place to produce a different
8769 // result.
8770 BackedgeTakenCounts.clear();
8771 PredicatedBackedgeTakenCounts.clear();
8772 BECountUsers.clear();
8773 LoopPropertiesCache.clear();
8774 ConstantEvolutionLoopExitValue.clear();
8775 ValueExprMap.clear();
8776 ValuesAtScopes.clear();
8777 ValuesAtScopesUsers.clear();
8778 LoopDispositions.clear();
8779 BlockDispositions.clear();
8780 UnsignedRanges.clear();
8781 SignedRanges.clear();
8782 ExprValueMap.clear();
8783 HasRecMap.clear();
8784 ConstantMultipleCache.clear();
8785 PredicatedSCEVRewrites.clear();
8786 FoldCache.clear();
8787 FoldCacheUser.clear();
8788}
8789void ScalarEvolution::visitAndClearUsers(
8792 SmallVectorImpl<SCEVUse> &ToForget) {
8793 while (!Worklist.empty()) {
8794 Instruction *I = Worklist.pop_back_val();
8795 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8796 continue;
8797
8799 ValueExprMap.find_as(static_cast<Value *>(I));
8800 if (It != ValueExprMap.end()) {
8801 ToForget.push_back(It->second);
8802 eraseValueFromMap(It->first);
8803 if (PHINode *PN = dyn_cast<PHINode>(I))
8804 ConstantEvolutionLoopExitValue.erase(PN);
8805 }
8806
8807 PushDefUseChildren(I, Worklist, Visited);
8808 }
8809}
8810
8812 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8813 SmallVector<SCEVUse, 16> ToForget;
8814
8815 // Iterate over all the loops and sub-loops to drop SCEV information.
8816 while (!LoopWorklist.empty()) {
8817 auto *CurrL = LoopWorklist.pop_back_val();
8818
8819 // Drop any stored trip count value.
8820 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8821 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8822
8823 // Drop information about predicated SCEV rewrites for this loop.
8824 PredicatedSCEVRewrites.remove_if(
8825 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8826
8827 auto LoopUsersItr = LoopUsers.find(CurrL);
8828 if (LoopUsersItr != LoopUsers.end())
8829 llvm::append_range(ToForget, LoopUsersItr->second);
8830
8831 // Drop information about expressions based on loop-header PHIs.
8832 for (PHINode &PN : CurrL->getHeader()->phis()) {
8833 ConstantEvolutionLoopExitValue.erase(&PN);
8834 auto VIt = ValueExprMap.find_as(static_cast<Value *>(&PN));
8835 if (VIt != ValueExprMap.end())
8836 ToForget.push_back(VIt->second);
8837 }
8838
8839 LoopPropertiesCache.erase(CurrL);
8840 // Forget all contained loops too, to avoid dangling entries in the
8841 // ValuesAtScopes map.
8842 LoopWorklist.append(CurrL->begin(), CurrL->end());
8843 }
8844 forgetMemoizedResults(ToForget);
8845}
8846
8848 forgetLoop(L->getOutermostLoop());
8849}
8850
8853 if (!I) return;
8854
8855 // Drop information about expressions based on loop-header PHIs.
8858 SmallVector<SCEVUse, 8> ToForget;
8859 Worklist.push_back(I);
8860 Visited.insert(I);
8861 visitAndClearUsers(Worklist, Visited, ToForget);
8862
8863 forgetMemoizedResults(ToForget);
8864}
8865
8867 if (!isSCEVable(V->getType()))
8868 return;
8869
8870 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8871 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8872 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8873 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8874 if (const SCEV *S = getExistingSCEV(V)) {
8875 struct InvalidationRootCollector {
8876 Loop *L;
8878
8879 InvalidationRootCollector(Loop *L) : L(L) {}
8880
8881 bool follow(const SCEV *S) {
8882 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8883 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8884 if (L->contains(I))
8885 Roots.push_back(S);
8886 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8887 if (L->contains(AddRec->getLoop()))
8888 Roots.push_back(S);
8889 }
8890 return true;
8891 }
8892 bool isDone() const { return false; }
8893 };
8894
8895 InvalidationRootCollector C(L);
8896 visitAll(S, C);
8897 forgetMemoizedResults(C.Roots);
8898 }
8899
8900 // Also perform the normal invalidation.
8901 forgetValue(V);
8902}
8903
8904void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8905
8907 // Unless a specific value is passed to invalidation, completely clear both
8908 // caches.
8909 if (!V) {
8910 BlockDispositions.clear();
8911 LoopDispositions.clear();
8912 return;
8913 }
8914
8915 if (!isSCEVable(V->getType()))
8916 return;
8917
8918 const SCEV *S = getExistingSCEV(V);
8919 if (!S)
8920 return;
8921
8922 // Invalidate the block and loop dispositions cached for S. Dispositions of
8923 // S's users may change if S's disposition changes (i.e. a user may change to
8924 // loop-invariant, if S changes to loop invariant), so also invalidate
8925 // dispositions of S's users recursively.
8926 SmallVector<SCEVUse, 8> Worklist = {S};
8928 while (!Worklist.empty()) {
8929 const SCEV *Curr = Worklist.pop_back_val();
8930 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8931 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8932 if (!LoopDispoRemoved && !BlockDispoRemoved)
8933 continue;
8934 auto Users = SCEVUsers.find(Curr);
8935 if (Users != SCEVUsers.end())
8936 for (const auto *User : Users->second)
8937 if (Seen.insert(User).second)
8938 Worklist.push_back(User);
8939 }
8940}
8941
8942/// Get the exact loop backedge taken count considering all loop exits. A
8943/// computable result can only be returned for loops with all exiting blocks
8944/// dominating the latch. howFarToZero assumes that the limit of each loop test
8945/// is never skipped. This is a valid assumption as long as the loop exits via
8946/// that test. For precise results, it is the caller's responsibility to specify
8947/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8948const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8949 const Loop *L, ScalarEvolution *SE,
8951 // If any exits were not computable, the loop is not computable.
8952 if (!isComplete() || ExitNotTaken.empty())
8953 return SE->getCouldNotCompute();
8954
8955 const BasicBlock *Latch = L->getLoopLatch();
8956 // All exiting blocks we have collected must dominate the only backedge.
8957 if (!Latch)
8958 return SE->getCouldNotCompute();
8959
8960 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8961 // count is simply a minimum out of all these calculated exit counts.
8963 for (const auto &ENT : ExitNotTaken) {
8964 const SCEV *BECount = ENT.ExactNotTaken;
8965 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8966 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8967 "We should only have known counts for exiting blocks that dominate "
8968 "latch!");
8969
8970 Ops.push_back(BECount);
8971
8972 if (Preds)
8973 append_range(*Preds, ENT.Predicates);
8974
8975 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8976 "Predicate should be always true!");
8977 }
8978
8979 // If an earlier exit exits on the first iteration (exit count zero), then
8980 // a later poison exit count should not propagate into the result. This are
8981 // exactly the semantics provided by umin_seq.
8982 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8983}
8984
8985const ScalarEvolution::ExitNotTakenInfo *
8986ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8987 const BasicBlock *ExitingBlock,
8988 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8989 for (const auto &ENT : ExitNotTaken)
8990 if (ENT.ExitingBlock == ExitingBlock) {
8991 if (ENT.hasAlwaysTruePredicate())
8992 return &ENT;
8993 else if (Predicates) {
8994 append_range(*Predicates, ENT.Predicates);
8995 return &ENT;
8996 }
8997 }
8998
8999 return nullptr;
9000}
9001
9002/// getConstantMax - Get the constant max backedge taken count for the loop.
9003const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
9004 ScalarEvolution *SE,
9005 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
9006 if (!getConstantMax())
9007 return SE->getCouldNotCompute();
9008
9009 for (const auto &ENT : ExitNotTaken)
9010 if (!ENT.hasAlwaysTruePredicate()) {
9011 if (!Predicates)
9012 return SE->getCouldNotCompute();
9013 append_range(*Predicates, ENT.Predicates);
9014 }
9015
9016 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
9017 isa<SCEVConstant>(getConstantMax())) &&
9018 "No point in having a non-constant max backedge taken count!");
9019 return getConstantMax();
9020}
9021
9022const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
9023 const Loop *L, ScalarEvolution *SE,
9024 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
9025 if (!SymbolicMax) {
9026 // Form an expression for the maximum exit count possible for this loop. We
9027 // merge the max and exact information to approximate a version of
9028 // getConstantMaxBackedgeTakenCount which isn't restricted to just
9029 // constants.
9030 SmallVector<SCEVUse, 4> ExitCounts;
9031
9032 for (const auto &ENT : ExitNotTaken) {
9033 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
9034 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
9035 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
9036 "We should only have known counts for exiting blocks that "
9037 "dominate latch!");
9038 ExitCounts.push_back(ExitCount);
9039 if (Predicates)
9040 append_range(*Predicates, ENT.Predicates);
9041
9042 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
9043 "Predicate should be always true!");
9044 }
9045 }
9046 if (ExitCounts.empty())
9047 SymbolicMax = SE->getCouldNotCompute();
9048 else
9049 SymbolicMax =
9050 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
9051 }
9052 return SymbolicMax;
9053}
9054
9055bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
9056 ScalarEvolution *SE) const {
9057 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
9058 return !ENT.hasAlwaysTruePredicate();
9059 };
9060 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
9061}
9062
9065
9067 const SCEV *E, const SCEV *ConstantMaxNotTaken,
9068 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
9072 // If we prove the max count is zero, so is the symbolic bound. This happens
9073 // in practice due to differences in a) how context sensitive we've chosen
9074 // to be and b) how we reason about bounds implied by UB.
9075 if (ConstantMaxNotTaken->isZero()) {
9076 this->ExactNotTaken = E = ConstantMaxNotTaken;
9077 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
9078 }
9079
9082 "Exact is not allowed to be less precise than Constant Max");
9085 "Exact is not allowed to be less precise than Symbolic Max");
9088 "Symbolic Max is not allowed to be less precise than Constant Max");
9091 "No point in having a non-constant max backedge taken count!");
9093 for (const auto PredList : PredLists)
9094 for (const auto *P : PredList) {
9095 if (SeenPreds.contains(P))
9096 continue;
9097 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
9098 SeenPreds.insert(P);
9099 Predicates.push_back(P);
9100 }
9101 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
9102 "Backedge count should be int");
9104 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
9105 "Max backedge count should be int");
9106}
9107
9115
9116/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
9117/// computable exit into a persistent ExitNotTakenInfo array.
9118ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
9120 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
9121 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
9122 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9123
9124 ExitNotTaken.reserve(ExitCounts.size());
9125 std::transform(ExitCounts.begin(), ExitCounts.end(),
9126 std::back_inserter(ExitNotTaken),
9127 [&](const EdgeExitInfo &EEI) {
9128 BasicBlock *ExitBB = EEI.first;
9129 const ExitLimit &EL = EEI.second;
9130 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
9131 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
9132 EL.Predicates);
9133 });
9134 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
9135 isa<SCEVConstant>(ConstantMax)) &&
9136 "No point in having a non-constant max backedge taken count!");
9137}
9138
9139/// Compute the number of times the backedge of the specified loop will execute.
9140ScalarEvolution::BackedgeTakenInfo
9141ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
9142 bool AllowPredicates) {
9143 SmallVector<BasicBlock *, 8> ExitingBlocks;
9144 L->getExitingBlocks(ExitingBlocks);
9145
9146 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9147
9149 bool CouldComputeBECount = true;
9150 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
9151 const SCEV *MustExitMaxBECount = nullptr;
9152 const SCEV *MayExitMaxBECount = nullptr;
9153 bool MustExitMaxOrZero = false;
9154 bool IsOnlyExit = ExitingBlocks.size() == 1;
9155
9156 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9157 // and compute maxBECount.
9158 // Do a union of all the predicates here.
9159 for (BasicBlock *ExitBB : ExitingBlocks) {
9160 // We canonicalize untaken exits to br (constant), ignore them so that
9161 // proving an exit untaken doesn't negatively impact our ability to reason
9162 // about the loop as whole.
9163 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9164 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9165 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9166 if (ExitIfTrue == CI->isZero())
9167 continue;
9168 }
9169
9170 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9171
9172 assert((AllowPredicates || EL.Predicates.empty()) &&
9173 "Predicated exit limit when predicates are not allowed!");
9174
9175 // 1. For each exit that can be computed, add an entry to ExitCounts.
9176 // CouldComputeBECount is true only if all exits can be computed.
9177 if (EL.ExactNotTaken != getCouldNotCompute())
9178 ++NumExitCountsComputed;
9179 else
9180 // We couldn't compute an exact value for this exit, so
9181 // we won't be able to compute an exact value for the loop.
9182 CouldComputeBECount = false;
9183 // Remember exit count if either exact or symbolic is known. Because
9184 // Exact always implies symbolic, only check symbolic.
9185 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9186 ExitCounts.emplace_back(ExitBB, EL);
9187 else {
9188 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9189 "Exact is known but symbolic isn't?");
9190 ++NumExitCountsNotComputed;
9191 }
9192
9193 // 2. Derive the loop's MaxBECount from each exit's max number of
9194 // non-exiting iterations. Partition the loop exits into two kinds:
9195 // LoopMustExits and LoopMayExits.
9196 //
9197 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9198 // is a LoopMayExit. If any computable LoopMustExit is found, then
9199 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9200 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9201 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9202 // any
9203 // computable EL.ConstantMaxNotTaken.
9204 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9205 DT.dominates(ExitBB, Latch)) {
9206 if (!MustExitMaxBECount) {
9207 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9208 MustExitMaxOrZero = EL.MaxOrZero;
9209 } else {
9210 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9211 EL.ConstantMaxNotTaken);
9212 }
9213 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9214 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9215 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9216 else {
9217 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9218 EL.ConstantMaxNotTaken);
9219 }
9220 }
9221 }
9222 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9223 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9224 // The loop backedge will be taken the maximum or zero times if there's
9225 // a single exit that must be taken the maximum or zero times.
9226 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9227
9228 // Remember which SCEVs are used in exit limits for invalidation purposes.
9229 // We only care about non-constant SCEVs here, so we can ignore
9230 // EL.ConstantMaxNotTaken
9231 // and MaxBECount, which must be SCEVConstant.
9232 for (const auto &Pair : ExitCounts) {
9233 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9234 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9235 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9236 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9237 {L, AllowPredicates});
9238 }
9239 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9240 MaxBECount, MaxOrZero);
9241}
9242
9243ScalarEvolution::ExitLimit
9244ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9245 bool IsOnlyExit, bool AllowPredicates) {
9246 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9247 // If our exiting block does not dominate the latch, then its connection with
9248 // loop's exit limit may be far from trivial.
9249 const BasicBlock *Latch = L->getLoopLatch();
9250 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9251 return getCouldNotCompute();
9252
9253 Instruction *Term = ExitingBlock->getTerminator();
9254 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9255 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9256 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9257 "It should have one successor in loop and one exit block!");
9258 // Proceed to the next level to examine the exit condition expression.
9259 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9260 /*ControlsOnlyExit=*/IsOnlyExit,
9261 AllowPredicates);
9262 }
9263
9264 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9265 // For switch, make sure that there is a single exit from the loop.
9266 BasicBlock *Exit = nullptr;
9267 for (auto *SBB : successors(ExitingBlock))
9268 if (!L->contains(SBB)) {
9269 if (Exit) // Multiple exit successors.
9270 return getCouldNotCompute();
9271 Exit = SBB;
9272 }
9273 assert(Exit && "Exiting block must have at least one exit");
9274 return computeExitLimitFromSingleExitSwitch(
9275 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9276 }
9277
9278 return getCouldNotCompute();
9279}
9280
9282 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9283 bool AllowPredicates) {
9284 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9285 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9286 ControlsOnlyExit, AllowPredicates);
9287}
9288
9289std::optional<ScalarEvolution::ExitLimit>
9290ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9291 bool ExitIfTrue, bool ControlsOnlyExit,
9292 bool AllowPredicates) {
9293 (void)this->L;
9294 (void)this->ExitIfTrue;
9295 (void)this->AllowPredicates;
9296
9297 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9298 this->AllowPredicates == AllowPredicates &&
9299 "Variance in assumed invariant key components!");
9300 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9301 if (Itr == TripCountMap.end())
9302 return std::nullopt;
9303 return Itr->second;
9304}
9305
9306void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9307 bool ExitIfTrue,
9308 bool ControlsOnlyExit,
9309 bool AllowPredicates,
9310 const ExitLimit &EL) {
9311 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9312 this->AllowPredicates == AllowPredicates &&
9313 "Variance in assumed invariant key components!");
9314
9315 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9316 assert(InsertResult.second && "Expected successful insertion!");
9317 (void)InsertResult;
9318 (void)ExitIfTrue;
9319}
9320
9321ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9322 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9323 bool ControlsOnlyExit, bool AllowPredicates) {
9324
9325 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9326 AllowPredicates))
9327 return *MaybeEL;
9328
9329 ExitLimit EL = computeExitLimitFromCondImpl(
9330 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9331 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9332 return EL;
9333}
9334
9335ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9336 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9337 bool ControlsOnlyExit, bool AllowPredicates) {
9338 // Handle BinOp conditions (And, Or).
9339 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9340 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9341 return *LimitFromBinOp;
9342
9343 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9344 // Proceed to the next level to examine the icmp.
9345 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9346 ExitLimit EL =
9347 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9348 if (EL.hasFullInfo() || !AllowPredicates)
9349 return EL;
9350
9351 // Try again, but use SCEV predicates this time.
9352 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9353 ControlsOnlyExit,
9354 /*AllowPredicates=*/true);
9355 }
9356
9357 // Check for a constant condition. These are normally stripped out by
9358 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9359 // preserve the CFG and is temporarily leaving constant conditions
9360 // in place.
9361 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9362 if (ExitIfTrue == !CI->getZExtValue())
9363 // The backedge is always taken.
9364 return getCouldNotCompute();
9365 // The backedge is never taken.
9366 return getZero(CI->getType());
9367 }
9368
9369 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9370 // with a constant step, we can form an equivalent icmp predicate and figure
9371 // out how many iterations will be taken before we exit.
9372 const WithOverflowInst *WO;
9373 const APInt *C;
9374 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9375 match(WO->getRHS(), m_APInt(C))) {
9376 ConstantRange NWR =
9378 WO->getNoWrapKind());
9379 CmpInst::Predicate Pred;
9380 APInt NewRHSC, Offset;
9381 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9382 if (!ExitIfTrue)
9383 Pred = ICmpInst::getInversePredicate(Pred);
9384 auto *LHS = getSCEV(WO->getLHS());
9385 if (Offset != 0)
9387 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9388 ControlsOnlyExit, AllowPredicates);
9389 if (EL.hasAnyInfo())
9390 return EL;
9391 }
9392
9393 // If it's not an integer or pointer comparison then compute it the hard way.
9394 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9395}
9396
9397std::optional<ScalarEvolution::ExitLimit>
9398ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9399 const Loop *L,
9400 Value *ExitCond,
9401 bool ExitIfTrue,
9402 bool AllowPredicates) {
9403 // Check if the controlling expression for this loop is an And or Or.
9404 Value *Op0, *Op1;
9405 bool IsAnd;
9406 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9407 IsAnd = true;
9408 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9409 IsAnd = false;
9410 else
9411 return std::nullopt;
9412
9413 // A sub-condition of a non-trivial binop never solely controls the exit,
9414 // whether we exit always depends on both conditions.
9415 ExitLimit EL0 = computeExitLimitFromCondCached(
9416 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9417 ExitLimit EL1 = computeExitLimitFromCondCached(
9418 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9419
9420 // EitherMayExit is true in these two cases:
9421 // br (and Op0 Op1), loop, exit
9422 // br (or Op0 Op1), exit, loop
9423 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9424
9425 const SCEV *BECount = getCouldNotCompute();
9426 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9427 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9428 if (EitherMayExit) {
9429 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9430 // Both conditions must be same for the loop to continue executing.
9431 // Choose the less conservative count.
9432 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9433 EL1.ExactNotTaken != getCouldNotCompute()) {
9434 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9435 UseSequentialUMin);
9436 }
9437 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9438 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9439 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9440 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9441 else
9442 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9443 EL1.ConstantMaxNotTaken);
9444 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9445 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9446 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9447 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9448 else
9449 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9450 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9451 } else {
9452 // Both conditions must be same at the same time for the loop to exit.
9453 // For now, be conservative.
9454 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9455 BECount = EL0.ExactNotTaken;
9456 }
9457
9458 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9459 // to be more aggressive when computing BECount than when computing
9460 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9461 // and
9462 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9463 // EL1.ConstantMaxNotTaken to not.
9464 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9465 !isa<SCEVCouldNotCompute>(BECount))
9466 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9467 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9468 SymbolicMaxBECount =
9469 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9470 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9471 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9472}
9473
9474ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9475 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9476 bool AllowPredicates) {
9477 // If the condition was exit on true, convert the condition to exit on false
9478 CmpPredicate Pred;
9479 if (!ExitIfTrue)
9480 Pred = ExitCond->getCmpPredicate();
9481 else
9482 Pred = ExitCond->getInverseCmpPredicate();
9483 const ICmpInst::Predicate OriginalPred = Pred;
9484
9485 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9486 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9487
9488 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9489 AllowPredicates);
9490 if (EL.hasAnyInfo())
9491 return EL;
9492
9493 auto *ExhaustiveCount =
9494 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9495
9496 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9497 return ExhaustiveCount;
9498
9499 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9500 ExitCond->getOperand(1), L, OriginalPred);
9501}
9502ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9503 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9504 bool ControlsOnlyExit, bool AllowPredicates) {
9505
9506 // Try to evaluate any dependencies out of the loop.
9507 LHS = getSCEVAtScope(LHS, L);
9508 RHS = getSCEVAtScope(RHS, L);
9509
9510 // At this point, we would like to compute how many iterations of the
9511 // loop the predicate will return true for these inputs.
9512 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9513 // If there is a loop-invariant, force it into the RHS.
9514 std::swap(LHS, RHS);
9516 }
9517
9518 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9520 // Simplify the operands before analyzing them.
9521 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9522
9523 // If we have a comparison of a chrec against a constant, try to use value
9524 // ranges to answer this query.
9525 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9526 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9527 if (AddRec->getLoop() == L) {
9528 // Form the constant range.
9529 ConstantRange CompRange =
9530 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9531
9532 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9533 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9534 }
9535
9536 // If this loop must exit based on this condition (or execute undefined
9537 // behaviour), see if we can improve wrap flags. This is essentially
9538 // a must execute style proof.
9539 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9540 // If we can prove the test sequence produced must repeat the same values
9541 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9542 // because if it did, we'd have an infinite (undefined) loop.
9543 // TODO: We can peel off any functions which are invertible *in L*. Loop
9544 // invariant terms are effectively constants for our purposes here.
9545 SCEVUse InnerLHS = LHS;
9546 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9547 InnerLHS = ZExt->getOperand();
9548 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9549 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9550 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9551 /*OrNegative=*/true)) {
9552 auto Flags = AR->getNoWrapFlags();
9553 Flags = setFlags(Flags, SCEV::FlagNW);
9554 SmallVector<SCEVUse> Operands{AR->operands()};
9555 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9556 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9557 }
9558
9559 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9560 // From no-self-wrap, this follows trivially from the fact that every
9561 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9562 // last value before (un)signed wrap. Since we know that last value
9563 // didn't exit, nor will any smaller one.
9564 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9565 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9566 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9567 AR && AR->getLoop() == L && AR->isAffine() &&
9568 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9569 isKnownPositive(AR->getStepRecurrence(*this))) {
9570 auto Flags = AR->getNoWrapFlags();
9571 Flags = setFlags(Flags, WrapType);
9572 SmallVector<SCEVUse> Operands{AR->operands()};
9573 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9574 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9575 }
9576 }
9577 }
9578
9579 switch (Pred) {
9580 case ICmpInst::ICMP_NE: { // while (X != Y)
9581 // Convert to: while (X-Y != 0)
9582 if (LHS->getType()->isPointerTy()) {
9585 return LHS;
9586 }
9587 if (RHS->getType()->isPointerTy()) {
9590 return RHS;
9591 }
9592 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9593 AllowPredicates);
9594 if (EL.hasAnyInfo())
9595 return EL;
9596 break;
9597 }
9598 case ICmpInst::ICMP_EQ: { // while (X == Y)
9599 // Convert to: while (X-Y == 0)
9600 if (LHS->getType()->isPointerTy()) {
9603 return LHS;
9604 }
9605 if (RHS->getType()->isPointerTy()) {
9608 return RHS;
9609 }
9610 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9611 if (EL.hasAnyInfo()) return EL;
9612 break;
9613 }
9614 case ICmpInst::ICMP_SLE:
9615 case ICmpInst::ICMP_ULE:
9616 // Since the loop is finite, an invariant RHS cannot include the boundary
9617 // value, otherwise it would loop forever.
9618 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9619 !isLoopInvariant(RHS, L)) {
9620 // Otherwise, perform the addition in a wider type, to avoid overflow.
9621 // If the LHS is an addrec with the appropriate nowrap flag, the
9622 // extension will be sunk into it and the exit count can be analyzed.
9623 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9624 if (!OldType)
9625 break;
9626 // Prefer doubling the bitwidth over adding a single bit to make it more
9627 // likely that we use a legal type.
9628 auto *NewType =
9629 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9630 if (ICmpInst::isSigned(Pred)) {
9631 LHS = getSignExtendExpr(LHS, NewType);
9632 RHS = getSignExtendExpr(RHS, NewType);
9633 } else {
9634 LHS = getZeroExtendExpr(LHS, NewType);
9635 RHS = getZeroExtendExpr(RHS, NewType);
9636 }
9637 }
9639 [[fallthrough]];
9640 case ICmpInst::ICMP_SLT:
9641 case ICmpInst::ICMP_ULT: { // while (X < Y)
9642 bool IsSigned = ICmpInst::isSigned(Pred);
9643 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9644 AllowPredicates);
9645 if (EL.hasAnyInfo())
9646 return EL;
9647 break;
9648 }
9649 case ICmpInst::ICMP_SGE:
9650 case ICmpInst::ICMP_UGE:
9651 // Since the loop is finite, an invariant RHS cannot include the boundary
9652 // value, otherwise it would loop forever.
9653 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9654 !isLoopInvariant(RHS, L))
9655 break;
9657 [[fallthrough]];
9658 case ICmpInst::ICMP_SGT:
9659 case ICmpInst::ICMP_UGT: { // while (X > Y)
9660 bool IsSigned = ICmpInst::isSigned(Pred);
9661 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9662 AllowPredicates);
9663 if (EL.hasAnyInfo())
9664 return EL;
9665 break;
9666 }
9667 default:
9668 break;
9669 }
9670
9671 return getCouldNotCompute();
9672}
9673
9674ScalarEvolution::ExitLimit
9675ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9676 SwitchInst *Switch,
9677 BasicBlock *ExitingBlock,
9678 bool ControlsOnlyExit) {
9679 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9680
9681 // Give up if the exit is the default dest of a switch.
9682 if (Switch->getDefaultDest() == ExitingBlock)
9683 return getCouldNotCompute();
9684
9685 assert(L->contains(Switch->getDefaultDest()) &&
9686 "Default case must not exit the loop!");
9687 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9688 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9689
9690 // while (X != Y) --> while (X-Y != 0)
9691 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9692 if (EL.hasAnyInfo())
9693 return EL;
9694
9695 return getCouldNotCompute();
9696}
9697
9698static ConstantInt *
9700 ScalarEvolution &SE) {
9701 const SCEV *InVal = SE.getConstant(C);
9702 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9704 "Evaluation of SCEV at constant didn't fold correctly?");
9705 return cast<SCEVConstant>(Val)->getValue();
9706}
9707
9708ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9709 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9710 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9711 if (!RHS)
9712 return getCouldNotCompute();
9713
9714 const BasicBlock *Latch = L->getLoopLatch();
9715 if (!Latch)
9716 return getCouldNotCompute();
9717
9718 const BasicBlock *Predecessor = L->getLoopPredecessor();
9719 if (!Predecessor)
9720 return getCouldNotCompute();
9721
9722 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9723 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9724 // OutShiftAmt.
9725 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9726 Instruction::BinaryOps &OutOpCode,
9727 unsigned &OutShiftAmt) {
9728 using namespace PatternMatch;
9729
9730 ConstantInt *ShiftAmt;
9731 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9732 OutOpCode = Instruction::LShr;
9733 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9734 OutOpCode = Instruction::AShr;
9735 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9736 OutOpCode = Instruction::Shl;
9737 else
9738 return false;
9739
9740 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9741 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9742 return false;
9743 OutShiftAmt = Amt;
9744 return true;
9745 };
9746
9747 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9748 //
9749 // loop:
9750 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9751 // %iv.shifted = lshr i32 %iv, <positive constant>
9752 //
9753 // Return true on a successful match. Return the corresponding PHI node (%iv
9754 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9755 // shift amount in ShiftAmtOut.
9756 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9757 Instruction::BinaryOps &OpCodeOut,
9758 unsigned &ShiftAmtOut) {
9759 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9760
9761 {
9763 Value *V;
9764 unsigned Amt;
9765
9766 // If we encounter a shift instruction, "peel off" the shift operation,
9767 // and remember that we did so. Later when we inspect %iv's backedge
9768 // value, we will make sure that the backedge value uses the same
9769 // operation.
9770 //
9771 // Note: the peeled shift operation does not have to be the same
9772 // instruction as the one feeding into the PHI's backedge value. We only
9773 // really care about it being the same *kind* of shift instruction --
9774 // that's all that is required for our later inferences to hold.
9775 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9776 PostShiftOpCode = OpC;
9777 LHS = V;
9778 }
9779 }
9780
9781 PNOut = dyn_cast<PHINode>(LHS);
9782 if (!PNOut || PNOut->getParent() != L->getHeader())
9783 return false;
9784
9785 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9786 Value *OpLHS;
9787
9788 return
9789 // The backedge value for the PHI node must be a shift by a positive
9790 // amount
9791 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9792
9793 // of the PHI node itself
9794 OpLHS == PNOut &&
9795
9796 // and the kind of shift should be match the kind of shift we peeled
9797 // off, if any.
9798 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9799 };
9800
9801 PHINode *PN;
9803 unsigned ShiftAmt;
9804 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9805 return getCouldNotCompute();
9806
9807 const DataLayout &DL = getDataLayout();
9808
9809 // The key rationale for this optimization is that for some kinds of shift
9810 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9811 // within a finite number of iterations. If the condition guarding the
9812 // backedge (in the sense that the backedge is taken if the condition is true)
9813 // is false for the value the shift recurrence stabilizes to, then we know
9814 // that the backedge is taken only a finite number of times.
9815
9816 ConstantInt *StableValue = nullptr;
9817 switch (OpCode) {
9818 default:
9819 llvm_unreachable("Impossible case!");
9820
9821 case Instruction::AShr: {
9822 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9823 // bitwidth(K) iterations.
9824 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9825 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9826 Predecessor->getTerminator(), &DT);
9827 auto *Ty = cast<IntegerType>(RHS->getType());
9828 if (Known.isNonNegative())
9829 StableValue = ConstantInt::get(Ty, 0);
9830 else if (Known.isNegative())
9831 StableValue = ConstantInt::get(Ty, -1, true);
9832 else
9833 return getCouldNotCompute();
9834
9835 break;
9836 }
9837 case Instruction::LShr:
9838 case Instruction::Shl:
9839 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9840 // stabilize to 0 in at most bitwidth(K) iterations.
9841 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9842 break;
9843 }
9844
9845 auto *Result =
9846 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9847 assert(Result->getType()->isIntegerTy(1) &&
9848 "Otherwise cannot be an operand to a branch instruction");
9849
9850 if (Result->isNullValue()) {
9851 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9852 unsigned MaxBTC = BitWidth;
9853
9854 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9855 // compute a tighter max backedge-taken count from the range of the start
9856 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9857 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9858 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9859 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9860 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9861 const SCEV *StartSCEV = getSCEV(StartValue);
9862 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9863 if (MaxStart.isStrictlyPositive()) {
9864 unsigned ActiveBits = MaxStart.getActiveBits();
9865 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9866 MaxBTC = std::min(MaxBTC, RangeBTC);
9867 }
9868 }
9869
9870 const SCEV *UpperBound =
9872 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9873 }
9874
9875 return getCouldNotCompute();
9876}
9877
9878/// Return true if we can constant fold an instruction of the specified type,
9879/// assuming that all operands were constants.
9880static bool CanConstantFold(const Instruction *I) {
9884 return true;
9885
9886 if (const CallInst *CI = dyn_cast<CallInst>(I))
9887 if (const Function *F = CI->getCalledFunction())
9888 return canConstantFoldCallTo(CI, F);
9889 return false;
9890}
9891
9892/// Determine whether this instruction can constant evolve within this loop
9893/// assuming its operands can all constant evolve.
9894static bool canConstantEvolve(Instruction *I, const Loop *L) {
9895 // An instruction outside of the loop can't be derived from a loop PHI.
9896 if (!L->contains(I)) return false;
9897
9898 if (isa<PHINode>(I)) {
9899 // We don't currently keep track of the control flow needed to evaluate
9900 // PHIs, so we cannot handle PHIs inside of loops.
9901 return L->getHeader() == I->getParent();
9902 }
9903
9904 // If we won't be able to constant fold this expression even if the operands
9905 // are constants, bail early.
9906 return CanConstantFold(I);
9907}
9908
9909/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9910/// recursing through each instruction operand until reaching a loop header phi.
9911static PHINode *
9914 unsigned Depth) {
9916 return nullptr;
9917
9918 // Otherwise, we can evaluate this instruction if all of its operands are
9919 // constant or derived from a PHI node themselves.
9920 PHINode *PHI = nullptr;
9921 for (Value *Op : UseInst->operands()) {
9922 if (isa<Constant>(Op)) continue;
9923
9925 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
9926
9927 PHINode *P = dyn_cast<PHINode>(OpInst);
9928 if (!P)
9929 // If this operand is already visited, reuse the prior result.
9930 // We may have P != PHI if this is the deepest point at which the
9931 // inconsistent paths meet.
9932 P = PHIMap.lookup(OpInst);
9933 if (!P) {
9934 // Recurse and memoize the results, whether a phi is found or not.
9935 // This recursive call invalidates pointers into PHIMap.
9936 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
9937 PHIMap[OpInst] = P;
9938 }
9939 if (!P)
9940 return nullptr; // Not evolving from PHI
9941 if (PHI && PHI != P)
9942 return nullptr; // Evolving from multiple different PHIs.
9943 PHI = P;
9944 }
9945 // This is a expression evolving from a constant PHI!
9946 return PHI;
9947}
9948
9949/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9950/// in the loop that V is derived from. We allow arbitrary operations along the
9951/// way, but the operands of an operation must either be constants or a value
9952/// derived from a constant PHI. If this expression does not fit with these
9953/// constraints, return null.
9956 if (!I || !canConstantEvolve(I, L)) return nullptr;
9957
9958 if (PHINode *PN = dyn_cast<PHINode>(I))
9959 return PN;
9960
9961 // Record non-constant instructions contained by the loop.
9963 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9964}
9965
9966/// EvaluateExpression - Given an expression that passes the
9967/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9968/// in the loop has the value PHIVal. If we can't fold this expression for some
9969/// reason, return null.
9972 const DataLayout &DL,
9973 const TargetLibraryInfo *TLI) {
9974 // Convenient constant check, but redundant for recursive calls.
9975 if (Constant *C = dyn_cast<Constant>(V)) return C;
9977 if (!I) return nullptr;
9978
9979 if (Constant *C = Vals.lookup(I)) return C;
9980
9981 // An instruction inside the loop depends on a value outside the loop that we
9982 // weren't given a mapping for, or a value such as a call inside the loop.
9983 if (!canConstantEvolve(I, L)) return nullptr;
9984
9985 // An unmapped PHI can be due to a branch or another loop inside this loop,
9986 // or due to this not being the initial iteration through a loop where we
9987 // couldn't compute the evolution of this particular PHI last time.
9988 if (isa<PHINode>(I)) return nullptr;
9989
9990 std::vector<Constant*> Operands(I->getNumOperands());
9991
9992 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9993 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9994 if (!Operand) {
9995 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9996 if (!Operands[i]) return nullptr;
9997 continue;
9998 }
9999 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
10000 Vals[Operand] = C;
10001 if (!C) return nullptr;
10002 Operands[i] = C;
10003 }
10004
10005 return ConstantFoldInstOperands(I, Operands, DL, TLI,
10006 /*AllowNonDeterministic=*/false);
10007}
10008
10009
10010// If every incoming value to PN except the one for BB is a specific Constant,
10011// return that, else return nullptr.
10013 Constant *IncomingVal = nullptr;
10014
10015 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10016 if (PN->getIncomingBlock(i) == BB)
10017 continue;
10018
10019 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
10020 if (!CurrentVal)
10021 return nullptr;
10022
10023 if (IncomingVal != CurrentVal) {
10024 if (IncomingVal)
10025 return nullptr;
10026 IncomingVal = CurrentVal;
10027 }
10028 }
10029
10030 return IncomingVal;
10031}
10032
10033/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
10034/// in the header of its containing loop, we know the loop executes a
10035/// constant number of times, and the PHI node is just a recurrence
10036/// involving constants, fold it.
10037Constant *
10038ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
10039 const APInt &BEs,
10040 const Loop *L) {
10041 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
10042 if (!Inserted)
10043 return I->second;
10044
10046 return nullptr; // Not going to evaluate it.
10047
10048 Constant *&RetVal = I->second;
10049
10050 DenseMap<Instruction *, Constant *> CurrentIterVals;
10051 BasicBlock *Header = L->getHeader();
10052 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
10053
10054 BasicBlock *Latch = L->getLoopLatch();
10055 if (!Latch)
10056 return nullptr;
10057
10058 for (PHINode &PHI : Header->phis()) {
10059 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10060 CurrentIterVals[&PHI] = StartCST;
10061 }
10062 if (!CurrentIterVals.count(PN))
10063 return RetVal = nullptr;
10064
10065 Value *BEValue = PN->getIncomingValueForBlock(Latch);
10066
10067 // Execute the loop symbolically to determine the exit value.
10068 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
10069 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
10070
10071 unsigned NumIterations = BEs.getZExtValue(); // must be in range
10072 unsigned IterationNum = 0;
10073 const DataLayout &DL = getDataLayout();
10074 for (; ; ++IterationNum) {
10075 if (IterationNum == NumIterations)
10076 return RetVal = CurrentIterVals[PN]; // Got exit value!
10077
10078 // Compute the value of the PHIs for the next iteration.
10079 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
10080 DenseMap<Instruction *, Constant *> NextIterVals;
10081 Constant *NextPHI =
10082 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10083 if (!NextPHI)
10084 return nullptr; // Couldn't evaluate!
10085 NextIterVals[PN] = NextPHI;
10086
10087 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
10088
10089 // Also evaluate the other PHI nodes. However, we don't get to stop if we
10090 // cease to be able to evaluate one of them or if they stop evolving,
10091 // because that doesn't necessarily prevent us from computing PN.
10093 for (const auto &I : CurrentIterVals) {
10094 PHINode *PHI = dyn_cast<PHINode>(I.first);
10095 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
10096 PHIsToCompute.emplace_back(PHI, I.second);
10097 }
10098 // We use two distinct loops because EvaluateExpression may invalidate any
10099 // iterators into CurrentIterVals.
10100 for (const auto &I : PHIsToCompute) {
10101 PHINode *PHI = I.first;
10102 Constant *&NextPHI = NextIterVals[PHI];
10103 if (!NextPHI) { // Not already computed.
10104 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10105 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10106 }
10107 if (NextPHI != I.second)
10108 StoppedEvolving = false;
10109 }
10110
10111 // If all entries in CurrentIterVals == NextIterVals then we can stop
10112 // iterating, the loop can't continue to change.
10113 if (StoppedEvolving)
10114 return RetVal = CurrentIterVals[PN];
10115
10116 CurrentIterVals.swap(NextIterVals);
10117 }
10118}
10119
10120const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
10121 Value *Cond,
10122 bool ExitWhen) {
10123 PHINode *PN = getConstantEvolvingPHI(Cond, L);
10124 if (!PN) return getCouldNotCompute();
10125
10126 // If the loop is canonicalized, the PHI will have exactly two entries.
10127 // That's the only form we support here.
10128 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
10129
10130 DenseMap<Instruction *, Constant *> CurrentIterVals;
10131 BasicBlock *Header = L->getHeader();
10132 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
10133
10134 BasicBlock *Latch = L->getLoopLatch();
10135 assert(Latch && "Should follow from NumIncomingValues == 2!");
10136
10137 for (PHINode &PHI : Header->phis()) {
10138 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10139 CurrentIterVals[&PHI] = StartCST;
10140 }
10141 if (!CurrentIterVals.count(PN))
10142 return getCouldNotCompute();
10143
10144 // Okay, we find a PHI node that defines the trip count of this loop. Execute
10145 // the loop symbolically to determine when the condition gets a value of
10146 // "ExitWhen".
10147 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
10148 const DataLayout &DL = getDataLayout();
10149 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
10150 auto *CondVal = dyn_cast_or_null<ConstantInt>(
10151 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
10152
10153 // Couldn't symbolically evaluate.
10154 if (!CondVal) return getCouldNotCompute();
10155
10156 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10157 ++NumBruteForceTripCountsComputed;
10158 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10159 }
10160
10161 // Update all the PHI nodes for the next iteration.
10162 DenseMap<Instruction *, Constant *> NextIterVals;
10163
10164 // Create a list of which PHIs we need to compute. We want to do this before
10165 // calling EvaluateExpression on them because that may invalidate iterators
10166 // into CurrentIterVals.
10167 SmallVector<PHINode *, 8> PHIsToCompute;
10168 for (const auto &I : CurrentIterVals) {
10169 PHINode *PHI = dyn_cast<PHINode>(I.first);
10170 if (!PHI || PHI->getParent() != Header) continue;
10171 PHIsToCompute.push_back(PHI);
10172 }
10173 for (PHINode *PHI : PHIsToCompute) {
10174 Constant *&NextPHI = NextIterVals[PHI];
10175 if (NextPHI) continue; // Already computed!
10176
10177 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10178 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10179 }
10180 CurrentIterVals.swap(NextIterVals);
10181 }
10182
10183 // Too many iterations were needed to evaluate.
10184 return getCouldNotCompute();
10185}
10186
10187const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
10189 ValuesAtScopes[V];
10190 // Check to see if we've folded this expression at this loop before.
10191 for (auto &LS : Values)
10192 if (LS.first == L)
10193 return LS.second ? LS.second : V;
10194
10195 Values.emplace_back(L, nullptr);
10196
10197 // Otherwise compute it.
10198 const SCEV *C = computeSCEVAtScope(V, L);
10199 for (auto &LS : reverse(ValuesAtScopes[V]))
10200 if (LS.first == L) {
10201 LS.second = C;
10202 if (!isa<SCEVConstant>(C))
10203 ValuesAtScopesUsers[C].push_back({L, V});
10204 break;
10205 }
10206 return C;
10207}
10208
10209/// This builds up a Constant using the ConstantExpr interface. That way, we
10210/// will return Constants for objects which aren't represented by a
10211/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10212/// Returns NULL if the SCEV isn't representable as a Constant.
10214 switch (V->getSCEVType()) {
10215 case scCouldNotCompute:
10216 case scAddRecExpr:
10217 case scVScale:
10218 return nullptr;
10219 case scConstant:
10220 return cast<SCEVConstant>(V)->getValue();
10221 case scUnknown:
10223 case scPtrToAddr: {
10225 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10226 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10227
10228 return nullptr;
10229 }
10230 case scPtrToInt: {
10232 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10233 return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
10234
10235 return nullptr;
10236 }
10237 case scTruncate: {
10239 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10240 return ConstantExpr::getTrunc(CastOp, ST->getType());
10241 return nullptr;
10242 }
10243 case scAddExpr: {
10244 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10245 Constant *C = nullptr;
10246 for (const SCEV *Op : SA->operands()) {
10248 if (!OpC)
10249 return nullptr;
10250 if (!C) {
10251 C = OpC;
10252 continue;
10253 }
10254 assert(!C->getType()->isPointerTy() &&
10255 "Can only have one pointer, and it must be last");
10256 if (OpC->getType()->isPointerTy()) {
10257 // The offsets have been converted to bytes. We can add bytes using
10258 // an i8 GEP.
10259 C = ConstantExpr::getPtrAdd(OpC, C);
10260 } else {
10261 C = ConstantExpr::getAdd(C, OpC);
10262 }
10263 }
10264 return C;
10265 }
10266 case scMulExpr:
10267 case scSignExtend:
10268 case scZeroExtend:
10269 case scUDivExpr:
10270 case scSMaxExpr:
10271 case scUMaxExpr:
10272 case scSMinExpr:
10273 case scUMinExpr:
10275 return nullptr;
10276 }
10277 llvm_unreachable("Unknown SCEV kind!");
10278}
10279
10280const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10281 SmallVectorImpl<SCEVUse> &NewOps) {
10282 switch (S->getSCEVType()) {
10283 case scTruncate:
10284 case scZeroExtend:
10285 case scSignExtend:
10286 case scPtrToAddr:
10287 case scPtrToInt:
10288 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10289 case scAddRecExpr: {
10290 auto *AddRec = cast<SCEVAddRecExpr>(S);
10291 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10292 }
10293 case scAddExpr:
10294 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10295 case scMulExpr:
10296 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10297 case scUDivExpr:
10298 return getUDivExpr(NewOps[0], NewOps[1]);
10299 case scUMaxExpr:
10300 case scSMaxExpr:
10301 case scUMinExpr:
10302 case scSMinExpr:
10303 return getMinMaxExpr(S->getSCEVType(), NewOps);
10305 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10306 case scConstant:
10307 case scVScale:
10308 case scUnknown:
10309 return S;
10310 case scCouldNotCompute:
10311 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10312 }
10313 llvm_unreachable("Unknown SCEV kind!");
10314}
10315
10316const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10317 switch (V->getSCEVType()) {
10318 case scConstant:
10319 case scVScale:
10320 return V;
10321 case scAddRecExpr: {
10322 // If this is a loop recurrence for a loop that does not contain L, then we
10323 // are dealing with the final value computed by the loop.
10324 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10325 // First, attempt to evaluate each operand.
10326 // Avoid performing the look-up in the common case where the specified
10327 // expression has no loop-variant portions.
10328 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10329 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10330 if (OpAtScope == AddRec->getOperand(i))
10331 continue;
10332
10333 // Okay, at least one of these operands is loop variant but might be
10334 // foldable. Build a new instance of the folded commutative expression.
10336 NewOps.reserve(AddRec->getNumOperands());
10337 append_range(NewOps, AddRec->operands().take_front(i));
10338 NewOps.push_back(OpAtScope);
10339 for (++i; i != e; ++i)
10340 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10341
10342 const SCEV *FoldedRec = getAddRecExpr(
10343 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10344 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10345 // The addrec may be folded to a nonrecurrence, for example, if the
10346 // induction variable is multiplied by zero after constant folding. Go
10347 // ahead and return the folded value.
10348 if (!AddRec)
10349 return FoldedRec;
10350 break;
10351 }
10352
10353 // If the scope is outside the addrec's loop, evaluate it by using the
10354 // loop exit value of the addrec.
10355 if (!AddRec->getLoop()->contains(L)) {
10356 // To evaluate this recurrence, we need to know how many times the AddRec
10357 // loop iterates. Compute this now.
10358 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
10359 if (BackedgeTakenCount == getCouldNotCompute())
10360 return AddRec;
10361
10362 // Then, evaluate the AddRec.
10363 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
10364 }
10365
10366 return AddRec;
10367 }
10368 case scTruncate:
10369 case scZeroExtend:
10370 case scSignExtend:
10371 case scPtrToAddr:
10372 case scPtrToInt:
10373 case scAddExpr:
10374 case scMulExpr:
10375 case scUDivExpr:
10376 case scUMaxExpr:
10377 case scSMaxExpr:
10378 case scUMinExpr:
10379 case scSMinExpr:
10380 case scSequentialUMinExpr: {
10381 ArrayRef<SCEVUse> Ops = V->operands();
10382 // Avoid performing the look-up in the common case where the specified
10383 // expression has no loop-variant portions.
10384 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10385 const SCEV *OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10386 if (OpAtScope != Ops[i].getPointer()) {
10387 // Okay, at least one of these operands is loop variant but might be
10388 // foldable. Build a new instance of the folded commutative expression.
10390 NewOps.reserve(Ops.size());
10391 append_range(NewOps, Ops.take_front(i));
10392 NewOps.push_back(OpAtScope);
10393
10394 for (++i; i != e; ++i) {
10395 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10396 NewOps.push_back(OpAtScope);
10397 }
10398
10399 return getWithOperands(V, NewOps);
10400 }
10401 }
10402 // If we got here, all operands are loop invariant.
10403 return V;
10404 }
10405 case scUnknown: {
10406 // If this instruction is evolved from a constant-evolving PHI, compute the
10407 // exit value from the loop without using SCEVs.
10408 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10410 if (!I)
10411 return V; // This is some other type of SCEVUnknown, just return it.
10412
10413 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10414 const Loop *CurrLoop = this->LI[I->getParent()];
10415 // Looking for loop exit value.
10416 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10417 PN->getParent() == CurrLoop->getHeader()) {
10418 // Okay, there is no closed form solution for the PHI node. Check
10419 // to see if the loop that contains it has a known backedge-taken
10420 // count. If so, we may be able to force computation of the exit
10421 // value.
10422 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10423 // This trivial case can show up in some degenerate cases where
10424 // the incoming IR has not yet been fully simplified.
10425 if (BackedgeTakenCount->isZero()) {
10426 Value *InitValue = nullptr;
10427 bool MultipleInitValues = false;
10428 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10429 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10430 if (!InitValue)
10431 InitValue = PN->getIncomingValue(i);
10432 else if (InitValue != PN->getIncomingValue(i)) {
10433 MultipleInitValues = true;
10434 break;
10435 }
10436 }
10437 }
10438 if (!MultipleInitValues && InitValue)
10439 return getSCEV(InitValue);
10440 }
10441 // Do we have a loop invariant value flowing around the backedge
10442 // for a loop which must execute the backedge?
10443 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10444 isKnownNonZero(BackedgeTakenCount) &&
10445 PN->getNumIncomingValues() == 2) {
10446
10447 unsigned InLoopPred =
10448 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10449 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10450 if (CurrLoop->isLoopInvariant(BackedgeVal))
10451 return getSCEV(BackedgeVal);
10452 }
10453 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10454 // Okay, we know how many times the containing loop executes. If
10455 // this is a constant evolving PHI node, get the final value at
10456 // the specified iteration number.
10457 Constant *RV =
10458 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10459 if (RV)
10460 return getSCEV(RV);
10461 }
10462 }
10463 }
10464
10465 // Okay, this is an expression that we cannot symbolically evaluate
10466 // into a SCEV. Check to see if it's possible to symbolically evaluate
10467 // the arguments into constants, and if so, try to constant propagate the
10468 // result. This is particularly useful for computing loop exit values.
10469 if (!CanConstantFold(I))
10470 return V; // This is some other type of SCEVUnknown, just return it.
10471
10472 SmallVector<Constant *, 4> Operands;
10473 Operands.reserve(I->getNumOperands());
10474 bool MadeImprovement = false;
10475 for (Value *Op : I->operands()) {
10476 if (Constant *C = dyn_cast<Constant>(Op)) {
10477 Operands.push_back(C);
10478 continue;
10479 }
10480
10481 // If any of the operands is non-constant and if they are
10482 // non-integer and non-pointer, don't even try to analyze them
10483 // with scev techniques.
10484 if (!isSCEVable(Op->getType()))
10485 return V;
10486
10487 const SCEV *OrigV = getSCEV(Op);
10488 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10489 MadeImprovement |= OrigV != OpV;
10490
10492 if (!C)
10493 return V;
10494 assert(C->getType() == Op->getType() && "Type mismatch");
10495 Operands.push_back(C);
10496 }
10497
10498 // Check to see if getSCEVAtScope actually made an improvement.
10499 if (!MadeImprovement)
10500 return V; // This is some other type of SCEVUnknown, just return it.
10501
10502 Constant *C = nullptr;
10503 const DataLayout &DL = getDataLayout();
10504 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10505 /*AllowNonDeterministic=*/false);
10506 if (!C)
10507 return V;
10508 return getSCEV(C);
10509 }
10510 case scCouldNotCompute:
10511 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10512 }
10513 llvm_unreachable("Unknown SCEV type!");
10514}
10515
10517 return getSCEVAtScope(getSCEV(V), L);
10518}
10519
10520const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10522 return stripInjectiveFunctions(ZExt->getOperand());
10524 return stripInjectiveFunctions(SExt->getOperand());
10525 return S;
10526}
10527
10528/// Finds the minimum unsigned root of the following equation:
10529///
10530/// A * X = B (mod N)
10531///
10532/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10533/// A and B isn't important.
10534///
10535/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10536static const SCEV *
10539 ScalarEvolution &SE, const Loop *L) {
10540 uint32_t BW = A.getBitWidth();
10541 assert(BW == SE.getTypeSizeInBits(B->getType()));
10542 assert(A != 0 && "A must be non-zero.");
10543
10544 // 1. D = gcd(A, N)
10545 //
10546 // The gcd of A and N may have only one prime factor: 2. The number of
10547 // trailing zeros in A is its multiplicity
10548 uint32_t Mult2 = A.countr_zero();
10549 // D = 2^Mult2
10550
10551 // 2. Check if B is divisible by D.
10552 //
10553 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10554 // is not less than multiplicity of this prime factor for D.
10555 unsigned MinTZ = SE.getMinTrailingZeros(B);
10556 // Try again with the terminator of the loop predecessor for context-specific
10557 // result, if MinTZ s too small.
10558 if (MinTZ < Mult2 && L->getLoopPredecessor())
10559 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10560 if (MinTZ < Mult2) {
10561 // Check if we can prove there's no remainder using URem.
10562 const SCEV *URem =
10563 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10564 const SCEV *Zero = SE.getZero(B->getType());
10565 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10566 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10567 if (!Predicates)
10568 return SE.getCouldNotCompute();
10569
10570 // Avoid adding a predicate that is known to be false.
10571 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10572 return SE.getCouldNotCompute();
10573 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10574 }
10575 }
10576
10577 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10578 // modulo (N / D).
10579 //
10580 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10581 // (N / D) in general. The inverse itself always fits into BW bits, though,
10582 // so we immediately truncate it.
10583 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10584 APInt I = AD.multiplicativeInverse().zext(BW);
10585
10586 // 4. Compute the minimum unsigned root of the equation:
10587 // I * (B / D) mod (N / D)
10588 // To simplify the computation, we factor out the divide by D:
10589 // (I * B mod N) / D
10590 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10591 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10592}
10593
10594/// For a given quadratic addrec, generate coefficients of the corresponding
10595/// quadratic equation, multiplied by a common value to ensure that they are
10596/// integers.
10597/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10598/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10599/// were multiplied by, and BitWidth is the bit width of the original addrec
10600/// coefficients.
10601/// This function returns std::nullopt if the addrec coefficients are not
10602/// compile- time constants.
10603static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10605 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10606 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10607 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10608 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10609 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10610 << *AddRec << '\n');
10611
10612 // We currently can only solve this if the coefficients are constants.
10613 if (!LC || !MC || !NC) {
10614 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10615 return std::nullopt;
10616 }
10617
10618 APInt L = LC->getAPInt();
10619 APInt M = MC->getAPInt();
10620 APInt N = NC->getAPInt();
10621 assert(!N.isZero() && "This is not a quadratic addrec");
10622
10623 unsigned BitWidth = LC->getAPInt().getBitWidth();
10624 unsigned NewWidth = BitWidth + 1;
10625 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10626 << BitWidth << '\n');
10627 // The sign-extension (as opposed to a zero-extension) here matches the
10628 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10629 N = N.sext(NewWidth);
10630 M = M.sext(NewWidth);
10631 L = L.sext(NewWidth);
10632
10633 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10634 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10635 // L+M, L+2M+N, L+3M+3N, ...
10636 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10637 //
10638 // The equation Acc = 0 is then
10639 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10640 // In a quadratic form it becomes:
10641 // N n^2 + (2M-N) n + 2L = 0.
10642
10643 APInt A = N;
10644 APInt B = 2 * M - A;
10645 APInt C = 2 * L;
10646 APInt T = APInt(NewWidth, 2);
10647 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10648 << "x + " << C << ", coeff bw: " << NewWidth
10649 << ", multiplied by " << T << '\n');
10650 return std::make_tuple(A, B, C, T, BitWidth);
10651}
10652
10653/// Helper function to compare optional APInts:
10654/// (a) if X and Y both exist, return min(X, Y),
10655/// (b) if neither X nor Y exist, return std::nullopt,
10656/// (c) if exactly one of X and Y exists, return that value.
10657static std::optional<APInt> MinOptional(std::optional<APInt> X,
10658 std::optional<APInt> Y) {
10659 if (X && Y) {
10660 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10661 APInt XW = X->sext(W);
10662 APInt YW = Y->sext(W);
10663 return XW.slt(YW) ? *X : *Y;
10664 }
10665 if (!X && !Y)
10666 return std::nullopt;
10667 return X ? *X : *Y;
10668}
10669
10670/// Helper function to truncate an optional APInt to a given BitWidth.
10671/// When solving addrec-related equations, it is preferable to return a value
10672/// that has the same bit width as the original addrec's coefficients. If the
10673/// solution fits in the original bit width, truncate it (except for i1).
10674/// Returning a value of a different bit width may inhibit some optimizations.
10675///
10676/// In general, a solution to a quadratic equation generated from an addrec
10677/// may require BW+1 bits, where BW is the bit width of the addrec's
10678/// coefficients. The reason is that the coefficients of the quadratic
10679/// equation are BW+1 bits wide (to avoid truncation when converting from
10680/// the addrec to the equation).
10681static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10682 unsigned BitWidth) {
10683 if (!X)
10684 return std::nullopt;
10685 unsigned W = X->getBitWidth();
10687 return X->trunc(BitWidth);
10688 return X;
10689}
10690
10691/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10692/// iterations. The values L, M, N are assumed to be signed, and they
10693/// should all have the same bit widths.
10694/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10695/// where BW is the bit width of the addrec's coefficients.
10696/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10697/// returned as such, otherwise the bit width of the returned value may
10698/// be greater than BW.
10699///
10700/// This function returns std::nullopt if
10701/// (a) the addrec coefficients are not constant, or
10702/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10703/// like x^2 = 5, no integer solutions exist, in other cases an integer
10704/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10705static std::optional<APInt>
10707 APInt A, B, C, M;
10708 unsigned BitWidth;
10709 auto T = GetQuadraticEquation(AddRec);
10710 if (!T)
10711 return std::nullopt;
10712
10713 std::tie(A, B, C, M, BitWidth) = *T;
10714 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10715 std::optional<APInt> X =
10717 if (!X)
10718 return std::nullopt;
10719
10720 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10721 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10722 if (!V->isZero())
10723 return std::nullopt;
10724
10725 return TruncIfPossible(X, BitWidth);
10726}
10727
10728/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10729/// iterations. The values M, N are assumed to be signed, and they
10730/// should all have the same bit widths.
10731/// Find the least n such that c(n) does not belong to the given range,
10732/// while c(n-1) does.
10733///
10734/// This function returns std::nullopt if
10735/// (a) the addrec coefficients are not constant, or
10736/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10737/// bounds of the range.
10738static std::optional<APInt>
10740 const ConstantRange &Range, ScalarEvolution &SE) {
10741 assert(AddRec->getOperand(0)->isZero() &&
10742 "Starting value of addrec should be 0");
10743 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10744 << Range << ", addrec " << *AddRec << '\n');
10745 // This case is handled in getNumIterationsInRange. Here we can assume that
10746 // we start in the range.
10747 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10748 "Addrec's initial value should be in range");
10749
10750 APInt A, B, C, M;
10751 unsigned BitWidth;
10752 auto T = GetQuadraticEquation(AddRec);
10753 if (!T)
10754 return std::nullopt;
10755
10756 // Be careful about the return value: there can be two reasons for not
10757 // returning an actual number. First, if no solutions to the equations
10758 // were found, and second, if the solutions don't leave the given range.
10759 // The first case means that the actual solution is "unknown", the second
10760 // means that it's known, but not valid. If the solution is unknown, we
10761 // cannot make any conclusions.
10762 // Return a pair: the optional solution and a flag indicating if the
10763 // solution was found.
10764 auto SolveForBoundary =
10765 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10766 // Solve for signed overflow and unsigned overflow, pick the lower
10767 // solution.
10768 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10769 << Bound << " (before multiplying by " << M << ")\n");
10770 Bound *= M; // The quadratic equation multiplier.
10771
10772 std::optional<APInt> SO;
10773 if (BitWidth > 1) {
10774 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10775 "signed overflow\n");
10777 }
10778 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10779 "unsigned overflow\n");
10780 std::optional<APInt> UO =
10782
10783 auto LeavesRange = [&] (const APInt &X) {
10784 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10785 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10786 if (Range.contains(V0->getValue()))
10787 return false;
10788 // X should be at least 1, so X-1 is non-negative.
10789 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10791 if (Range.contains(V1->getValue()))
10792 return true;
10793 return false;
10794 };
10795
10796 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10797 // can be a solution, but the function failed to find it. We cannot treat it
10798 // as "no solution".
10799 if (!SO || !UO)
10800 return {std::nullopt, false};
10801
10802 // Check the smaller value first to see if it leaves the range.
10803 // At this point, both SO and UO must have values.
10804 std::optional<APInt> Min = MinOptional(SO, UO);
10805 if (LeavesRange(*Min))
10806 return { Min, true };
10807 std::optional<APInt> Max = Min == SO ? UO : SO;
10808 if (LeavesRange(*Max))
10809 return { Max, true };
10810
10811 // Solutions were found, but were eliminated, hence the "true".
10812 return {std::nullopt, true};
10813 };
10814
10815 std::tie(A, B, C, M, BitWidth) = *T;
10816 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10817 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10818 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10819 auto SL = SolveForBoundary(Lower);
10820 auto SU = SolveForBoundary(Upper);
10821 // If any of the solutions was unknown, no meaninigful conclusions can
10822 // be made.
10823 if (!SL.second || !SU.second)
10824 return std::nullopt;
10825
10826 // Claim: The correct solution is not some value between Min and Max.
10827 //
10828 // Justification: Assuming that Min and Max are different values, one of
10829 // them is when the first signed overflow happens, the other is when the
10830 // first unsigned overflow happens. Crossing the range boundary is only
10831 // possible via an overflow (treating 0 as a special case of it, modeling
10832 // an overflow as crossing k*2^W for some k).
10833 //
10834 // The interesting case here is when Min was eliminated as an invalid
10835 // solution, but Max was not. The argument is that if there was another
10836 // overflow between Min and Max, it would also have been eliminated if
10837 // it was considered.
10838 //
10839 // For a given boundary, it is possible to have two overflows of the same
10840 // type (signed/unsigned) without having the other type in between: this
10841 // can happen when the vertex of the parabola is between the iterations
10842 // corresponding to the overflows. This is only possible when the two
10843 // overflows cross k*2^W for the same k. In such case, if the second one
10844 // left the range (and was the first one to do so), the first overflow
10845 // would have to enter the range, which would mean that either we had left
10846 // the range before or that we started outside of it. Both of these cases
10847 // are contradictions.
10848 //
10849 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10850 // solution is not some value between the Max for this boundary and the
10851 // Min of the other boundary.
10852 //
10853 // Justification: Assume that we had such Max_A and Min_B corresponding
10854 // to range boundaries A and B and such that Max_A < Min_B. If there was
10855 // a solution between Max_A and Min_B, it would have to be caused by an
10856 // overflow corresponding to either A or B. It cannot correspond to B,
10857 // since Min_B is the first occurrence of such an overflow. If it
10858 // corresponded to A, it would have to be either a signed or an unsigned
10859 // overflow that is larger than both eliminated overflows for A. But
10860 // between the eliminated overflows and this overflow, the values would
10861 // cover the entire value space, thus crossing the other boundary, which
10862 // is a contradiction.
10863
10864 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10865}
10866
10867ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10868 const Loop *L,
10869 bool ControlsOnlyExit,
10870 bool AllowPredicates) {
10871
10872 // This is only used for loops with a "x != y" exit test. The exit condition
10873 // is now expressed as a single expression, V = x-y. So the exit test is
10874 // effectively V != 0. We know and take advantage of the fact that this
10875 // expression only being used in a comparison by zero context.
10876
10878 // If the value is a constant
10879 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10880 // If the value is already zero, the branch will execute zero times.
10881 if (C->getValue()->isZero()) return C;
10882 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10883 }
10884
10885 const SCEVAddRecExpr *AddRec =
10886 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10887
10888 if (!AddRec && AllowPredicates)
10889 // Try to make this an AddRec using runtime tests, in the first X
10890 // iterations of this loop, where X is the SCEV expression found by the
10891 // algorithm below.
10892 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10893
10894 if (!AddRec || AddRec->getLoop() != L)
10895 return getCouldNotCompute();
10896
10897 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10898 // the quadratic equation to solve it.
10899 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10900 // We can only use this value if the chrec ends up with an exact zero
10901 // value at this index. When solving for "X*X != 5", for example, we
10902 // should not accept a root of 2.
10903 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10904 const auto *R = cast<SCEVConstant>(getConstant(*S));
10905 return ExitLimit(R, R, R, false, Predicates);
10906 }
10907 return getCouldNotCompute();
10908 }
10909
10910 // Otherwise we can only handle this if it is affine.
10911 if (!AddRec->isAffine())
10912 return getCouldNotCompute();
10913
10914 // If this is an affine expression, the execution count of this branch is
10915 // the minimum unsigned root of the following equation:
10916 //
10917 // Start + Step*N = 0 (mod 2^BW)
10918 //
10919 // equivalent to:
10920 //
10921 // Step*N = -Start (mod 2^BW)
10922 //
10923 // where BW is the common bit width of Start and Step.
10924
10925 // Get the initial value for the loop.
10926 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10927 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10928
10929 if (!isLoopInvariant(Step, L))
10930 return getCouldNotCompute();
10931
10932 LoopGuards Guards = LoopGuards::collect(L, *this);
10933 // Specialize step for this loop so we get context sensitive facts below.
10934 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10935
10936 // For positive steps (counting up until unsigned overflow):
10937 // N = -Start/Step (as unsigned)
10938 // For negative steps (counting down to zero):
10939 // N = Start/-Step
10940 // First compute the unsigned distance from zero in the direction of Step.
10941 bool CountDown = isKnownNegative(StepWLG);
10942 if (!CountDown && !isKnownNonNegative(StepWLG))
10943 return getCouldNotCompute();
10944
10945 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10946 // Handle unitary steps, which cannot wraparound.
10947 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10948 // N = Distance (as unsigned)
10949
10950 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10951 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10952 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10953
10954 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10955 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10956 // case, and see if we can improve the bound.
10957 //
10958 // Explicitly handling this here is necessary because getUnsignedRange
10959 // isn't context-sensitive; it doesn't know that we only care about the
10960 // range inside the loop.
10961 const SCEV *Zero = getZero(Distance->getType());
10962 const SCEV *One = getOne(Distance->getType());
10963 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10964 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10965 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10966 // as "unsigned_max(Distance + 1) - 1".
10967 ConstantRange CR = getUnsignedRange(DistancePlusOne);
10968 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
10969 }
10970 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10971 Predicates);
10972 }
10973
10974 // If the condition controls loop exit (the loop exits only if the expression
10975 // is true) and the addition is no-wrap we can use unsigned divide to
10976 // compute the backedge count. In this case, the step may not divide the
10977 // distance, but we don't care because if the condition is "missed" the loop
10978 // will have undefined behavior due to wrapping.
10979 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10980 loopHasNoAbnormalExits(AddRec->getLoop())) {
10981
10982 // If the stride is zero and the start is non-zero, the loop must be
10983 // infinite. In C++, most loops are finite by assumption, in which case the
10984 // step being zero implies UB must execute if the loop is entered.
10985 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10986 !isKnownNonZero(StepWLG))
10987 return getCouldNotCompute();
10988
10989 const SCEV *Exact =
10990 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10991 const SCEV *ConstantMax = getCouldNotCompute();
10992 if (Exact != getCouldNotCompute()) {
10993 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10994 ConstantMax =
10996 }
10997 const SCEV *SymbolicMax =
10998 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10999 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
11000 }
11001
11002 // Solve the general equation.
11003 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
11004 if (!StepC || StepC->getValue()->isZero())
11005 return getCouldNotCompute();
11006 const SCEV *E = SolveLinEquationWithOverflow(
11007 StepC->getAPInt(), getNegativeSCEV(Start),
11008 AllowPredicates ? &Predicates : nullptr, *this, L);
11009
11010 const SCEV *M = E;
11011 if (E != getCouldNotCompute()) {
11012 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
11013 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
11014 }
11015 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
11016 return ExitLimit(E, M, S, false, Predicates);
11017}
11018
11019ScalarEvolution::ExitLimit
11020ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
11021 // Loops that look like: while (X == 0) are very strange indeed. We don't
11022 // handle them yet except for the trivial case. This could be expanded in the
11023 // future as needed.
11024
11025 // If the value is a constant, check to see if it is known to be non-zero
11026 // already. If so, the backedge will execute zero times.
11027 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
11028 if (!C->getValue()->isZero())
11029 return getZero(C->getType());
11030 return getCouldNotCompute(); // Otherwise it will loop infinitely.
11031 }
11032
11033 // We could implement others, but I really doubt anyone writes loops like
11034 // this, and if they did, they would already be constant folded.
11035 return getCouldNotCompute();
11036}
11037
11038std::pair<const BasicBlock *, const BasicBlock *>
11039ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
11040 const {
11041 // If the block has a unique predecessor, then there is no path from the
11042 // predecessor to the block that does not go through the direct edge
11043 // from the predecessor to the block.
11044 if (const BasicBlock *Pred = BB->getSinglePredecessor())
11045 return {Pred, BB};
11046
11047 // A loop's header is defined to be a block that dominates the loop.
11048 // If the header has a unique predecessor outside the loop, it must be
11049 // a block that has exactly one successor that can reach the loop.
11050 if (const Loop *L = LI.getLoopFor(BB))
11051 return {L->getLoopPredecessor(), L->getHeader()};
11052
11053 return {nullptr, BB};
11054}
11055
11056/// SCEV structural equivalence is usually sufficient for testing whether two
11057/// expressions are equal, however for the purposes of looking for a condition
11058/// guarding a loop, it can be useful to be a little more general, since a
11059/// front-end may have replicated the controlling expression.
11060static bool HasSameValue(const SCEV *A, const SCEV *B) {
11061 // Quick check to see if they are the same SCEV.
11062 if (A == B) return true;
11063
11064 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
11065 // Not all instructions that are "identical" compute the same value. For
11066 // instance, two distinct alloca instructions allocating the same type are
11067 // identical and do not read memory; but compute distinct values.
11068 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
11069 };
11070
11071 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
11072 // two different instructions with the same value. Check for this case.
11073 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
11074 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
11075 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
11076 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
11077 if (ComputesEqualValues(AI, BI))
11078 return true;
11079
11080 // Otherwise assume they may have a different value.
11081 return false;
11082}
11083
11084static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
11085 const SCEV *Op0, *Op1;
11086 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
11087 return false;
11088 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
11089 LHS = Op1;
11090 return true;
11091 }
11092 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
11093 LHS = Op0;
11094 return true;
11095 }
11096 return false;
11097}
11098
11100 SCEVUse &RHS, unsigned Depth) {
11101 bool Changed = false;
11102 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
11103 // '0 != 0'.
11104 auto TrivialCase = [&](bool TriviallyTrue) {
11106 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
11107 return true;
11108 };
11109 // If we hit the max recursion limit bail out.
11110 if (Depth >= 3)
11111 return false;
11112
11113 const SCEV *NewLHS, *NewRHS;
11114 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
11115 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
11116 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
11117 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
11118
11119 // (X * vscale) pred (Y * vscale) ==> X pred Y
11120 // when both multiples are NSW.
11121 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
11122 // when both multiples are NUW.
11123 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
11124 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
11125 !ICmpInst::isSigned(Pred))) {
11126 LHS = NewLHS;
11127 RHS = NewRHS;
11128 Changed = true;
11129 }
11130 }
11131
11132 // Canonicalize a constant to the right side.
11133 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
11134 // Check for both operands constant.
11135 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
11136 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
11137 return TrivialCase(false);
11138 return TrivialCase(true);
11139 }
11140 // Otherwise swap the operands to put the constant on the right.
11141 std::swap(LHS, RHS);
11143 Changed = true;
11144 }
11145
11146 // (K + A) pred (K + B) --> A pred B
11147 // For equality, no flags are needed.
11148 // For signed, both adds must be NSW. For unsigned, both must be NUW.
11149 {
11150 const SCEVConstant *C = nullptr;
11151 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11152 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11153 const auto *LAdd = cast<SCEVAddExpr>(LHS);
11154 const auto *RAdd = cast<SCEVAddExpr>(RHS);
11155 if (ICmpInst::isEquality(Pred) ||
11156 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
11157 RAdd->hasNoSignedWrap()) ||
11158 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
11159 RAdd->hasNoUnsignedWrap())) {
11160 LHS = NewLHS;
11161 RHS = NewRHS;
11162 Changed = true;
11163 }
11164 }
11165 }
11166
11167 // (C * A) pred (C * B) --> A pred B
11168 // For equality predicates, both muls must be NUW or both must be NSW
11169 // (either suffices to make multiplication by C injective; C == 0 is
11170 // impossible because SCEV folds 0 * X to 0).
11171 // For signed ordering, C must be positive and both muls must be NSW.
11172 // For unsigned ordering, both muls must be NUW.
11173 {
11174 const SCEVConstant *C = nullptr;
11175 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11176 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11177 const auto *LMul = cast<SCEVMulExpr>(LHS);
11178 const auto *RMul = cast<SCEVMulExpr>(RHS);
11179 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11180 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11181 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11182 (ICmpInst::isSigned(Pred) && BothNSW &&
11183 C->getAPInt().isStrictlyPositive()) ||
11184 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11185 LHS = NewLHS;
11186 RHS = NewRHS;
11187 Changed = true;
11188 }
11189 }
11190 }
11191
11192 // If we're comparing an addrec with a value which is loop-invariant in the
11193 // addrec's loop, put the addrec on the left. Also make a dominance check,
11194 // as both operands could be addrecs loop-invariant in each other's loop.
11195 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11196 const Loop *L = AR->getLoop();
11197 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11198 std::swap(LHS, RHS);
11200 Changed = true;
11201 }
11202 }
11203
11204 // If there's a constant operand, canonicalize comparisons with boundary
11205 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11206 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11207 const APInt &RA = RC->getAPInt();
11208
11209 bool SimplifiedByConstantRange = false;
11210
11211 if (!ICmpInst::isEquality(Pred)) {
11213 if (ExactCR.isFullSet())
11214 return TrivialCase(true);
11215 if (ExactCR.isEmptySet())
11216 return TrivialCase(false);
11217
11218 APInt NewRHS;
11219 CmpInst::Predicate NewPred;
11220 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11221 ICmpInst::isEquality(NewPred)) {
11222 // We were able to convert an inequality to an equality.
11223 Pred = NewPred;
11224 RHS = getConstant(NewRHS);
11225 Changed = SimplifiedByConstantRange = true;
11226 }
11227 }
11228
11229 if (!SimplifiedByConstantRange) {
11230 switch (Pred) {
11231 default:
11232 break;
11233 case ICmpInst::ICMP_EQ:
11234 case ICmpInst::ICMP_NE:
11235 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11236 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11237 Changed = true;
11238 break;
11239
11240 // The "Should have been caught earlier!" messages refer to the fact
11241 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11242 // should have fired on the corresponding cases, and canonicalized the
11243 // check to trivial case.
11244
11245 case ICmpInst::ICMP_UGE:
11246 assert(!RA.isMinValue() && "Should have been caught earlier!");
11247 Pred = ICmpInst::ICMP_UGT;
11248 RHS = getConstant(RA - 1);
11249 Changed = true;
11250 break;
11251 case ICmpInst::ICMP_ULE:
11252 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11253 Pred = ICmpInst::ICMP_ULT;
11254 RHS = getConstant(RA + 1);
11255 Changed = true;
11256 break;
11257 case ICmpInst::ICMP_SGE:
11258 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11259 Pred = ICmpInst::ICMP_SGT;
11260 RHS = getConstant(RA - 1);
11261 Changed = true;
11262 break;
11263 case ICmpInst::ICMP_SLE:
11264 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11265 Pred = ICmpInst::ICMP_SLT;
11266 RHS = getConstant(RA + 1);
11267 Changed = true;
11268 break;
11269 }
11270 }
11271 }
11272
11273 // Check for obvious equality.
11274 if (HasSameValue(LHS, RHS)) {
11275 if (ICmpInst::isTrueWhenEqual(Pred))
11276 return TrivialCase(true);
11278 return TrivialCase(false);
11279 }
11280
11281 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11282 // adding or subtracting 1 from one of the operands.
11283 switch (Pred) {
11284 case ICmpInst::ICMP_SLE:
11285 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11286 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11288 Pred = ICmpInst::ICMP_SLT;
11289 Changed = true;
11290 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11291 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11293 Pred = ICmpInst::ICMP_SLT;
11294 Changed = true;
11295 }
11296 break;
11297 case ICmpInst::ICMP_SGE:
11298 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11299 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11301 Pred = ICmpInst::ICMP_SGT;
11302 Changed = true;
11303 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11304 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11306 Pred = ICmpInst::ICMP_SGT;
11307 Changed = true;
11308 }
11309 break;
11310 case ICmpInst::ICMP_ULE:
11311 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11312 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11314 Pred = ICmpInst::ICMP_ULT;
11315 Changed = true;
11316 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11317 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11318 Pred = ICmpInst::ICMP_ULT;
11319 Changed = true;
11320 }
11321 break;
11322 case ICmpInst::ICMP_UGE:
11323 // If RHS is an op we can fold the -1, try that first.
11324 // Otherwise prefer LHS to preserve the nuw flag.
11325 if ((isa<SCEVConstant>(RHS) ||
11327 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11328 !getUnsignedRangeMin(RHS).isMinValue()) {
11329 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11330 Pred = ICmpInst::ICMP_UGT;
11331 Changed = true;
11332 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11333 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11335 Pred = ICmpInst::ICMP_UGT;
11336 Changed = true;
11337 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11338 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11339 Pred = ICmpInst::ICMP_UGT;
11340 Changed = true;
11341 }
11342 break;
11343 default:
11344 break;
11345 }
11346
11347 // TODO: More simplifications are possible here.
11348
11349 // Recursively simplify until we either hit a recursion limit or nothing
11350 // changes.
11351 if (Changed)
11352 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11353
11354 return Changed;
11355}
11356
11358 return getSignedRangeMax(S).isNegative();
11359}
11360
11364
11366 return !getSignedRangeMin(S).isNegative();
11367}
11368
11372
11374 // Query push down for cases where the unsigned range is
11375 // less than sufficient.
11376 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11377 return isKnownNonZero(SExt->getOperand(0));
11378 return getUnsignedRangeMin(S) != 0;
11379}
11380
11382 bool OrNegative) {
11383 auto NonRecursive = [OrNegative](const SCEV *S) {
11384 if (auto *C = dyn_cast<SCEVConstant>(S))
11385 return C->getAPInt().isPowerOf2() ||
11386 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11387
11388 // vscale is a power-of-two.
11389 return isa<SCEVVScale>(S);
11390 };
11391
11392 if (NonRecursive(S))
11393 return true;
11394
11395 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11396 if (!Mul)
11397 return false;
11398 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11399}
11400
11402 const SCEV *S, uint64_t M,
11404 if (M == 0)
11405 return false;
11406 if (M == 1)
11407 return true;
11408
11409 // Recursively check AddRec operands. An AddRecExpr S is a multiple of M if S
11410 // starts with a multiple of M and at every iteration step S only adds
11411 // multiples of M.
11412 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
11413 return isKnownMultipleOf(AddRec->getStart(), M, Assumptions) &&
11414 isKnownMultipleOf(AddRec->getStepRecurrence(*this), M, Assumptions);
11415
11416 // For a constant, check that "S % M == 0".
11417 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11418 APInt C = Cst->getAPInt();
11419 return C.urem(M) == 0;
11420 }
11421
11422 // TODO: Also check other SCEV expressions, i.e., SCEVAddRecExpr, etc.
11423
11424 // Basic tests have failed.
11425 // Check "S % M == 0" at compile time and record runtime Assumptions.
11426 auto *STy = dyn_cast<IntegerType>(S->getType());
11427 const SCEV *SmodM =
11428 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11429 const SCEV *Zero = getZero(STy);
11430
11431 // Check whether "S % M == 0" is known at compile time.
11432 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11433 return true;
11434
11435 // Check whether "S % M != 0" is known at compile time.
11436 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11437 return false;
11438
11440
11441 // Detect redundant predicates.
11442 for (auto *A : Assumptions)
11443 if (A->implies(P, *this))
11444 return true;
11445
11446 // Only record non-redundant predicates.
11447 Assumptions.push_back(P);
11448 return true;
11449}
11450
11452 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11454}
11455
11456std::pair<const SCEV *, const SCEV *>
11458 // Compute SCEV on entry of loop L.
11459 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11460 if (Start == getCouldNotCompute())
11461 return { Start, Start };
11462 // Compute post increment SCEV for loop L.
11463 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11464 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11465 return { Start, PostInc };
11466}
11467
11469 SCEVUse RHS) {
11470 // First collect all loops.
11472 getUsedLoops(LHS, LoopsUsed);
11473 getUsedLoops(RHS, LoopsUsed);
11474
11475 if (LoopsUsed.empty())
11476 return false;
11477
11478 // Domination relationship must be a linear order on collected loops.
11479#ifndef NDEBUG
11480 for (const auto *L1 : LoopsUsed)
11481 for (const auto *L2 : LoopsUsed)
11482 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11483 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11484 "Domination relationship is not a linear order");
11485#endif
11486
11487 const Loop *MDL =
11488 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11489 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11490 });
11491
11492 // Get init and post increment value for LHS.
11493 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11494 // if LHS contains unknown non-invariant SCEV then bail out.
11495 if (SplitLHS.first == getCouldNotCompute())
11496 return false;
11497 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11498 // Get init and post increment value for RHS.
11499 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11500 // if RHS contains unknown non-invariant SCEV then bail out.
11501 if (SplitRHS.first == getCouldNotCompute())
11502 return false;
11503 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11504 // It is possible that init SCEV contains an invariant load but it does
11505 // not dominate MDL and is not available at MDL loop entry, so we should
11506 // check it here.
11507 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11508 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11509 return false;
11510
11511 // It seems backedge guard check is faster than entry one so in some cases
11512 // it can speed up whole estimation by short circuit
11513 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11514 SplitRHS.second) &&
11515 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11516}
11517
11519 SCEVUse RHS) {
11520 // Canonicalize the inputs first.
11521 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11522
11523 if (isKnownViaInduction(Pred, LHS, RHS))
11524 return true;
11525
11526 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
11527 return true;
11528
11529 // Otherwise see what can be done with some simple reasoning.
11530 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11531}
11532
11534 const SCEV *LHS,
11535 const SCEV *RHS) {
11536 if (isKnownPredicate(Pred, LHS, RHS))
11537 return true;
11539 return false;
11540 return std::nullopt;
11541}
11542
11544 const SCEV *RHS,
11545 const Instruction *CtxI) {
11546 // TODO: Analyze guards and assumes from Context's block.
11547 return isKnownPredicate(Pred, LHS, RHS) ||
11548 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11549}
11550
11551std::optional<bool>
11553 const SCEV *RHS, const Instruction *CtxI) {
11554 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11555 if (KnownWithoutContext)
11556 return KnownWithoutContext;
11557
11558 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11559 return true;
11561 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11562 return false;
11563 return std::nullopt;
11564}
11565
11567 const SCEVAddRecExpr *LHS,
11568 const SCEV *RHS) {
11569 const Loop *L = LHS->getLoop();
11570 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11571 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11572}
11573
11574std::optional<ScalarEvolution::MonotonicPredicateType>
11576 ICmpInst::Predicate Pred) {
11577 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11578
11579#ifndef NDEBUG
11580 // Verify an invariant: inverting the predicate should turn a monotonically
11581 // increasing change to a monotonically decreasing one, and vice versa.
11582 if (Result) {
11583 auto ResultSwapped =
11584 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11585
11586 assert(*ResultSwapped != *Result &&
11587 "monotonicity should flip as we flip the predicate");
11588 }
11589#endif
11590
11591 return Result;
11592}
11593
11594std::optional<ScalarEvolution::MonotonicPredicateType>
11595ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11596 ICmpInst::Predicate Pred) {
11597 // A zero step value for LHS means the induction variable is essentially a
11598 // loop invariant value. We don't really depend on the predicate actually
11599 // flipping from false to true (for increasing predicates, and the other way
11600 // around for decreasing predicates), all we care about is that *if* the
11601 // predicate changes then it only changes from false to true.
11602 //
11603 // A zero step value in itself is not very useful, but there may be places
11604 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11605 // as general as possible.
11606
11607 // Only handle LE/LT/GE/GT predicates.
11608 if (!ICmpInst::isRelational(Pred))
11609 return std::nullopt;
11610
11611 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11612 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11613 "Should be greater or less!");
11614
11615 // Check that AR does not wrap.
11616 if (ICmpInst::isUnsigned(Pred)) {
11617 if (!LHS->hasNoUnsignedWrap())
11618 return std::nullopt;
11620 }
11621 assert(ICmpInst::isSigned(Pred) &&
11622 "Relational predicate is either signed or unsigned!");
11623 if (!LHS->hasNoSignedWrap())
11624 return std::nullopt;
11625
11626 const SCEV *Step = LHS->getStepRecurrence(*this);
11627
11628 if (isKnownNonNegative(Step))
11630
11631 if (isKnownNonPositive(Step))
11633
11634 return std::nullopt;
11635}
11636
11637std::optional<ScalarEvolution::LoopInvariantPredicate>
11639 const SCEV *RHS, const Loop *L,
11640 const Instruction *CtxI) {
11641 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11642 if (!isLoopInvariant(RHS, L)) {
11643 if (!isLoopInvariant(LHS, L))
11644 return std::nullopt;
11645
11646 std::swap(LHS, RHS);
11648 }
11649
11650 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11651 if (!ArLHS || ArLHS->getLoop() != L)
11652 return std::nullopt;
11653
11654 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11655 if (!MonotonicType)
11656 return std::nullopt;
11657 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11658 // true as the loop iterates, and the backedge is control dependent on
11659 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11660 //
11661 // * if the predicate was false in the first iteration then the predicate
11662 // is never evaluated again, since the loop exits without taking the
11663 // backedge.
11664 // * if the predicate was true in the first iteration then it will
11665 // continue to be true for all future iterations since it is
11666 // monotonically increasing.
11667 //
11668 // For both the above possibilities, we can replace the loop varying
11669 // predicate with its value on the first iteration of the loop (which is
11670 // loop invariant).
11671 //
11672 // A similar reasoning applies for a monotonically decreasing predicate, by
11673 // replacing true with false and false with true in the above two bullets.
11675 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11676
11677 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11679 RHS);
11680
11681 if (!CtxI)
11682 return std::nullopt;
11683 // Try to prove via context.
11684 // TODO: Support other cases.
11685 switch (Pred) {
11686 default:
11687 break;
11688 case ICmpInst::ICMP_ULE:
11689 case ICmpInst::ICMP_ULT: {
11690 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11691 // Given preconditions
11692 // (1) ArLHS does not cross the border of positive and negative parts of
11693 // range because of:
11694 // - Positive step; (TODO: lift this limitation)
11695 // - nuw - does not cross zero boundary;
11696 // - nsw - does not cross SINT_MAX boundary;
11697 // (2) ArLHS <s RHS
11698 // (3) RHS >=s 0
11699 // we can replace the loop variant ArLHS <u RHS condition with loop
11700 // invariant Start(ArLHS) <u RHS.
11701 //
11702 // Because of (1) there are two options:
11703 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11704 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11705 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11706 // Because of (2) ArLHS <u RHS is trivially true.
11707 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11708 // We can strengthen this to Start(ArLHS) <u RHS.
11709 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11710 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11711 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11712 isKnownNonNegative(RHS) &&
11713 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11715 RHS);
11716 }
11717 }
11718
11719 return std::nullopt;
11720}
11721
11722std::optional<ScalarEvolution::LoopInvariantPredicate>
11724 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11725 const Instruction *CtxI, const SCEV *MaxIter) {
11727 Pred, LHS, RHS, L, CtxI, MaxIter))
11728 return LIP;
11729 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11730 // Number of iterations expressed as UMIN isn't always great for expressing
11731 // the value on the last iteration. If the straightforward approach didn't
11732 // work, try the following trick: if the a predicate is invariant for X, it
11733 // is also invariant for umin(X, ...). So try to find something that works
11734 // among subexpressions of MaxIter expressed as umin.
11735 for (SCEVUse Op : UMin->operands())
11737 Pred, LHS, RHS, L, CtxI, Op))
11738 return LIP;
11739 return std::nullopt;
11740}
11741
11742std::optional<ScalarEvolution::LoopInvariantPredicate>
11744 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11745 const Instruction *CtxI, const SCEV *MaxIter) {
11746 // Try to prove the following set of facts:
11747 // - The predicate is monotonic in the iteration space.
11748 // - If the check does not fail on the 1st iteration:
11749 // - No overflow will happen during first MaxIter iterations;
11750 // - It will not fail on the MaxIter'th iteration.
11751 // If the check does fail on the 1st iteration, we leave the loop and no
11752 // other checks matter.
11753
11754 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11755 if (!isLoopInvariant(RHS, L)) {
11756 if (!isLoopInvariant(LHS, L))
11757 return std::nullopt;
11758
11759 std::swap(LHS, RHS);
11761 }
11762
11763 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11764 if (!AR || AR->getLoop() != L)
11765 return std::nullopt;
11766
11767 // Even if both are valid, we need to consistently chose the unsigned or the
11768 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11769 // predicate.
11770 Pred = Pred.dropSameSign();
11771
11772 // The predicate must be relational (i.e. <, <=, >=, >).
11773 if (!ICmpInst::isRelational(Pred))
11774 return std::nullopt;
11775
11776 // TODO: Support steps other than +/- 1.
11777 const SCEV *Step = AR->getStepRecurrence(*this);
11778 auto *One = getOne(Step->getType());
11779 auto *MinusOne = getNegativeSCEV(One);
11780 if (Step != One && Step != MinusOne)
11781 return std::nullopt;
11782
11783 // Type mismatch here means that MaxIter is potentially larger than max
11784 // unsigned value in start type, which mean we cannot prove no wrap for the
11785 // indvar.
11786 if (AR->getType() != MaxIter->getType())
11787 return std::nullopt;
11788
11789 // Value of IV on suggested last iteration.
11790 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11791 // Does it still meet the requirement?
11792 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11793 return std::nullopt;
11794 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11795 // not exceed max unsigned value of this type), this effectively proves
11796 // that there is no wrap during the iteration. To prove that there is no
11797 // signed/unsigned wrap, we need to check that
11798 // Start <= Last for step = 1 or Start >= Last for step = -1.
11799 ICmpInst::Predicate NoOverflowPred =
11801 if (Step == MinusOne)
11802 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11803 const SCEV *Start = AR->getStart();
11804 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11805 return std::nullopt;
11806
11807 // Everything is fine.
11808 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11809}
11810
11811bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11812 SCEVUse LHS,
11813 SCEVUse RHS) {
11814 if (HasSameValue(LHS, RHS))
11815 return ICmpInst::isTrueWhenEqual(Pred);
11816
11817 auto CheckRange = [&](bool IsSigned) {
11818 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11819 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11820 return RangeLHS.icmp(Pred, RangeRHS);
11821 };
11822
11823 // The check at the top of the function catches the case where the values are
11824 // known to be equal.
11825 if (Pred == CmpInst::ICMP_EQ)
11826 return false;
11827
11828 if (Pred == CmpInst::ICMP_NE) {
11829 if (CheckRange(true) || CheckRange(false))
11830 return true;
11831 auto *Diff = getMinusSCEV(LHS, RHS);
11832 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11833 }
11834
11835 return CheckRange(CmpInst::isSigned(Pred));
11836}
11837
11838bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11840 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11841 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11842 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11843 // OutC1 and OutC2.
11844 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11845 APInt &OutC2,
11846 SCEV::NoWrapFlags ExpectedFlags) {
11847 SCEVUse XNonConstOp, XConstOp;
11848 SCEVUse YNonConstOp, YConstOp;
11849 SCEV::NoWrapFlags XFlagsPresent;
11850 SCEV::NoWrapFlags YFlagsPresent;
11851
11852 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11853 XConstOp = getZero(X->getType());
11854 XNonConstOp = X;
11855 XFlagsPresent = ExpectedFlags;
11856 }
11857 if (!isa<SCEVConstant>(XConstOp))
11858 return false;
11859
11860 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11861 YConstOp = getZero(Y->getType());
11862 YNonConstOp = Y;
11863 YFlagsPresent = ExpectedFlags;
11864 }
11865
11866 if (YNonConstOp != XNonConstOp)
11867 return false;
11868
11869 if (!isa<SCEVConstant>(YConstOp))
11870 return false;
11871
11872 // When matching ADDs with NUW flags (and unsigned predicates), only the
11873 // second ADD (with the larger constant) requires NUW.
11874 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11875 return false;
11876 if (ExpectedFlags != SCEV::FlagNUW &&
11877 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11878 return false;
11879 }
11880
11881 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11882 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11883
11884 return true;
11885 };
11886
11887 APInt C1;
11888 APInt C2;
11889
11890 switch (Pred) {
11891 default:
11892 break;
11893
11894 case ICmpInst::ICMP_SGE:
11895 std::swap(LHS, RHS);
11896 [[fallthrough]];
11897 case ICmpInst::ICMP_SLE:
11898 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11899 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11900 return true;
11901
11902 break;
11903
11904 case ICmpInst::ICMP_SGT:
11905 std::swap(LHS, RHS);
11906 [[fallthrough]];
11907 case ICmpInst::ICMP_SLT:
11908 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11909 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11910 return true;
11911
11912 break;
11913
11914 case ICmpInst::ICMP_UGE:
11915 std::swap(LHS, RHS);
11916 [[fallthrough]];
11917 case ICmpInst::ICMP_ULE:
11918 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11919 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11920 return true;
11921
11922 break;
11923
11924 case ICmpInst::ICMP_UGT:
11925 std::swap(LHS, RHS);
11926 [[fallthrough]];
11927 case ICmpInst::ICMP_ULT:
11928 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11929 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11930 return true;
11931 break;
11932 }
11933
11934 return false;
11935}
11936
11937bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11939 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11940 return false;
11941
11942 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11943 // the stack can result in exponential time complexity.
11944 SaveAndRestore Restore(ProvingSplitPredicate, true);
11945
11946 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11947 //
11948 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11949 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11950 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11951 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11952 // use isKnownPredicate later if needed.
11953 return isKnownNonNegative(RHS) &&
11956}
11957
11958bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11959 const SCEV *LHS, const SCEV *RHS) {
11960 // No need to even try if we know the module has no guards.
11961 if (!HasGuards)
11962 return false;
11963
11964 return any_of(*BB, [&](const Instruction &I) {
11965 using namespace llvm::PatternMatch;
11966
11967 Value *Condition;
11969 m_Value(Condition))) &&
11970 isImpliedCond(Pred, LHS, RHS, Condition, false);
11971 });
11972}
11973
11974/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11975/// protected by a conditional between LHS and RHS. This is used to
11976/// to eliminate casts.
11978 CmpPredicate Pred,
11979 const SCEV *LHS,
11980 const SCEV *RHS) {
11981 // Interpret a null as meaning no loop, where there is obviously no guard
11982 // (interprocedural conditions notwithstanding). Do not bother about
11983 // unreachable loops.
11984 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11985 return true;
11986
11987 if (VerifyIR)
11988 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11989 "This cannot be done on broken IR!");
11990
11991
11992 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11993 return true;
11994
11995 BasicBlock *Latch = L->getLoopLatch();
11996 if (!Latch)
11997 return false;
11998
11999 CondBrInst *LoopContinuePredicate =
12001 if (LoopContinuePredicate &&
12002 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
12003 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
12004 return true;
12005
12006 // We don't want more than one activation of the following loops on the stack
12007 // -- that can lead to O(n!) time complexity.
12008 if (WalkingBEDominatingConds)
12009 return false;
12010
12011 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
12012
12013 // See if we can exploit a trip count to prove the predicate.
12014 const auto &BETakenInfo = getBackedgeTakenInfo(L);
12015 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
12016 if (LatchBECount != getCouldNotCompute()) {
12017 // We know that Latch branches back to the loop header exactly
12018 // LatchBECount times. This means the backdege condition at Latch is
12019 // equivalent to "{0,+,1} u< LatchBECount".
12020 Type *Ty = LatchBECount->getType();
12021 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
12022 const SCEV *LoopCounter =
12023 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
12024 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
12025 LatchBECount))
12026 return true;
12027 }
12028
12029 // Check conditions due to any @llvm.assume intrinsics.
12030 for (auto &AssumeVH : AC.assumptions()) {
12031 if (!AssumeVH)
12032 continue;
12033 auto *CI = cast<CallInst>(AssumeVH);
12034 if (!DT.dominates(CI, Latch->getTerminator()))
12035 continue;
12036
12037 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
12038 return true;
12039 }
12040
12041 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
12042 return true;
12043
12044 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
12045 DTN != HeaderDTN; DTN = DTN->getIDom()) {
12046 assert(DTN && "should reach the loop header before reaching the root!");
12047
12048 BasicBlock *BB = DTN->getBlock();
12049 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
12050 return true;
12051
12052 BasicBlock *PBB = BB->getSinglePredecessor();
12053 if (!PBB)
12054 continue;
12055
12057 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
12058 continue;
12059
12060 // If we have an edge `E` within the loop body that dominates the only
12061 // latch, the condition guarding `E` also guards the backedge. This
12062 // reasoning works only for loops with a single latch.
12063 // We're constructively (and conservatively) enumerating edges within the
12064 // loop body that dominate the latch. The dominator tree better agree
12065 // with us on this:
12066 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
12067 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
12068 BB != ContBr->getSuccessor(0)))
12069 return true;
12070 }
12071
12072 return false;
12073}
12074
12076 CmpPredicate Pred,
12077 const SCEV *LHS,
12078 const SCEV *RHS) {
12079 // Do not bother proving facts for unreachable code.
12080 if (!DT.isReachableFromEntry(BB))
12081 return true;
12082 if (VerifyIR)
12083 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
12084 "This cannot be done on broken IR!");
12085
12086 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
12087 // the facts (a >= b && a != b) separately. A typical situation is when the
12088 // non-strict comparison is known from ranges and non-equality is known from
12089 // dominating predicates. If we are proving strict comparison, we always try
12090 // to prove non-equality and non-strict comparison separately.
12091 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
12092 const bool ProvingStrictComparison =
12093 Pred != NonStrictPredicate.dropSameSign();
12094 bool ProvedNonStrictComparison = false;
12095 bool ProvedNonEquality = false;
12096
12097 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
12098 if (!ProvedNonStrictComparison)
12099 ProvedNonStrictComparison = Fn(NonStrictPredicate);
12100 if (!ProvedNonEquality)
12101 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
12102 if (ProvedNonStrictComparison && ProvedNonEquality)
12103 return true;
12104 return false;
12105 };
12106
12107 if (ProvingStrictComparison) {
12108 auto ProofFn = [&](CmpPredicate P) {
12109 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
12110 };
12111 if (SplitAndProve(ProofFn))
12112 return true;
12113 }
12114
12115 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
12116 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
12117 const Instruction *CtxI = &BB->front();
12118 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
12119 return true;
12120 if (ProvingStrictComparison) {
12121 auto ProofFn = [&](CmpPredicate P) {
12122 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
12123 };
12124 if (SplitAndProve(ProofFn))
12125 return true;
12126 }
12127 return false;
12128 };
12129
12130 // Starting at the block's predecessor, climb up the predecessor chain, as long
12131 // as there are predecessors that can be found that have unique successors
12132 // leading to the original block.
12133 const Loop *ContainingLoop = LI.getLoopFor(BB);
12134 const BasicBlock *PredBB;
12135 if (ContainingLoop && ContainingLoop->getHeader() == BB)
12136 PredBB = ContainingLoop->getLoopPredecessor();
12137 else
12138 PredBB = BB->getSinglePredecessor();
12139 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12140 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
12141 const CondBrInst *BlockEntryPredicate =
12142 dyn_cast<CondBrInst>(Pair.first->getTerminator());
12143 if (!BlockEntryPredicate)
12144 continue;
12145
12146 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12147 BlockEntryPredicate->getSuccessor(0) != Pair.second))
12148 return true;
12149 }
12150
12151 // Check conditions due to any @llvm.assume intrinsics.
12152 for (auto &AssumeVH : AC.assumptions()) {
12153 if (!AssumeVH)
12154 continue;
12155 auto *CI = cast<CallInst>(AssumeVH);
12156 if (!DT.dominates(CI, BB))
12157 continue;
12158
12159 if (ProveViaCond(CI->getArgOperand(0), false))
12160 return true;
12161 }
12162
12163 // Check conditions due to any @llvm.experimental.guard intrinsics.
12164 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12165 F.getParent(), Intrinsic::experimental_guard);
12166 if (GuardDecl)
12167 for (const auto *GU : GuardDecl->users())
12168 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12169 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12170 if (ProveViaCond(Guard->getArgOperand(0), false))
12171 return true;
12172 return false;
12173}
12174
12176 const SCEV *LHS,
12177 const SCEV *RHS) {
12178 // Interpret a null as meaning no loop, where there is obviously no guard
12179 // (interprocedural conditions notwithstanding).
12180 if (!L)
12181 return false;
12182
12183 // Both LHS and RHS must be available at loop entry.
12185 "LHS is not available at Loop Entry");
12187 "RHS is not available at Loop Entry");
12188
12189 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12190 return true;
12191
12192 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12193}
12194
12195bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12196 const SCEV *RHS,
12197 const Value *FoundCondValue, bool Inverse,
12198 const Instruction *CtxI) {
12199 // False conditions implies anything. Do not bother analyzing it further.
12200 if (FoundCondValue ==
12201 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12202 return true;
12203
12204 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12205 return false;
12206
12207 llvm::scope_exit ClearOnExit(
12208 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12209
12210 // Recursively handle And and Or conditions.
12211 const Value *Op0, *Op1;
12212 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12213 if (!Inverse)
12214 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12215 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12216 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12217 if (Inverse)
12218 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12219 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12220 }
12221
12222 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12223 if (!ICI) return false;
12224
12225 // Now that we found a conditional branch that dominates the loop or controls
12226 // the loop latch. Check to see if it is the comparison we are looking for.
12227 CmpPredicate FoundPred;
12228 if (Inverse)
12229 FoundPred = ICI->getInverseCmpPredicate();
12230 else
12231 FoundPred = ICI->getCmpPredicate();
12232
12233 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12234 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12235
12236 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12237}
12238
12239bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12240 const SCEV *RHS, CmpPredicate FoundPred,
12241 const SCEV *FoundLHS, const SCEV *FoundRHS,
12242 const Instruction *CtxI) {
12243 // Balance the types.
12244 if (getTypeSizeInBits(LHS->getType()) <
12245 getTypeSizeInBits(FoundLHS->getType())) {
12246 // For unsigned and equality predicates, try to prove that both found
12247 // operands fit into narrow unsigned range. If so, try to prove facts in
12248 // narrow types.
12249 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12250 !FoundRHS->getType()->isPointerTy()) {
12251 auto *NarrowType = LHS->getType();
12252 auto *WideType = FoundLHS->getType();
12253 auto BitWidth = getTypeSizeInBits(NarrowType);
12254 const SCEV *MaxValue = getZeroExtendExpr(
12256 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12257 MaxValue) &&
12258 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12259 MaxValue)) {
12260 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12261 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12262 // We cannot preserve samesign after truncation.
12263 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12264 TruncFoundLHS, TruncFoundRHS, CtxI))
12265 return true;
12266 }
12267 }
12268
12269 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12270 return false;
12271 if (CmpInst::isSigned(Pred)) {
12272 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12273 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12274 } else {
12275 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12276 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12277 }
12278 } else if (getTypeSizeInBits(LHS->getType()) >
12279 getTypeSizeInBits(FoundLHS->getType())) {
12280 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12281 return false;
12282 if (CmpInst::isSigned(FoundPred)) {
12283 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12284 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12285 } else {
12286 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12287 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12288 }
12289 }
12290 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12291 FoundRHS, CtxI);
12292}
12293
12294bool ScalarEvolution::isImpliedCondBalancedTypes(
12295 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12296 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12298 getTypeSizeInBits(FoundLHS->getType()) &&
12299 "Types should be balanced!");
12300 // Canonicalize the query to match the way instcombine will have
12301 // canonicalized the comparison.
12302 if (SimplifyICmpOperands(Pred, LHS, RHS))
12303 if (LHS == RHS)
12304 return CmpInst::isTrueWhenEqual(Pred);
12305 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12306 if (FoundLHS == FoundRHS)
12307 return CmpInst::isFalseWhenEqual(FoundPred);
12308
12309 // Check to see if we can make the LHS or RHS match.
12310 if (LHS == FoundRHS || RHS == FoundLHS) {
12311 if (isa<SCEVConstant>(RHS)) {
12312 std::swap(FoundLHS, FoundRHS);
12313 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12314 } else {
12315 std::swap(LHS, RHS);
12317 }
12318 }
12319
12320 // Check whether the found predicate is the same as the desired predicate.
12321 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12322 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12323
12324 // Check whether swapping the found predicate makes it the same as the
12325 // desired predicate.
12326 if (auto P = CmpPredicate::getMatching(
12327 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12328 // We can write the implication
12329 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12330 // using one of the following ways:
12331 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12332 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12333 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
12334 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
12335 // Forms 1. and 2. require swapping the operands of one condition. Don't
12336 // do this if it would break canonical constant/addrec ordering.
12338 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12339 LHS, FoundLHS, FoundRHS, CtxI);
12340 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12341 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12342
12343 // There's no clear preference between forms 3. and 4., try both. Avoid
12344 // forming getNotSCEV of pointer values as the resulting subtract is
12345 // not legal.
12346 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
12347 isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P),
12348 getNotSCEV(LHS), getNotSCEV(RHS), FoundLHS,
12349 FoundRHS, CtxI))
12350 return true;
12351
12352 if (!FoundLHS->getType()->isPointerTy() &&
12353 !FoundRHS->getType()->isPointerTy() &&
12354 isImpliedCondOperands(*P, LHS, RHS, getNotSCEV(FoundLHS),
12355 getNotSCEV(FoundRHS), CtxI))
12356 return true;
12357
12358 return false;
12359 }
12360
12361 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12363 assert(P1 != P2 && "Handled earlier!");
12364 return CmpInst::isRelational(P2) &&
12366 };
12367 if (IsSignFlippedPredicate(Pred, FoundPred)) {
12368 // Unsigned comparison is the same as signed comparison when both the
12369 // operands are non-negative or negative.
12370 if (haveSameSign(FoundLHS, FoundRHS))
12371 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12372 // Create local copies that we can freely swap and canonicalize our
12373 // conditions to "le/lt".
12374 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
12375 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
12376 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
12377 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
12378 CanonicalPred = ICmpInst::getSwappedCmpPredicate(CanonicalPred);
12379 CanonicalFoundPred = ICmpInst::getSwappedCmpPredicate(CanonicalFoundPred);
12380 std::swap(CanonicalLHS, CanonicalRHS);
12381 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
12382 }
12383 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
12384 "Must be!");
12385 assert((ICmpInst::isLT(CanonicalFoundPred) ||
12386 ICmpInst::isLE(CanonicalFoundPred)) &&
12387 "Must be!");
12388 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
12389 // Use implication:
12390 // x <u y && y >=s 0 --> x <s y.
12391 // If we can prove the left part, the right part is also proven.
12392 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12393 CanonicalRHS, CanonicalFoundLHS,
12394 CanonicalFoundRHS);
12395 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
12396 // Use implication:
12397 // x <s y && y <s 0 --> x <u y.
12398 // If we can prove the left part, the right part is also proven.
12399 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12400 CanonicalRHS, CanonicalFoundLHS,
12401 CanonicalFoundRHS);
12402 }
12403
12404 // Check if we can make progress by sharpening ranges.
12405 if (FoundPred == ICmpInst::ICMP_NE &&
12406 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12407
12408 const SCEVConstant *C = nullptr;
12409 const SCEV *V = nullptr;
12410
12411 if (isa<SCEVConstant>(FoundLHS)) {
12412 C = cast<SCEVConstant>(FoundLHS);
12413 V = FoundRHS;
12414 } else {
12415 C = cast<SCEVConstant>(FoundRHS);
12416 V = FoundLHS;
12417 }
12418
12419 // The guarding predicate tells us that C != V. If the known range
12420 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12421 // range we consider has to correspond to same signedness as the
12422 // predicate we're interested in folding.
12423
12424 APInt Min = ICmpInst::isSigned(Pred) ?
12426
12427 if (Min == C->getAPInt()) {
12428 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12429 // This is true even if (Min + 1) wraps around -- in case of
12430 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12431
12432 APInt SharperMin = Min + 1;
12433
12434 switch (Pred) {
12435 case ICmpInst::ICMP_SGE:
12436 case ICmpInst::ICMP_UGE:
12437 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12438 // RHS, we're done.
12439 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12440 CtxI))
12441 return true;
12442 [[fallthrough]];
12443
12444 case ICmpInst::ICMP_SGT:
12445 case ICmpInst::ICMP_UGT:
12446 // We know from the range information that (V `Pred` Min ||
12447 // V == Min). We know from the guarding condition that !(V
12448 // == Min). This gives us
12449 //
12450 // V `Pred` Min || V == Min && !(V == Min)
12451 // => V `Pred` Min
12452 //
12453 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12454
12455 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12456 return true;
12457 break;
12458
12459 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12460 case ICmpInst::ICMP_SLE:
12461 case ICmpInst::ICMP_ULE:
12462 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12463 LHS, V, getConstant(SharperMin), CtxI))
12464 return true;
12465 [[fallthrough]];
12466
12467 case ICmpInst::ICMP_SLT:
12468 case ICmpInst::ICMP_ULT:
12469 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12470 LHS, V, getConstant(Min), CtxI))
12471 return true;
12472 break;
12473
12474 default:
12475 // No change
12476 break;
12477 }
12478 }
12479 }
12480
12481 // Check whether the actual condition is beyond sufficient.
12482 if (FoundPred == ICmpInst::ICMP_EQ)
12483 if (ICmpInst::isTrueWhenEqual(Pred))
12484 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12485 return true;
12486 if (Pred == ICmpInst::ICMP_NE)
12487 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12488 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12489 return true;
12490
12491 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12492 return true;
12493
12494 // Otherwise assume the worst.
12495 return false;
12496}
12497
12498bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12499 SCEV::NoWrapFlags &Flags) {
12500 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12501 return false;
12502
12503 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12504 return true;
12505}
12506
12507std::optional<APInt>
12509 // We avoid subtracting expressions here because this function is usually
12510 // fairly deep in the call stack (i.e. is called many times).
12511
12512 unsigned BW = getTypeSizeInBits(More->getType());
12513 APInt Diff(BW, 0);
12514 APInt DiffMul(BW, 1);
12515 // Try various simplifications to reduce the difference to a constant. Limit
12516 // the number of allowed simplifications to keep compile-time low.
12517 for (unsigned I = 0; I < 8; ++I) {
12518 if (More == Less)
12519 return Diff;
12520
12521 // Reduce addrecs with identical steps to their start value.
12523 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12524 const auto *MAR = cast<SCEVAddRecExpr>(More);
12525
12526 if (LAR->getLoop() != MAR->getLoop())
12527 return std::nullopt;
12528
12529 // We look at affine expressions only; not for correctness but to keep
12530 // getStepRecurrence cheap.
12531 if (!LAR->isAffine() || !MAR->isAffine())
12532 return std::nullopt;
12533
12534 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12535 return std::nullopt;
12536
12537 Less = LAR->getStart();
12538 More = MAR->getStart();
12539 continue;
12540 }
12541
12542 // Try to match a common constant multiply.
12543 auto MatchConstMul =
12544 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12545 const APInt *C;
12546 const SCEV *Op;
12547 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12548 return {{Op, *C}};
12549 return std::nullopt;
12550 };
12551 if (auto MatchedMore = MatchConstMul(More)) {
12552 if (auto MatchedLess = MatchConstMul(Less)) {
12553 if (MatchedMore->second == MatchedLess->second) {
12554 More = MatchedMore->first;
12555 Less = MatchedLess->first;
12556 DiffMul *= MatchedMore->second;
12557 continue;
12558 }
12559 }
12560 }
12561
12562 // Try to cancel out common factors in two add expressions.
12564 auto Add = [&](const SCEV *S, int Mul) {
12565 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12566 if (Mul == 1) {
12567 Diff += C->getAPInt() * DiffMul;
12568 } else {
12569 assert(Mul == -1);
12570 Diff -= C->getAPInt() * DiffMul;
12571 }
12572 } else
12573 Multiplicity[S] += Mul;
12574 };
12575 auto Decompose = [&](const SCEV *S, int Mul) {
12576 if (isa<SCEVAddExpr>(S)) {
12577 for (const SCEV *Op : S->operands())
12578 Add(Op, Mul);
12579 } else
12580 Add(S, Mul);
12581 };
12582 Decompose(More, 1);
12583 Decompose(Less, -1);
12584
12585 // Check whether all the non-constants cancel out, or reduce to new
12586 // More/Less values.
12587 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12588 for (const auto &[S, Mul] : Multiplicity) {
12589 if (Mul == 0)
12590 continue;
12591 if (Mul == 1) {
12592 if (NewMore)
12593 return std::nullopt;
12594 NewMore = S;
12595 } else if (Mul == -1) {
12596 if (NewLess)
12597 return std::nullopt;
12598 NewLess = S;
12599 } else
12600 return std::nullopt;
12601 }
12602
12603 // Values stayed the same, no point in trying further.
12604 if (NewMore == More || NewLess == Less)
12605 return std::nullopt;
12606
12607 More = NewMore;
12608 Less = NewLess;
12609
12610 // Reduced to constant.
12611 if (!More && !Less)
12612 return Diff;
12613
12614 // Left with variable on only one side, bail out.
12615 if (!More || !Less)
12616 return std::nullopt;
12617 }
12618
12619 // Did not reduce to constant.
12620 return std::nullopt;
12621}
12622
12623bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12624 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12625 const SCEV *FoundRHS, const Instruction *CtxI) {
12626 // Try to recognize the following pattern:
12627 //
12628 // FoundRHS = ...
12629 // ...
12630 // loop:
12631 // FoundLHS = {Start,+,W}
12632 // context_bb: // Basic block from the same loop
12633 // known(Pred, FoundLHS, FoundRHS)
12634 //
12635 // If some predicate is known in the context of a loop, it is also known on
12636 // each iteration of this loop, including the first iteration. Therefore, in
12637 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12638 // prove the original pred using this fact.
12639 if (!CtxI)
12640 return false;
12641 const BasicBlock *ContextBB = CtxI->getParent();
12642 // Make sure AR varies in the context block.
12643 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12644 const Loop *L = AR->getLoop();
12645 const auto *Latch = L->getLoopLatch();
12646 // Make sure that context belongs to the loop and executes on 1st iteration
12647 // (if it ever executes at all).
12648 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12649 return false;
12650 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12651 return false;
12652 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12653 }
12654
12655 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12656 const Loop *L = AR->getLoop();
12657 const auto *Latch = L->getLoopLatch();
12658 // Make sure that context belongs to the loop and executes on 1st iteration
12659 // (if it ever executes at all).
12660 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12661 return false;
12662 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12663 return false;
12664 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12665 }
12666
12667 return false;
12668}
12669
12670bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12671 const SCEV *LHS,
12672 const SCEV *RHS,
12673 const SCEV *FoundLHS,
12674 const SCEV *FoundRHS) {
12675 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12676 return false;
12677
12678 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12679 if (!AddRecLHS)
12680 return false;
12681
12682 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12683 if (!AddRecFoundLHS)
12684 return false;
12685
12686 // We'd like to let SCEV reason about control dependencies, so we constrain
12687 // both the inequalities to be about add recurrences on the same loop. This
12688 // way we can use isLoopEntryGuardedByCond later.
12689
12690 const Loop *L = AddRecFoundLHS->getLoop();
12691 if (L != AddRecLHS->getLoop())
12692 return false;
12693
12694 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12695 //
12696 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12697 // ... (2)
12698 //
12699 // Informal proof for (2), assuming (1) [*]:
12700 //
12701 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12702 //
12703 // Then
12704 //
12705 // FoundLHS s< FoundRHS s< INT_MIN - C
12706 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12707 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12708 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12709 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12710 // <=> FoundLHS + C s< FoundRHS + C
12711 //
12712 // [*]: (1) can be proved by ruling out overflow.
12713 //
12714 // [**]: This can be proved by analyzing all the four possibilities:
12715 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12716 // (A s>= 0, B s>= 0).
12717 //
12718 // Note:
12719 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12720 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12721 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12722 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12723 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12724 // C)".
12725
12726 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12727 if (!LDiff)
12728 return false;
12729 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12730 if (!RDiff || *LDiff != *RDiff)
12731 return false;
12732
12733 if (LDiff->isMinValue())
12734 return true;
12735
12736 APInt FoundRHSLimit;
12737
12738 if (Pred == CmpInst::ICMP_ULT) {
12739 FoundRHSLimit = -(*RDiff);
12740 } else {
12741 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12742 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12743 }
12744
12745 // Try to prove (1) or (2), as needed.
12746 return isAvailableAtLoopEntry(FoundRHS, L) &&
12747 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12748 getConstant(FoundRHSLimit));
12749}
12750
12751bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12752 const SCEV *RHS, const SCEV *FoundLHS,
12753 const SCEV *FoundRHS, unsigned Depth) {
12754 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12755
12756 llvm::scope_exit ClearOnExit([&]() {
12757 if (LPhi) {
12758 bool Erased = PendingMerges.erase(LPhi);
12759 assert(Erased && "Failed to erase LPhi!");
12760 (void)Erased;
12761 }
12762 if (RPhi) {
12763 bool Erased = PendingMerges.erase(RPhi);
12764 assert(Erased && "Failed to erase RPhi!");
12765 (void)Erased;
12766 }
12767 });
12768
12769 // Find respective Phis and check that they are not being pending.
12770 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12771 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12772 if (!PendingMerges.insert(Phi).second)
12773 return false;
12774 LPhi = Phi;
12775 }
12776 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12777 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12778 // If we detect a loop of Phi nodes being processed by this method, for
12779 // example:
12780 //
12781 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12782 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12783 //
12784 // we don't want to deal with a case that complex, so return conservative
12785 // answer false.
12786 if (!PendingMerges.insert(Phi).second)
12787 return false;
12788 RPhi = Phi;
12789 }
12790
12791 // If none of LHS, RHS is a Phi, nothing to do here.
12792 if (!LPhi && !RPhi)
12793 return false;
12794
12795 // If there is a SCEVUnknown Phi we are interested in, make it left.
12796 if (!LPhi) {
12797 std::swap(LHS, RHS);
12798 std::swap(FoundLHS, FoundRHS);
12799 std::swap(LPhi, RPhi);
12801 }
12802
12803 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12804 const BasicBlock *LBB = LPhi->getParent();
12805 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12806
12807 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12808 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12809 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12810 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12811 };
12812
12813 if (RPhi && RPhi->getParent() == LBB) {
12814 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12815 // If we compare two Phis from the same block, and for each entry block
12816 // the predicate is true for incoming values from this block, then the
12817 // predicate is also true for the Phis.
12818 for (const BasicBlock *IncBB : predecessors(LBB)) {
12819 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12820 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12821 if (!ProvedEasily(L, R))
12822 return false;
12823 }
12824 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12825 // Case two: RHS is also a Phi from the same basic block, and it is an
12826 // AddRec. It means that there is a loop which has both AddRec and Unknown
12827 // PHIs, for it we can compare incoming values of AddRec from above the loop
12828 // and latch with their respective incoming values of LPhi.
12829 // TODO: Generalize to handle loops with many inputs in a header.
12830 if (LPhi->getNumIncomingValues() != 2) return false;
12831
12832 auto *RLoop = RAR->getLoop();
12833 auto *Predecessor = RLoop->getLoopPredecessor();
12834 assert(Predecessor && "Loop with AddRec with no predecessor?");
12835 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12836 if (!ProvedEasily(L1, RAR->getStart()))
12837 return false;
12838 auto *Latch = RLoop->getLoopLatch();
12839 assert(Latch && "Loop with AddRec with no latch?");
12840 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12841 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12842 return false;
12843 } else {
12844 // In all other cases go over inputs of LHS and compare each of them to RHS,
12845 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12846 // At this point RHS is either a non-Phi, or it is a Phi from some block
12847 // different from LBB.
12848 for (const BasicBlock *IncBB : predecessors(LBB)) {
12849 // Check that RHS is available in this block.
12850 if (!dominates(RHS, IncBB))
12851 return false;
12852 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12853 // Make sure L does not refer to a value from a potentially previous
12854 // iteration of a loop.
12855 if (!properlyDominates(L, LBB))
12856 return false;
12857 // Addrecs are considered to properly dominate their loop, so are missed
12858 // by the previous check. Discard any values that have computable
12859 // evolution in this loop.
12860 if (auto *Loop = LI.getLoopFor(LBB))
12861 if (hasComputableLoopEvolution(L, Loop))
12862 return false;
12863 if (!ProvedEasily(L, RHS))
12864 return false;
12865 }
12866 }
12867 return true;
12868}
12869
12870bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12871 const SCEV *LHS,
12872 const SCEV *RHS,
12873 const SCEV *FoundLHS,
12874 const SCEV *FoundRHS) {
12875 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12876 // sure that we are dealing with same LHS.
12877 if (RHS == FoundRHS) {
12878 std::swap(LHS, RHS);
12879 std::swap(FoundLHS, FoundRHS);
12881 }
12882 if (LHS != FoundLHS)
12883 return false;
12884
12885 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12886 if (!SUFoundRHS)
12887 return false;
12888
12889 Value *Shiftee, *ShiftValue;
12890
12891 using namespace PatternMatch;
12892 if (match(SUFoundRHS->getValue(),
12893 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12894 auto *ShifteeS = getSCEV(Shiftee);
12895 // Prove one of the following:
12896 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12897 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12898 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12899 // ---> LHS <s RHS
12900 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12901 // ---> LHS <=s RHS
12902 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12903 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12904 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12905 if (isKnownNonNegative(ShifteeS))
12906 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12907 }
12908
12909 return false;
12910}
12911
12912bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12913 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12914 const SCEV *FoundRHS) {
12915 // Only valid for equality predicates: (A == B) implies (C == D) when
12916 // the SCEV difference A - B equals C - D (they check the same
12917 // underlying relationship at every iteration).
12918 if (!ICmpInst::isEquality(Pred))
12919 return false;
12920
12921 // Restrict to cases involving loop recurrences - that's where this
12922 // pattern arises (correlated IV comparisons). This avoids calling
12923 // getMinusSCEV on arbitrary non-loop expressions.
12925 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12926 return false;
12927
12928 // AddRecs from different loops can never produce matching differences.
12929 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12930 if (!QueryAddRec)
12931 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12932 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12933 if (!FoundAddRec)
12934 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12935 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12936 return false;
12937
12938 // If the strides differ, the differences can never match.
12939 if (QueryAddRec->getStepRecurrence(*this) !=
12940 FoundAddRec->getStepRecurrence(*this))
12941 return false;
12942
12943 // Compute differences. For pointer-typed operands sharing the same base,
12944 // getMinusSCEV strips the common base and returns an integer SCEV.
12945 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12946 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12947 if (isa<SCEVCouldNotCompute>(FoundDiff))
12948 return false;
12949
12950 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12951 if (isa<SCEVCouldNotCompute>(Diff))
12952 return false;
12953
12954 return Diff == FoundDiff;
12955}
12956
12957bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12958 const SCEV *RHS,
12959 const SCEV *FoundLHS,
12960 const SCEV *FoundRHS,
12961 const Instruction *CtxI) {
12962 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12963 FoundRHS) ||
12964 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12965 FoundRHS) ||
12966 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12967 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12968 CtxI) ||
12969 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12970 FoundRHS) ||
12971 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12972}
12973
12974/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12975template <typename MinMaxExprType>
12976static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12977 const SCEV *Candidate) {
12978 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12979 if (!MinMaxExpr)
12980 return false;
12981
12982 return is_contained(MinMaxExpr->operands(), Candidate);
12983}
12984
12986 CmpPredicate Pred, const SCEV *LHS,
12987 const SCEV *RHS) {
12988 // If both sides are affine addrecs for the same loop, with equal
12989 // steps, and we know the recurrences don't wrap, then we only
12990 // need to check the predicate on the starting values.
12991
12992 if (!ICmpInst::isRelational(Pred))
12993 return false;
12994
12995 const SCEV *LStart, *RStart, *Step;
12996 const Loop *L;
12997 if (!match(LHS,
12998 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
13000 m_SpecificLoop(L))))
13001 return false;
13006 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
13007 return false;
13008
13009 return SE.isKnownPredicate(Pred, LStart, RStart);
13010}
13011
13012/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
13013/// expression?
13015 const SCEV *LHS, const SCEV *RHS) {
13016 switch (Pred) {
13017 default:
13018 return false;
13019
13020 case ICmpInst::ICMP_SGE:
13021 std::swap(LHS, RHS);
13022 [[fallthrough]];
13023 case ICmpInst::ICMP_SLE:
13024 return
13025 // min(A, ...) <= A
13027 // A <= max(A, ...)
13029
13030 case ICmpInst::ICMP_UGE:
13031 std::swap(LHS, RHS);
13032 [[fallthrough]];
13033 case ICmpInst::ICMP_ULE:
13034 return
13035 // min(A, ...) <= A
13036 // FIXME: what about umin_seq?
13038 // A <= max(A, ...)
13040
13041 case ICmpInst::ICMP_UGT:
13042 std::swap(LHS, RHS);
13043 [[fallthrough]];
13044 case ICmpInst::ICMP_ULT:
13045 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
13046 // umin(Ops) u< RHS.
13047 //
13048 // Use computeConstantDifference instead of the more powerful
13049 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
13050 // is called from isKnownViaNonRecursiveReasoning, so recursing into
13051 // the full predicate prover would be expensive.
13052 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
13053 for (SCEVUse Op : Min->operands()) {
13054 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
13055 // When Op and RHS share a common base differing by a
13056 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
13057 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
13058 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
13059 return true;
13060 }
13061 }
13062 return false;
13063 }
13064
13065 llvm_unreachable("covered switch fell through?!");
13066}
13067
13068bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
13069 const SCEV *RHS,
13070 const SCEV *FoundLHS,
13071 const SCEV *FoundRHS,
13072 unsigned Depth) {
13075 "LHS and RHS have different sizes?");
13076 assert(getTypeSizeInBits(FoundLHS->getType()) ==
13077 getTypeSizeInBits(FoundRHS->getType()) &&
13078 "FoundLHS and FoundRHS have different sizes?");
13079 // We want to avoid hurting the compile time with analysis of too big trees.
13081 return false;
13082
13083 // We only want to work with GT comparison so far.
13084 if (ICmpInst::isLT(Pred)) {
13086 std::swap(LHS, RHS);
13087 std::swap(FoundLHS, FoundRHS);
13088 }
13089
13091
13092 // For unsigned, try to reduce it to corresponding signed comparison.
13093 if (P == ICmpInst::ICMP_UGT)
13094 // We can replace unsigned predicate with its signed counterpart if all
13095 // involved values are non-negative.
13096 // TODO: We could have better support for unsigned.
13097 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
13098 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
13099 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
13100 // use this fact to prove that LHS and RHS are non-negative.
13101 const SCEV *MinusOne = getMinusOne(LHS->getType());
13102 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
13103 FoundRHS) &&
13104 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
13105 FoundRHS))
13107 }
13108
13109 if (P != ICmpInst::ICMP_SGT)
13110 return false;
13111
13112 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13113 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
13114 return Ext->getOperand();
13115 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13116 // the constant in some cases.
13117 return S;
13118 };
13119
13120 // Acquire values from extensions.
13121 auto *OrigLHS = LHS;
13122 auto *OrigFoundLHS = FoundLHS;
13123 LHS = GetOpFromSExt(LHS);
13124 FoundLHS = GetOpFromSExt(FoundLHS);
13125
13126 // Is the SGT predicate can be proved trivially or using the found context.
13127 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13128 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13129 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13130 FoundRHS, Depth + 1);
13131 };
13132
13133 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
13134 // We want to avoid creation of any new non-constant SCEV. Since we are
13135 // going to compare the operands to RHS, we should be certain that we don't
13136 // need any size extensions for this. So let's decline all cases when the
13137 // sizes of types of LHS and RHS do not match.
13138 // TODO: Maybe try to get RHS from sext to catch more cases?
13140 return false;
13141
13142 // Should not overflow.
13143 if (!LHSAddExpr->hasNoSignedWrap())
13144 return false;
13145
13146 SCEVUse LL = LHSAddExpr->getOperand(0);
13147 SCEVUse LR = LHSAddExpr->getOperand(1);
13148 auto *MinusOne = getMinusOne(RHS->getType());
13149
13150 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13151 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13152 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13153 };
13154 // Try to prove the following rule:
13155 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13156 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13157 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13158 return true;
13159 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13160 Value *LL, *LR;
13161 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13162
13163 using namespace llvm::PatternMatch;
13164
13165 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13166 // Rules for division.
13167 // We are going to perform some comparisons with Denominator and its
13168 // derivative expressions. In general case, creating a SCEV for it may
13169 // lead to a complex analysis of the entire graph, and in particular it
13170 // can request trip count recalculation for the same loop. This would
13171 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13172 // this, we only want to create SCEVs that are constants in this section.
13173 // So we bail if Denominator is not a constant.
13174 if (!isa<ConstantInt>(LR))
13175 return false;
13176
13177 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13178
13179 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13180 // then a SCEV for the numerator already exists and matches with FoundLHS.
13181 auto *Numerator = getExistingSCEV(LL);
13182 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13183 return false;
13184
13185 // Make sure that the numerator matches with FoundLHS and the denominator
13186 // is positive.
13187 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13188 return false;
13189
13190 auto *DTy = Denominator->getType();
13191 auto *FRHSTy = FoundRHS->getType();
13192 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13193 // One of types is a pointer and another one is not. We cannot extend
13194 // them properly to a wider type, so let us just reject this case.
13195 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13196 // to avoid this check.
13197 return false;
13198
13199 // Given that:
13200 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13201 auto *WTy = getWiderType(DTy, FRHSTy);
13202 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13203 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13204
13205 // Try to prove the following rule:
13206 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13207 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13208 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13209 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13210 if (isKnownNonPositive(RHS) &&
13211 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13212 return true;
13213
13214 // Try to prove the following rule:
13215 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13216 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13217 // If we divide it by Denominator > 2, then:
13218 // 1. If FoundLHS is negative, then the result is 0.
13219 // 2. If FoundLHS is non-negative, then the result is non-negative.
13220 // Anyways, the result is non-negative.
13221 auto *MinusOne = getMinusOne(WTy);
13222 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13223 if (isKnownNegative(RHS) &&
13224 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13225 return true;
13226 }
13227 }
13228
13229 // If our expression contained SCEVUnknown Phis, and we split it down and now
13230 // need to prove something for them, try to prove the predicate for every
13231 // possible incoming values of those Phis.
13232 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13233 return true;
13234
13235 return false;
13236}
13237
13239 const SCEV *RHS) {
13240 // zext x u<= sext x, sext x s<= zext x
13241 const SCEV *Op;
13242 switch (Pred) {
13243 case ICmpInst::ICMP_SGE:
13244 std::swap(LHS, RHS);
13245 [[fallthrough]];
13246 case ICmpInst::ICMP_SLE: {
13247 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13248 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13250 }
13251 case ICmpInst::ICMP_UGE:
13252 std::swap(LHS, RHS);
13253 [[fallthrough]];
13254 case ICmpInst::ICMP_ULE: {
13255 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13256 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13258 }
13259 default:
13260 return false;
13261 };
13262 llvm_unreachable("unhandled case");
13263}
13264
13265bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13266 SCEVUse LHS,
13267 SCEVUse RHS) {
13268 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13269 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13270 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13271 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13272 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13273}
13274
13275bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13276 const SCEV *LHS,
13277 const SCEV *RHS,
13278 const SCEV *FoundLHS,
13279 const SCEV *FoundRHS) {
13280 switch (Pred) {
13281 default:
13282 llvm_unreachable("Unexpected CmpPredicate value!");
13283 case ICmpInst::ICMP_EQ:
13284 case ICmpInst::ICMP_NE:
13285 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13286 return true;
13287 break;
13288 case ICmpInst::ICMP_SLT:
13289 case ICmpInst::ICMP_SLE:
13290 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
13291 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
13292 return true;
13293 break;
13294 case ICmpInst::ICMP_SGT:
13295 case ICmpInst::ICMP_SGE:
13296 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
13297 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
13298 return true;
13299 break;
13300 case ICmpInst::ICMP_ULT:
13301 case ICmpInst::ICMP_ULE:
13302 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
13303 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
13304 return true;
13305 break;
13306 case ICmpInst::ICMP_UGT:
13307 case ICmpInst::ICMP_UGE:
13308 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
13309 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
13310 return true;
13311 break;
13312 }
13313
13314 // Maybe it can be proved via operations?
13315 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13316 return true;
13317
13318 return false;
13319}
13320
13321bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13322 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13323 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13324 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13325 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13326 // reduce the compile time impact of this optimization.
13327 return false;
13328
13329 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13330 if (!Addend)
13331 return false;
13332
13333 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13334
13335 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13336 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13337 ConstantRange FoundLHSRange =
13338 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13339
13340 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13341 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13342
13343 // We can also compute the range of values for `LHS` that satisfy the
13344 // consequent, "`LHS` `Pred` `RHS`":
13345 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13346 // The antecedent implies the consequent if every value of `LHS` that
13347 // satisfies the antecedent also satisfies the consequent.
13348 return LHSRange.icmp(Pred, ConstRHS);
13349}
13350
13351bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13352 bool IsSigned) {
13353 assert(isKnownPositive(Stride) && "Positive stride expected!");
13354
13355 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13356 const SCEV *One = getOne(Stride->getType());
13357
13358 if (IsSigned) {
13359 APInt MaxRHS = getSignedRangeMax(RHS);
13360 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13361 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13362
13363 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13364 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13365 }
13366
13367 APInt MaxRHS = getUnsignedRangeMax(RHS);
13368 APInt MaxValue = APInt::getMaxValue(BitWidth);
13369 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13370
13371 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13372 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13373}
13374
13375bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
13376 bool IsSigned) {
13377
13378 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13379 const SCEV *One = getOne(Stride->getType());
13380
13381 if (IsSigned) {
13382 APInt MinRHS = getSignedRangeMin(RHS);
13383 APInt MinValue = APInt::getSignedMinValue(BitWidth);
13384 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13385
13386 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
13387 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
13388 }
13389
13390 APInt MinRHS = getUnsignedRangeMin(RHS);
13391 APInt MinValue = APInt::getMinValue(BitWidth);
13392 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13393
13394 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
13395 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
13396}
13397
13399 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13400 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13401 // expression fixes the case of N=0.
13402 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13403 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13404 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13405}
13406
13407const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
13408 const SCEV *Stride,
13409 const SCEV *End,
13410 unsigned BitWidth,
13411 bool IsSigned) {
13412 // The logic in this function assumes we can represent a positive stride.
13413 // If we can't, the backedge-taken count must be zero.
13414 if (IsSigned && BitWidth == 1)
13415 return getZero(Stride->getType());
13416
13417 // This code below only been closely audited for negative strides in the
13418 // unsigned comparison case, it may be correct for signed comparison, but
13419 // that needs to be established.
13420 if (IsSigned && isKnownNegative(Stride))
13421 return getCouldNotCompute();
13422
13423 // Calculate the maximum backedge count based on the range of values
13424 // permitted by Start, End, and Stride.
13425 APInt MinStart =
13426 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
13427
13428 APInt MinStride =
13429 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13430
13431 // We assume either the stride is positive, or the backedge-taken count
13432 // is zero. So force StrideForMaxBECount to be at least one.
13433 APInt One(BitWidth, 1);
13434 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13435 : APIntOps::umax(One, MinStride);
13436
13437 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13438 : APInt::getMaxValue(BitWidth);
13439 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13440
13441 // Although End can be a MAX expression we estimate MaxEnd considering only
13442 // the case End = RHS of the loop termination condition. This is safe because
13443 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13444 // taken count.
13445 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
13446 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
13447
13448 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13449 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13450 : APIntOps::umax(MaxEnd, MinStart);
13451
13452 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
13453 getConstant(StrideForMaxBECount) /* Step */);
13454}
13455
13457ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13458 const Loop *L, bool IsSigned,
13459 bool ControlsOnlyExit, bool AllowPredicates) {
13461
13463 bool PredicatedIV = false;
13464 if (!IV) {
13465 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13466 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13467 if (AR && AR->getLoop() == L && AR->isAffine()) {
13468 auto canProveNUW = [&]() {
13469 // We can use the comparison to infer no-wrap flags only if it fully
13470 // controls the loop exit.
13471 if (!ControlsOnlyExit)
13472 return false;
13473
13474 if (!isLoopInvariant(RHS, L))
13475 return false;
13476
13477 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13478 // We need the sequence defined by AR to strictly increase in the
13479 // unsigned integer domain for the logic below to hold.
13480 return false;
13481
13482 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13483 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13484 // If RHS <=u Limit, then there must exist a value V in the sequence
13485 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13486 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13487 // overflow occurs. This limit also implies that a signed comparison
13488 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13489 // the high bits on both sides must be zero.
13490 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13491 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13492 Limit = Limit.zext(OuterBitWidth);
13493 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
13494 };
13495 auto Flags = AR->getNoWrapFlags();
13496 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13497 Flags = setFlags(Flags, SCEV::FlagNUW);
13498
13499 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13500 if (AR->hasNoUnsignedWrap()) {
13501 // Emulate what getZeroExtendExpr would have done during construction
13502 // if we'd been able to infer the fact just above at that time.
13503 const SCEV *Step = AR->getStepRecurrence(*this);
13504 Type *Ty = ZExt->getType();
13505 auto *S = getAddRecExpr(
13507 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13509 }
13510 }
13511 }
13512 }
13513
13514
13515 if (!IV && AllowPredicates) {
13516 // Try to make this an AddRec using runtime tests, in the first X
13517 // iterations of this loop, where X is the SCEV expression found by the
13518 // algorithm below.
13519 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13520 PredicatedIV = true;
13521 }
13522
13523 // Avoid weird loops
13524 if (!IV || IV->getLoop() != L || !IV->isAffine())
13525 return getCouldNotCompute();
13526
13527 // A precondition of this method is that the condition being analyzed
13528 // reaches an exiting branch which dominates the latch. Given that, we can
13529 // assume that an increment which violates the nowrap specification and
13530 // produces poison must cause undefined behavior when the resulting poison
13531 // value is branched upon and thus we can conclude that the backedge is
13532 // taken no more often than would be required to produce that poison value.
13533 // Note that a well defined loop can exit on the iteration which violates
13534 // the nowrap specification if there is another exit (either explicit or
13535 // implicit/exceptional) which causes the loop to execute before the
13536 // exiting instruction we're analyzing would trigger UB.
13537 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13538 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13540
13541 const SCEV *Stride = IV->getStepRecurrence(*this);
13542
13543 bool PositiveStride = isKnownPositive(Stride);
13544
13545 // Avoid negative or zero stride values.
13546 if (!PositiveStride) {
13547 // We can compute the correct backedge taken count for loops with unknown
13548 // strides if we can prove that the loop is not an infinite loop with side
13549 // effects. Here's the loop structure we are trying to handle -
13550 //
13551 // i = start
13552 // do {
13553 // A[i] = i;
13554 // i += s;
13555 // } while (i < end);
13556 //
13557 // The backedge taken count for such loops is evaluated as -
13558 // (max(end, start + stride) - start - 1) /u stride
13559 //
13560 // The additional preconditions that we need to check to prove correctness
13561 // of the above formula is as follows -
13562 //
13563 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13564 // NoWrap flag).
13565 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13566 // no side effects within the loop)
13567 // c) loop has a single static exit (with no abnormal exits)
13568 //
13569 // Precondition a) implies that if the stride is negative, this is a single
13570 // trip loop. The backedge taken count formula reduces to zero in this case.
13571 //
13572 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13573 // then a zero stride means the backedge can't be taken without executing
13574 // undefined behavior.
13575 //
13576 // The positive stride case is the same as isKnownPositive(Stride) returning
13577 // true (original behavior of the function).
13578 //
13579 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
13581 return getCouldNotCompute();
13582
13583 if (!isKnownNonZero(Stride)) {
13584 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13585 // if it might eventually be greater than start and if so, on which
13586 // iteration. We can't even produce a useful upper bound.
13587 if (!isLoopInvariant(RHS, L))
13588 return getCouldNotCompute();
13589
13590 // We allow a potentially zero stride, but we need to divide by stride
13591 // below. Since the loop can't be infinite and this check must control
13592 // the sole exit, we can infer the exit must be taken on the first
13593 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13594 // we know the numerator in the divides below must be zero, so we can
13595 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13596 // and produce the right result.
13597 // FIXME: Handle the case where Stride is poison?
13598 auto wouldZeroStrideBeUB = [&]() {
13599 // Proof by contradiction. Suppose the stride were zero. If we can
13600 // prove that the backedge *is* taken on the first iteration, then since
13601 // we know this condition controls the sole exit, we must have an
13602 // infinite loop. We can't have a (well defined) infinite loop per
13603 // check just above.
13604 // Note: The (Start - Stride) term is used to get the start' term from
13605 // (start' + stride,+,stride). Remember that we only care about the
13606 // result of this expression when stride == 0 at runtime.
13607 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13608 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13609 };
13610 if (!wouldZeroStrideBeUB()) {
13611 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13612 }
13613 }
13614 } else if (!NoWrap) {
13615 // Avoid proven overflow cases: this will ensure that the backedge taken
13616 // count will not generate any unsigned overflow.
13617 if (canIVOverflowOnLT(RHS, Stride, IsSigned))
13618 return getCouldNotCompute();
13619 }
13620
13621 // On all paths just preceeding, we established the following invariant:
13622 // IV can be assumed not to overflow up to and including the exiting
13623 // iteration. We proved this in one of two ways:
13624 // 1) We can show overflow doesn't occur before the exiting iteration
13625 // 1a) canIVOverflowOnLT, and b) step of one
13626 // 2) We can show that if overflow occurs, the loop must execute UB
13627 // before any possible exit.
13628 // Note that we have not yet proved RHS invariant (in general).
13629
13630 const SCEV *Start = IV->getStart();
13631
13632 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13633 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13634 // Use integer-typed versions for actual computation; we can't subtract
13635 // pointers in general.
13636 const SCEV *OrigStart = Start;
13637 const SCEV *OrigRHS = RHS;
13638 if (Start->getType()->isPointerTy()) {
13640 if (isa<SCEVCouldNotCompute>(Start))
13641 return Start;
13642 }
13643 if (RHS->getType()->isPointerTy()) {
13646 return RHS;
13647 }
13648
13649 const SCEV *End = nullptr, *BECount = nullptr,
13650 *BECountIfBackedgeTaken = nullptr;
13651 if (!isLoopInvariant(RHS, L)) {
13652 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13653 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13654 any(RHSAddRec->getNoWrapFlags())) {
13655 // The structure of loop we are trying to calculate backedge count of:
13656 //
13657 // left = left_start
13658 // right = right_start
13659 //
13660 // while(left < right){
13661 // ... do something here ...
13662 // left += s1; // stride of left is s1 (s1 > 0)
13663 // right += s2; // stride of right is s2 (s2 < 0)
13664 // }
13665 //
13666
13667 const SCEV *RHSStart = RHSAddRec->getStart();
13668 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13669
13670 // If Stride - RHSStride is positive and does not overflow, we can write
13671 // backedge count as ->
13672 // ceil((End - Start) /u (Stride - RHSStride))
13673 // Where, End = max(RHSStart, Start)
13674
13675 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13676 if (isKnownNegative(RHSStride) &&
13677 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13678 RHSStride)) {
13679
13680 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13681 if (isKnownPositive(Denominator)) {
13682 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13683 : getUMaxExpr(RHSStart, Start);
13684
13685 // We can do this because End >= Start, as End = max(RHSStart, Start)
13686 const SCEV *Delta = getMinusSCEV(End, Start);
13687
13688 BECount = getUDivCeilSCEV(Delta, Denominator);
13689 BECountIfBackedgeTaken =
13690 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13691 }
13692 }
13693 }
13694 if (BECount == nullptr) {
13695 // If we cannot calculate ExactBECount, we can calculate the MaxBECount,
13696 // given the start, stride and max value for the end bound of the
13697 // loop (RHS), and the fact that IV does not overflow (which is
13698 // checked above).
13699 const SCEV *MaxBECount = computeMaxBECountForLT(
13700 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13701 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
13702 MaxBECount, false /*MaxOrZero*/, Predicates);
13703 }
13704 } else {
13705 // We use the expression (max(End,Start)-Start)/Stride to describe the
13706 // backedge count, as if the backedge is taken at least once
13707 // max(End,Start) is End and so the result is as above, and if not
13708 // max(End,Start) is Start so we get a backedge count of zero.
13709 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
13710 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
13711 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13712 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13713 // Can we prove (max(RHS,Start) > Start - Stride?
13714 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
13715 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
13716 // In this case, we can use a refined formula for computing backedge
13717 // taken count. The general formula remains:
13718 // "End-Start /uceiling Stride" where "End = max(RHS,Start)"
13719 // We want to use the alternate formula:
13720 // "((End - 1) - (Start - Stride)) /u Stride"
13721 // Let's do a quick case analysis to show these are equivalent under
13722 // our precondition that max(RHS,Start) > Start - Stride.
13723 // * For RHS <= Start, the backedge-taken count must be zero.
13724 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13725 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
13726 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values
13727 // of Stride. For 0 stride, we've use umin(1,Stride) above,
13728 // reducing this to the stride of 1 case.
13729 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil
13730 // Stride".
13731 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13732 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
13733 // "((RHS - (Start - Stride) - 1) /u Stride".
13734 // Our preconditions trivially imply no overflow in that form.
13735 const SCEV *MinusOne = getMinusOne(Stride->getType());
13736 const SCEV *Numerator =
13737 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
13738 BECount = getUDivExpr(Numerator, Stride);
13739 }
13740
13741 if (!BECount) {
13742 auto canProveRHSGreaterThanEqualStart = [&]() {
13743 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13744 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, L);
13745 const SCEV *GuardedStart = applyLoopGuards(OrigStart, L);
13746
13747 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart) ||
13748 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13749 return true;
13750
13751 // (RHS > Start - 1) implies RHS >= Start.
13752 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13753 // "Start - 1" doesn't overflow.
13754 // * For signed comparison, if Start - 1 does overflow, it's equal
13755 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13756 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13757 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13758 //
13759 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13760 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13761 auto *StartMinusOne =
13762 getAddExpr(OrigStart, getMinusOne(OrigStart->getType()));
13763 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
13764 };
13765
13766 // If we know that RHS >= Start in the context of loop, then we know
13767 // that max(RHS, Start) = RHS at this point.
13768 if (canProveRHSGreaterThanEqualStart()) {
13769 End = RHS;
13770 } else {
13771 // If RHS < Start, the backedge will be taken zero times. So in
13772 // general, we can write the backedge-taken count as:
13773 //
13774 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13775 //
13776 // We convert it to the following to make it more convenient for SCEV:
13777 //
13778 // ceil(max(RHS, Start) - Start) / Stride
13779 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13780
13781 // See what would happen if we assume the backedge is taken. This is
13782 // used to compute MaxBECount.
13783 BECountIfBackedgeTaken =
13784 getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
13785 }
13786
13787 // At this point, we know:
13788 //
13789 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
13790 // 2. The index variable doesn't overflow.
13791 //
13792 // Therefore, we know N exists such that
13793 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13794 // doesn't overflow.
13795 //
13796 // Using this information, try to prove whether the addition in
13797 // "(Start - End) + (Stride - 1)" has unsigned overflow.
13798 const SCEV *One = getOne(Stride->getType());
13799 bool MayAddOverflow = [&] {
13800 if (isKnownToBeAPowerOfTwo(Stride)) {
13801 // Suppose Stride is a power of two, and Start/End are unsigned
13802 // integers. Let UMAX be the largest representable unsigned
13803 // integer.
13804 //
13805 // By the preconditions of this function, we know
13806 // "(Start + Stride * N) >= End", and this doesn't overflow.
13807 // As a formula:
13808 //
13809 // End <= (Start + Stride * N) <= UMAX
13810 //
13811 // Subtracting Start from all the terms:
13812 //
13813 // End - Start <= Stride * N <= UMAX - Start
13814 //
13815 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13816 //
13817 // End - Start <= Stride * N <= UMAX
13818 //
13819 // Stride * N is a multiple of Stride. Therefore,
13820 //
13821 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13822 //
13823 // Since Stride is a power of two, UMAX + 1 is divisible by
13824 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13825 // write:
13826 //
13827 // End - Start <= Stride * N <= UMAX - Stride - 1
13828 //
13829 // Dropping the middle term:
13830 //
13831 // End - Start <= UMAX - Stride - 1
13832 //
13833 // Adding Stride - 1 to both sides:
13834 //
13835 // (End - Start) + (Stride - 1) <= UMAX
13836 //
13837 // In other words, the addition doesn't have unsigned overflow.
13838 //
13839 // A similar proof works if we treat Start/End as signed values.
13840 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13841 // to use signed max instead of unsigned max. Note that we're
13842 // trying to prove a lack of unsigned overflow in either case.
13843 return false;
13844 }
13845 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13846 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13847 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13848 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13849 // 1 <s End.
13850 //
13851 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13852 // End.
13853 return false;
13854 }
13855 return true;
13856 }();
13857
13858 const SCEV *Delta = getMinusSCEV(End, Start);
13859 if (!MayAddOverflow) {
13860 // floor((D + (S - 1)) / S)
13861 // We prefer this formulation if it's legal because it's fewer
13862 // operations.
13863 BECount =
13864 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13865 } else {
13866 BECount = getUDivCeilSCEV(Delta, Stride);
13867 }
13868 }
13869 }
13870
13871 const SCEV *ConstantMaxBECount;
13872 bool MaxOrZero = false;
13873 if (isa<SCEVConstant>(BECount)) {
13874 ConstantMaxBECount = BECount;
13875 } else if (BECountIfBackedgeTaken &&
13876 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13877 // If we know exactly how many times the backedge will be taken if it's
13878 // taken at least once, then the backedge count will either be that or
13879 // zero.
13880 ConstantMaxBECount = BECountIfBackedgeTaken;
13881 MaxOrZero = true;
13882 } else {
13883 ConstantMaxBECount = computeMaxBECountForLT(
13884 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13885 }
13886
13887 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13888 !isa<SCEVCouldNotCompute>(BECount))
13889 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13890
13891 const SCEV *SymbolicMaxBECount =
13892 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13893 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13894 Predicates);
13895}
13896
13897ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13898 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13899 bool ControlsOnlyExit, bool AllowPredicates) {
13901 // We handle only IV > Invariant
13902 if (!isLoopInvariant(RHS, L))
13903 return getCouldNotCompute();
13904
13905 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13906 if (!IV && AllowPredicates)
13907 // Try to make this an AddRec using runtime tests, in the first X
13908 // iterations of this loop, where X is the SCEV expression found by the
13909 // algorithm below.
13910 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13911
13912 // Avoid weird loops
13913 if (!IV || IV->getLoop() != L || !IV->isAffine())
13914 return getCouldNotCompute();
13915
13916 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13917 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13919
13920 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13921
13922 // Avoid negative or zero stride values
13923 if (!isKnownPositive(Stride))
13924 return getCouldNotCompute();
13925
13926 // Avoid proven overflow cases: this will ensure that the backedge taken count
13927 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13928 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13929 // behaviors like the case of C language.
13930 if (!Stride->isOne() && !NoWrap)
13931 if (canIVOverflowOnGT(RHS, Stride, IsSigned))
13932 return getCouldNotCompute();
13933
13934 const SCEV *Start = IV->getStart();
13935 const SCEV *End = RHS;
13936 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13937 // If we know that Start >= RHS in the context of loop, then we know that
13938 // min(RHS, Start) = RHS at this point.
13940 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13941 End = RHS;
13942 else
13943 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13944 }
13945
13946 if (Start->getType()->isPointerTy()) {
13948 if (isa<SCEVCouldNotCompute>(Start))
13949 return Start;
13950 }
13951 if (End->getType()->isPointerTy()) {
13952 End = getLosslessPtrToIntExpr(End);
13953 if (isa<SCEVCouldNotCompute>(End))
13954 return End;
13955 }
13956
13957 // Compute ((Start - End) + (Stride - 1)) / Stride.
13958 // FIXME: This can overflow. Holding off on fixing this for now;
13959 // howManyGreaterThans will hopefully be gone soon.
13960 const SCEV *One = getOne(Stride->getType());
13961 const SCEV *BECount = getUDivExpr(
13962 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
13963
13964 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13966
13967 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13968 : getUnsignedRangeMin(Stride);
13969
13970 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13971 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13972 : APInt::getMinValue(BitWidth) + (MinStride - 1);
13973
13974 // Although End can be a MIN expression we estimate MinEnd considering only
13975 // the case End = RHS. This is safe because in the other case (Start - End)
13976 // is zero, leading to a zero maximum backedge taken count.
13977 APInt MinEnd =
13978 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13979 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13980
13981 const SCEV *ConstantMaxBECount =
13982 isa<SCEVConstant>(BECount)
13983 ? BECount
13984 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13985 getConstant(MinStride));
13986
13987 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13988 ConstantMaxBECount = BECount;
13989 const SCEV *SymbolicMaxBECount =
13990 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13991
13992 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13993 Predicates);
13994}
13995
13997 ScalarEvolution &SE) const {
13998 if (Range.isFullSet()) // Infinite loop.
13999 return SE.getCouldNotCompute();
14000
14001 // If the start is a non-zero constant, shift the range to simplify things.
14002 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
14003 if (!SC->getValue()->isZero()) {
14005 Operands[0] = SE.getZero(SC->getType());
14006 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
14008 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
14009 return ShiftedAddRec->getNumIterationsInRange(
14010 Range.subtract(SC->getAPInt()), SE);
14011 // This is strange and shouldn't happen.
14012 return SE.getCouldNotCompute();
14013 }
14014
14015 // The only time we can solve this is when we have all constant indices.
14016 // Otherwise, we cannot determine the overflow conditions.
14017 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
14018 return SE.getCouldNotCompute();
14019
14020 // Okay at this point we know that all elements of the chrec are constants and
14021 // that the start element is zero.
14022
14023 // First check to see if the range contains zero. If not, the first
14024 // iteration exits.
14025 unsigned BitWidth = SE.getTypeSizeInBits(getType());
14026 if (!Range.contains(APInt(BitWidth, 0)))
14027 return SE.getZero(getType());
14028
14029 if (isAffine()) {
14030 // If this is an affine expression then we have this situation:
14031 // Solve {0,+,A} in Range === Ax in Range
14032
14033 // We know that zero is in the range. If A is positive then we know that
14034 // the upper value of the range must be the first possible exit value.
14035 // If A is negative then the lower of the range is the last possible loop
14036 // value. Also note that we already checked for a full range.
14037 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
14038 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
14039
14040 // The exit value should be (End+A)/A.
14041 APInt ExitVal = (End + A).udiv(A);
14042 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
14043
14044 // Evaluate at the exit value. If we really did fall out of the valid
14045 // range, then we computed our trip count, otherwise wrap around or other
14046 // things must have happened.
14047 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
14048 if (Range.contains(Val->getValue()))
14049 return SE.getCouldNotCompute(); // Something strange happened
14050
14051 // Ensure that the previous value is in the range.
14052 assert(Range.contains(
14054 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
14055 "Linear scev computation is off in a bad way!");
14056 return SE.getConstant(ExitValue);
14057 }
14058
14059 if (isQuadratic()) {
14060 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
14061 return SE.getConstant(*S);
14062 }
14063
14064 return SE.getCouldNotCompute();
14065}
14066
14067const SCEVAddRecExpr *
14069 assert(getNumOperands() > 1 && "AddRec with zero step?");
14070 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
14071 // but in this case we cannot guarantee that the value returned will be an
14072 // AddRec because SCEV does not have a fixed point where it stops
14073 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
14074 // may happen if we reach arithmetic depth limit while simplifying. So we
14075 // construct the returned value explicitly.
14077 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
14078 // (this + Step) is {A+B,+,B+C,+...,+,N}.
14079 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
14080 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
14081 // We know that the last operand is not a constant zero (otherwise it would
14082 // have been popped out earlier). This guarantees us that if the result has
14083 // the same last operand, then it will also not be popped out, meaning that
14084 // the returned value will be an AddRec.
14085 const SCEV *Last = getOperand(getNumOperands() - 1);
14086 assert(!Last->isZero() && "Recurrency with zero step?");
14087 Ops.push_back(Last);
14090}
14091
14092// Return true when S contains at least an undef value.
14094 return SCEVExprContains(
14095 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
14096}
14097
14098// Return true when S contains a value that is a nullptr.
14100 return SCEVExprContains(S, [](const SCEV *S) {
14101 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
14102 return SU->getValue() == nullptr;
14103 return false;
14104 });
14105}
14106
14107/// Return the size of an element read or written by Inst.
14109 Type *Ty;
14110 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
14111 Ty = Store->getValueOperand()->getType();
14112 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
14113 Ty = Load->getType();
14114 else
14115 return nullptr;
14116
14118 return getSizeOfExpr(ETy, Ty);
14119}
14120
14121//===----------------------------------------------------------------------===//
14122// SCEVCallbackVH Class Implementation
14123//===----------------------------------------------------------------------===//
14124
14126 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14127 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
14128 SE->ConstantEvolutionLoopExitValue.erase(PN);
14129 SE->eraseValueFromMap(getValPtr());
14130 // this now dangles!
14131}
14132
14133void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14134 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14135
14136 // Forget all the expressions associated with users of the old value,
14137 // so that future queries will recompute the expressions using the new
14138 // value.
14139 SE->forgetValue(getValPtr());
14140 // this now dangles!
14141}
14142
14143ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14144 : CallbackVH(V), SE(se) {}
14145
14146//===----------------------------------------------------------------------===//
14147// ScalarEvolution Class Implementation
14148//===----------------------------------------------------------------------===//
14149
14152 LoopInfo &LI)
14153 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14154 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14155 LoopDispositions(64), BlockDispositions(64) {
14156 // To use guards for proving predicates, we need to scan every instruction in
14157 // relevant basic blocks, and not just terminators. Doing this is a waste of
14158 // time if the IR does not actually contain any calls to
14159 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14160 //
14161 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14162 // to _add_ guards to the module when there weren't any before, and wants
14163 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14164 // efficient in lieu of being smart in that rather obscure case.
14165
14166 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14167 F.getParent(), Intrinsic::experimental_guard);
14168 HasGuards = GuardDecl && !GuardDecl->use_empty();
14169}
14170
14172 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14173 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14174 ValueExprMap(std::move(Arg.ValueExprMap)),
14175 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14176 PendingMerges(std::move(Arg.PendingMerges)),
14177 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14178 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14179 PredicatedBackedgeTakenCounts(
14180 std::move(Arg.PredicatedBackedgeTakenCounts)),
14181 BECountUsers(std::move(Arg.BECountUsers)),
14182 ConstantEvolutionLoopExitValue(
14183 std::move(Arg.ConstantEvolutionLoopExitValue)),
14184 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14185 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14186 LoopDispositions(std::move(Arg.LoopDispositions)),
14187 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14188 BlockDispositions(std::move(Arg.BlockDispositions)),
14189 SCEVUsers(std::move(Arg.SCEVUsers)),
14190 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14191 SignedRanges(std::move(Arg.SignedRanges)),
14192 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14193 UniquePreds(std::move(Arg.UniquePreds)),
14194 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14195 LoopUsers(std::move(Arg.LoopUsers)),
14196 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14197 FirstUnknown(Arg.FirstUnknown) {
14198 Arg.FirstUnknown = nullptr;
14199}
14200
14202 // Iterate through all the SCEVUnknown instances and call their
14203 // destructors, so that they release their references to their values.
14204 for (SCEVUnknown *U = FirstUnknown; U;) {
14205 SCEVUnknown *Tmp = U;
14206 U = U->Next;
14207 Tmp->~SCEVUnknown();
14208 }
14209 FirstUnknown = nullptr;
14210
14211 ExprValueMap.clear();
14212 ValueExprMap.clear();
14213 HasRecMap.clear();
14214 BackedgeTakenCounts.clear();
14215 PredicatedBackedgeTakenCounts.clear();
14216
14217 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14218 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14219 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14220 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14221}
14222
14226
14227/// When printing a top-level SCEV for trip counts, it's helpful to include
14228/// a type for constants which are otherwise hard to disambiguate.
14229static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14230 if (isa<SCEVConstant>(S))
14231 OS << *S->getType() << " ";
14232 OS << *S;
14233}
14234
14236 const Loop *L) {
14237 // Print all inner loops first
14238 for (Loop *I : *L)
14239 PrintLoopInfo(OS, SE, I);
14240
14241 OS << "Loop ";
14242 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14243 OS << ": ";
14244
14245 SmallVector<BasicBlock *, 8> ExitingBlocks;
14246 L->getExitingBlocks(ExitingBlocks);
14247 if (ExitingBlocks.size() != 1)
14248 OS << "<multiple exits> ";
14249
14250 auto *BTC = SE->getBackedgeTakenCount(L);
14251 if (!isa<SCEVCouldNotCompute>(BTC)) {
14252 OS << "backedge-taken count is ";
14253 PrintSCEVWithTypeHint(OS, BTC);
14254 } else
14255 OS << "Unpredictable backedge-taken count.";
14256 OS << "\n";
14257
14258 if (ExitingBlocks.size() > 1)
14259 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14260 OS << " exit count for " << ExitingBlock->getName() << ": ";
14261 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14262 PrintSCEVWithTypeHint(OS, EC);
14263 if (isa<SCEVCouldNotCompute>(EC)) {
14264 // Retry with predicates.
14266 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14267 if (!isa<SCEVCouldNotCompute>(EC)) {
14268 OS << "\n predicated exit count for " << ExitingBlock->getName()
14269 << ": ";
14270 PrintSCEVWithTypeHint(OS, EC);
14271 OS << "\n Predicates:\n";
14272 for (const auto *P : Predicates)
14273 P->print(OS, 4);
14274 }
14275 }
14276 OS << "\n";
14277 }
14278
14279 OS << "Loop ";
14280 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14281 OS << ": ";
14282
14283 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14284 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14285 OS << "constant max backedge-taken count is ";
14286 PrintSCEVWithTypeHint(OS, ConstantBTC);
14288 OS << ", actual taken count either this or zero.";
14289 } else {
14290 OS << "Unpredictable constant max backedge-taken count. ";
14291 }
14292
14293 OS << "\n"
14294 "Loop ";
14295 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14296 OS << ": ";
14297
14298 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14299 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14300 OS << "symbolic max backedge-taken count is ";
14301 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14303 OS << ", actual taken count either this or zero.";
14304 } else {
14305 OS << "Unpredictable symbolic max backedge-taken count. ";
14306 }
14307 OS << "\n";
14308
14309 if (ExitingBlocks.size() > 1)
14310 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14311 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14312 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14314 PrintSCEVWithTypeHint(OS, ExitBTC);
14315 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14316 // Retry with predicates.
14318 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14320 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14321 OS << "\n predicated symbolic max exit count for "
14322 << ExitingBlock->getName() << ": ";
14323 PrintSCEVWithTypeHint(OS, ExitBTC);
14324 OS << "\n Predicates:\n";
14325 for (const auto *P : Predicates)
14326 P->print(OS, 4);
14327 }
14328 }
14329 OS << "\n";
14330 }
14331
14333 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14334 if (PBT != BTC) {
14335 OS << "Loop ";
14336 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14337 OS << ": ";
14338 if (!isa<SCEVCouldNotCompute>(PBT)) {
14339 OS << "Predicated backedge-taken count is ";
14340 PrintSCEVWithTypeHint(OS, PBT);
14341 } else
14342 OS << "Unpredictable predicated backedge-taken count.";
14343 OS << "\n";
14344 OS << " Predicates:\n";
14345 for (const auto *P : Preds)
14346 P->print(OS, 4);
14347 }
14348 Preds.clear();
14349
14350 auto *PredConstantMax =
14352 if (PredConstantMax != ConstantBTC) {
14353 OS << "Loop ";
14354 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14355 OS << ": ";
14356 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14357 OS << "Predicated constant max backedge-taken count is ";
14358 PrintSCEVWithTypeHint(OS, PredConstantMax);
14359 } else
14360 OS << "Unpredictable predicated constant max backedge-taken count.";
14361 OS << "\n";
14362 OS << " Predicates:\n";
14363 for (const auto *P : Preds)
14364 P->print(OS, 4);
14365 }
14366 Preds.clear();
14367
14368 auto *PredSymbolicMax =
14370 if (SymbolicBTC != PredSymbolicMax) {
14371 OS << "Loop ";
14372 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14373 OS << ": ";
14374 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14375 OS << "Predicated symbolic max backedge-taken count is ";
14376 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14377 } else
14378 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14379 OS << "\n";
14380 OS << " Predicates:\n";
14381 for (const auto *P : Preds)
14382 P->print(OS, 4);
14383 }
14384
14386 OS << "Loop ";
14387 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14388 OS << ": ";
14389 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14390 }
14391}
14392
14393namespace llvm {
14394// Note: these overloaded operators need to be in the llvm namespace for them
14395// to be resolved correctly. If we put them outside the llvm namespace, the
14396//
14397// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14398//
14399// code below "breaks" and start printing raw enum values as opposed to the
14400// string values.
14403 switch (LD) {
14405 OS << "Variant";
14406 break;
14408 OS << "Invariant";
14409 break;
14411 OS << "Uniform";
14412 break;
14414 OS << "Computable";
14415 break;
14416 }
14417 return OS;
14418}
14419
14422 switch (BD) {
14424 OS << "DoesNotDominate";
14425 break;
14427 OS << "Dominates";
14428 break;
14430 OS << "ProperlyDominates";
14431 break;
14432 }
14433 return OS;
14434}
14435} // namespace llvm
14436
14438 // ScalarEvolution's implementation of the print method is to print
14439 // out SCEV values of all instructions that are interesting. Doing
14440 // this potentially causes it to create new SCEV objects though,
14441 // which technically conflicts with the const qualifier. This isn't
14442 // observable from outside the class though, so casting away the
14443 // const isn't dangerous.
14444 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14445
14446 if (ClassifyExpressions) {
14447 OS << "Classifying expressions for: ";
14448 F.printAsOperand(OS, /*PrintType=*/false);
14449 OS << "\n";
14450 for (Instruction &I : instructions(F))
14451 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14452 OS << I << '\n';
14453 OS << " --> ";
14454 const SCEV *SV = SE.getSCEV(&I);
14455 SV->print(OS);
14456 if (!isa<SCEVCouldNotCompute>(SV)) {
14457 OS << " U: ";
14458 SE.getUnsignedRange(SV).print(OS);
14459 OS << " S: ";
14460 SE.getSignedRange(SV).print(OS);
14461 }
14462
14463 const Loop *L = LI.getLoopFor(I.getParent());
14464
14465 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
14466 if (AtUse != SV) {
14467 OS << " --> ";
14468 AtUse->print(OS);
14469 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14470 OS << " U: ";
14471 SE.getUnsignedRange(AtUse).print(OS);
14472 OS << " S: ";
14473 SE.getSignedRange(AtUse).print(OS);
14474 }
14475 }
14476
14477 if (L) {
14478 OS << "\t\t" "Exits: ";
14479 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14480 if (!SE.isLoopInvariant(ExitValue, L)) {
14481 OS << "<<Unknown>>";
14482 } else {
14483 OS << *ExitValue;
14484 }
14485
14486 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14487 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14488 OS << LS;
14489 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14490 OS << ": " << SE.getLoopDisposition(SV, Iter);
14491 }
14492
14493 for (const auto *InnerL : depth_first(L)) {
14494 if (InnerL == L)
14495 continue;
14496 OS << LS;
14497 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14498 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14499 }
14500
14501 OS << " }";
14502 }
14503
14504 OS << "\n";
14505 }
14506 }
14507
14508 OS << "Determining loop execution counts for: ";
14509 F.printAsOperand(OS, /*PrintType=*/false);
14510 OS << "\n";
14511 for (Loop *I : LI)
14512 PrintLoopInfo(OS, &SE, I);
14513}
14514
14517 auto &Values = LoopDispositions[S];
14518 for (auto &V : Values) {
14519 if (V.getPointer() == L)
14520 return V.getInt();
14521 }
14522 Values.emplace_back(L, LoopVariant);
14523 LoopDisposition D = computeLoopDisposition(S, L);
14524 auto &Values2 = LoopDispositions[S];
14525 for (auto &V : llvm::reverse(Values2)) {
14526 if (V.getPointer() == L) {
14527 V.setInt(D);
14528 break;
14529 }
14530 }
14531 return D;
14532}
14533
14535ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14536 switch (S->getSCEVType()) {
14537 case scConstant:
14538 case scVScale:
14539 return LoopInvariant;
14540 case scAddRecExpr: {
14541 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14542
14543 // If L is the addrec's loop, it's computable.
14544 if (AR->getLoop() == L)
14545 return LoopComputable;
14546
14547 // Add recurrences are never invariant in the function-body (null loop).
14548 if (!L)
14549 return LoopVariant;
14550
14551 // Everything that is not defined at loop entry is variant.
14552 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14553 if (L->contains(AR->getLoop()) &&
14554 llvm::all_of(AR->operands(),
14555 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14556 return LoopUniform;
14557
14558 return LoopVariant;
14559 }
14560 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14561 " dominate the contained loop's header?");
14562
14563 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14564 if (AR->getLoop()->contains(L))
14565 return LoopInvariant;
14566
14567 // This recurrence is variant w.r.t. L if any of its operands
14568 // are variant.
14569 for (SCEVUse Op : AR->operands())
14570 if (!isLoopInvariant(Op, L))
14571 return LoopVariant;
14572
14573 // Otherwise it's loop-invariant.
14574 return LoopInvariant;
14575 }
14576 case scTruncate:
14577 case scZeroExtend:
14578 case scSignExtend:
14579 case scPtrToAddr:
14580 case scPtrToInt:
14581 case scAddExpr:
14582 case scMulExpr:
14583 case scUDivExpr:
14584 case scUMaxExpr:
14585 case scSMaxExpr:
14586 case scUMinExpr:
14587 case scSMinExpr:
14588 case scSequentialUMinExpr: {
14589 bool HasVarying = false;
14590 bool HasUniform = false;
14591 for (SCEVUse Op : S->operands()) {
14593 if (D == LoopVariant)
14594 return LoopVariant;
14595 if (D == LoopComputable)
14596 HasVarying = true;
14597 if (D == LoopUniform)
14598 HasUniform = true;
14599 }
14600 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14601 : (HasUniform ? LoopUniform : LoopInvariant);
14602 }
14603 case scUnknown:
14604 // All non-instruction values are loop invariant. All instructions are loop
14605 // invariant if they are not contained in the specified loop.
14606 // Instructions are never considered invariant in the function body
14607 // (null loop) because they are defined within the "loop".
14609 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14610 return LoopInvariant;
14611 case scCouldNotCompute:
14612 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14613 }
14614 llvm_unreachable("Unknown SCEV kind!");
14615}
14616
14617bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14619 return D == LoopUniform || D == LoopInvariant;
14620}
14621
14623 return getLoopDisposition(S, L) == LoopInvariant;
14624}
14625
14627 return getLoopDisposition(S, L) == LoopComputable;
14628}
14629
14632 auto &Values = BlockDispositions[S];
14633 for (auto &V : Values) {
14634 if (V.getPointer() == BB)
14635 return V.getInt();
14636 }
14637 Values.emplace_back(BB, DoesNotDominateBlock);
14638 BlockDisposition D = computeBlockDisposition(S, BB);
14639 auto &Values2 = BlockDispositions[S];
14640 for (auto &V : llvm::reverse(Values2)) {
14641 if (V.getPointer() == BB) {
14642 V.setInt(D);
14643 break;
14644 }
14645 }
14646 return D;
14647}
14648
14650ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14651 switch (S->getSCEVType()) {
14652 case scConstant:
14653 case scVScale:
14655 case scAddRecExpr: {
14656 // This uses a "dominates" query instead of "properly dominates" query
14657 // to test for proper dominance too, because the instruction which
14658 // produces the addrec's value is a PHI, and a PHI effectively properly
14659 // dominates its entire containing block.
14660 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14661 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14662 return DoesNotDominateBlock;
14663
14664 // Fall through into SCEVNAryExpr handling.
14665 [[fallthrough]];
14666 }
14667 case scTruncate:
14668 case scZeroExtend:
14669 case scSignExtend:
14670 case scPtrToAddr:
14671 case scPtrToInt:
14672 case scAddExpr:
14673 case scMulExpr:
14674 case scUDivExpr:
14675 case scUMaxExpr:
14676 case scSMaxExpr:
14677 case scUMinExpr:
14678 case scSMinExpr:
14679 case scSequentialUMinExpr: {
14680 bool Proper = true;
14681 for (const SCEV *NAryOp : S->operands()) {
14683 if (D == DoesNotDominateBlock)
14684 return DoesNotDominateBlock;
14685 if (D == DominatesBlock)
14686 Proper = false;
14687 }
14688 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14689 }
14690 case scUnknown:
14691 if (Instruction *I =
14693 if (I->getParent() == BB)
14694 return DominatesBlock;
14695 if (DT.properlyDominates(I->getParent(), BB))
14697 return DoesNotDominateBlock;
14698 }
14700 case scCouldNotCompute:
14701 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14702 }
14703 llvm_unreachable("Unknown SCEV kind!");
14704}
14705
14706bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14707 return getBlockDisposition(S, BB) >= DominatesBlock;
14708}
14709
14712}
14713
14714bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
14715 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
14716}
14717
14718void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14719 bool Predicated) {
14720 auto &BECounts =
14721 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14722 auto It = BECounts.find(L);
14723 if (It != BECounts.end()) {
14724 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14725 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14726 if (!isa<SCEVConstant>(S)) {
14727 auto UserIt = BECountUsers.find(S);
14728 assert(UserIt != BECountUsers.end());
14729 UserIt->second.erase({L, Predicated});
14730 }
14731 }
14732 }
14733 BECounts.erase(It);
14734 }
14735}
14736
14737void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14738 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14739 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14740
14741 while (!Worklist.empty()) {
14742 const SCEV *Curr = Worklist.pop_back_val();
14743 auto Users = SCEVUsers.find(Curr);
14744 if (Users != SCEVUsers.end())
14745 for (const auto *User : Users->second)
14746 if (ToForget.insert(User).second)
14747 Worklist.push_back(User);
14748 }
14749
14750 for (const auto *S : ToForget)
14751 forgetMemoizedResultsImpl(S);
14752
14753 PredicatedSCEVRewrites.remove_if(
14754 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14755}
14756
14757void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14758 LoopDispositions.erase(S);
14759 BlockDispositions.erase(S);
14760 UnsignedRanges.erase(S);
14761 SignedRanges.erase(S);
14762 HasRecMap.erase(S);
14763 ConstantMultipleCache.erase(S);
14764
14765 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14766 UnsignedWrapViaInductionTried.erase(AR);
14767 SignedWrapViaInductionTried.erase(AR);
14768 }
14769
14770 auto ExprIt = ExprValueMap.find(S);
14771 if (ExprIt != ExprValueMap.end()) {
14772 for (Value *V : ExprIt->second) {
14773 auto ValueIt = ValueExprMap.find_as(V);
14774 if (ValueIt != ValueExprMap.end())
14775 ValueExprMap.erase(ValueIt);
14776 }
14777 ExprValueMap.erase(ExprIt);
14778 }
14779
14780 auto ScopeIt = ValuesAtScopes.find(S);
14781 if (ScopeIt != ValuesAtScopes.end()) {
14782 for (const auto &Pair : ScopeIt->second)
14783 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14784 llvm::erase(ValuesAtScopesUsers[Pair.second],
14785 std::make_pair(Pair.first, S));
14786 ValuesAtScopes.erase(ScopeIt);
14787 }
14788
14789 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14790 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14791 for (const auto &Pair : ScopeUserIt->second)
14792 llvm::erase(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
14793 ValuesAtScopesUsers.erase(ScopeUserIt);
14794 }
14795
14796 auto BEUsersIt = BECountUsers.find(S);
14797 if (BEUsersIt != BECountUsers.end()) {
14798 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14799 auto Copy = BEUsersIt->second;
14800 for (const auto &Pair : Copy)
14801 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14802 BECountUsers.erase(BEUsersIt);
14803 }
14804
14805 auto FoldUser = FoldCacheUser.find(S);
14806 if (FoldUser != FoldCacheUser.end())
14807 for (auto &KV : FoldUser->second)
14808 FoldCache.erase(KV);
14809 FoldCacheUser.erase(S);
14810}
14811
14812void
14813ScalarEvolution::getUsedLoops(const SCEV *S,
14814 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14815 struct FindUsedLoops {
14816 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14817 : LoopsUsed(LoopsUsed) {}
14818 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14819 bool follow(const SCEV *S) {
14820 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14821 LoopsUsed.insert(AR->getLoop());
14822 return true;
14823 }
14824
14825 bool isDone() const { return false; }
14826 };
14827
14828 FindUsedLoops F(LoopsUsed);
14829 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14830}
14831
14832void ScalarEvolution::getReachableBlocks(
14835 Worklist.push_back(&F.getEntryBlock());
14836 while (!Worklist.empty()) {
14837 BasicBlock *BB = Worklist.pop_back_val();
14838 if (!Reachable.insert(BB).second)
14839 continue;
14840
14841 Value *Cond;
14842 BasicBlock *TrueBB, *FalseBB;
14843 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14844 m_BasicBlock(FalseBB)))) {
14845 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14846 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14847 continue;
14848 }
14849
14850 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14851 const SCEV *L = getSCEV(Cmp->getOperand(0));
14852 const SCEV *R = getSCEV(Cmp->getOperand(1));
14853 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14854 Worklist.push_back(TrueBB);
14855 continue;
14856 }
14857 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14858 R)) {
14859 Worklist.push_back(FalseBB);
14860 continue;
14861 }
14862 }
14863 }
14864
14865 append_range(Worklist, successors(BB));
14866 }
14867}
14868
14870 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14871 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14872
14873 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14874
14875 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14876 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14877 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14878
14879 const SCEV *visitConstant(const SCEVConstant *Constant) {
14880 return SE.getConstant(Constant->getAPInt());
14881 }
14882
14883 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14884 return SE.getUnknown(Expr->getValue());
14885 }
14886
14887 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14888 return SE.getCouldNotCompute();
14889 }
14890 };
14891
14892 SCEVMapper SCM(SE2);
14893 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14894 SE2.getReachableBlocks(ReachableBlocks, F);
14895
14896 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14897 if (containsUndefs(Old) || containsUndefs(New)) {
14898 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14899 // not propagate undef aggressively). This means we can (and do) fail
14900 // verification in cases where a transform makes a value go from "undef"
14901 // to "undef+1" (say). The transform is fine, since in both cases the
14902 // result is "undef", but SCEV thinks the value increased by 1.
14903 return nullptr;
14904 }
14905
14906 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14907 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14908 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14909 return nullptr;
14910
14911 return Delta;
14912 };
14913
14914 while (!LoopStack.empty()) {
14915 auto *L = LoopStack.pop_back_val();
14916 llvm::append_range(LoopStack, *L);
14917
14918 // Only verify BECounts in reachable loops. For an unreachable loop,
14919 // any BECount is legal.
14920 if (!ReachableBlocks.contains(L->getHeader()))
14921 continue;
14922
14923 // Only verify cached BECounts. Computing new BECounts may change the
14924 // results of subsequent SCEV uses.
14925 auto It = BackedgeTakenCounts.find(L);
14926 if (It == BackedgeTakenCounts.end())
14927 continue;
14928
14929 auto *CurBECount =
14930 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14931 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14932
14933 if (CurBECount == SE2.getCouldNotCompute() ||
14934 NewBECount == SE2.getCouldNotCompute()) {
14935 // NB! This situation is legal, but is very suspicious -- whatever pass
14936 // change the loop to make a trip count go from could not compute to
14937 // computable or vice-versa *should have* invalidated SCEV. However, we
14938 // choose not to assert here (for now) since we don't want false
14939 // positives.
14940 continue;
14941 }
14942
14943 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14944 SE.getTypeSizeInBits(NewBECount->getType()))
14945 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14946 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14947 SE.getTypeSizeInBits(NewBECount->getType()))
14948 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14949
14950 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14951 if (Delta && !Delta->isZero()) {
14952 dbgs() << "Trip Count for " << *L << " Changed!\n";
14953 dbgs() << "Old: " << *CurBECount << "\n";
14954 dbgs() << "New: " << *NewBECount << "\n";
14955 dbgs() << "Delta: " << *Delta << "\n";
14956 std::abort();
14957 }
14958 }
14959
14960 // Collect all valid loops currently in LoopInfo.
14961 SmallPtrSet<Loop *, 32> ValidLoops;
14962 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14963 while (!Worklist.empty()) {
14964 Loop *L = Worklist.pop_back_val();
14965 if (ValidLoops.insert(L).second)
14966 Worklist.append(L->begin(), L->end());
14967 }
14968 for (const auto &KV : ValueExprMap) {
14969#ifndef NDEBUG
14970 // Check for SCEV expressions referencing invalid/deleted loops.
14971 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14972 assert(ValidLoops.contains(AR->getLoop()) &&
14973 "AddRec references invalid loop");
14974 }
14975#endif
14976
14977 // Check that the value is also part of the reverse map.
14978 auto It = ExprValueMap.find(KV.second);
14979 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14980 dbgs() << "Value " << *KV.first
14981 << " is in ValueExprMap but not in ExprValueMap\n";
14982 std::abort();
14983 }
14984
14985 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14986 if (!ReachableBlocks.contains(I->getParent()))
14987 continue;
14988 const SCEV *OldSCEV = SCM.visit(KV.second);
14989 const SCEV *NewSCEV = SE2.getSCEV(I);
14990 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14991 if (Delta && !Delta->isZero()) {
14992 dbgs() << "SCEV for value " << *I << " changed!\n"
14993 << "Old: " << *OldSCEV << "\n"
14994 << "New: " << *NewSCEV << "\n"
14995 << "Delta: " << *Delta << "\n";
14996 std::abort();
14997 }
14998 }
14999 }
15000
15001 for (const auto &KV : ExprValueMap) {
15002 for (Value *V : KV.second) {
15003 const SCEV *S = ValueExprMap.lookup(V);
15004 if (!S) {
15005 dbgs() << "Value " << *V
15006 << " is in ExprValueMap but not in ValueExprMap\n";
15007 std::abort();
15008 }
15009 if (S != KV.first) {
15010 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
15011 << *KV.first << "\n";
15012 std::abort();
15013 }
15014 }
15015 }
15016
15017 // Verify integrity of SCEV users.
15018 for (const auto &S : UniqueSCEVs) {
15019 for (SCEVUse Op : S.operands()) {
15020 // We do not store dependencies of constants.
15021 if (isa<SCEVConstant>(Op))
15022 continue;
15023 auto It = SCEVUsers.find(Op);
15024 if (It != SCEVUsers.end() && It->second.count(&S))
15025 continue;
15026 dbgs() << "Use of operand " << *Op << " by user " << S
15027 << " is not being tracked!\n";
15028 std::abort();
15029 }
15030 }
15031
15032 // Verify integrity of ValuesAtScopes users.
15033 for (const auto &ValueAndVec : ValuesAtScopes) {
15034 const SCEV *Value = ValueAndVec.first;
15035 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
15036 const Loop *L = LoopAndValueAtScope.first;
15037 const SCEV *ValueAtScope = LoopAndValueAtScope.second;
15038 if (!isa<SCEVConstant>(ValueAtScope)) {
15039 auto It = ValuesAtScopesUsers.find(ValueAtScope);
15040 if (It != ValuesAtScopesUsers.end() &&
15041 is_contained(It->second, std::make_pair(L, Value)))
15042 continue;
15043 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
15044 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
15045 std::abort();
15046 }
15047 }
15048 }
15049
15050 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
15051 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
15052 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
15053 const Loop *L = LoopAndValue.first;
15054 const SCEV *Value = LoopAndValue.second;
15056 auto It = ValuesAtScopes.find(Value);
15057 if (It != ValuesAtScopes.end() &&
15058 is_contained(It->second, std::make_pair(L, ValueAtScope)))
15059 continue;
15060 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
15061 << *ValueAtScope << " missing in ValuesAtScopes\n";
15062 std::abort();
15063 }
15064 }
15065
15066 // Verify integrity of BECountUsers.
15067 auto VerifyBECountUsers = [&](bool Predicated) {
15068 auto &BECounts =
15069 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
15070 for (const auto &LoopAndBEInfo : BECounts) {
15071 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
15072 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
15073 if (!isa<SCEVConstant>(S)) {
15074 auto UserIt = BECountUsers.find(S);
15075 if (UserIt != BECountUsers.end() &&
15076 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
15077 continue;
15078 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
15079 << " missing from BECountUsers\n";
15080 std::abort();
15081 }
15082 }
15083 }
15084 }
15085 };
15086 VerifyBECountUsers(/* Predicated */ false);
15087 VerifyBECountUsers(/* Predicated */ true);
15088
15089 // Verify intergity of loop disposition cache.
15090 for (auto &[S, Values] : LoopDispositions) {
15091 for (auto [Loop, CachedDisposition] : Values) {
15092 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
15093 if (CachedDisposition != RecomputedDisposition) {
15094 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
15095 << " is incorrect: cached " << CachedDisposition << ", actual "
15096 << RecomputedDisposition << "\n";
15097 std::abort();
15098 }
15099 }
15100 }
15101
15102 // Verify integrity of the block disposition cache.
15103 for (auto &[S, Values] : BlockDispositions) {
15104 for (auto [BB, CachedDisposition] : Values) {
15105 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
15106 if (CachedDisposition != RecomputedDisposition) {
15107 dbgs() << "Cached disposition of " << *S << " for block %"
15108 << BB->getName() << " is incorrect: cached " << CachedDisposition
15109 << ", actual " << RecomputedDisposition << "\n";
15110 std::abort();
15111 }
15112 }
15113 }
15114
15115 // Verify FoldCache/FoldCacheUser caches.
15116 for (auto [FoldID, Expr] : FoldCache) {
15117 auto I = FoldCacheUser.find(Expr);
15118 if (I == FoldCacheUser.end()) {
15119 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
15120 << "!\n";
15121 std::abort();
15122 }
15123 if (!is_contained(I->second, FoldID)) {
15124 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15125 std::abort();
15126 }
15127 }
15128 for (auto [Expr, IDs] : FoldCacheUser) {
15129 for (auto &FoldID : IDs) {
15130 const SCEV *S = FoldCache.lookup(FoldID);
15131 if (!S) {
15132 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15133 << "!\n";
15134 std::abort();
15135 }
15136 if (S != Expr) {
15137 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15138 << " != " << *Expr << "!\n";
15139 std::abort();
15140 }
15141 }
15142 }
15143
15144 // Verify that ConstantMultipleCache computations are correct. We check that
15145 // cached multiples and recomputed multiples are multiples of each other to
15146 // verify correctness. It is possible that a recomputed multiple is different
15147 // from the cached multiple due to strengthened no wrap flags or changes in
15148 // KnownBits computations.
15149 for (auto [S, Multiple] : ConstantMultipleCache) {
15150 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15151 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15152 Multiple.urem(RecomputedMultiple) != 0 &&
15153 RecomputedMultiple.urem(Multiple) != 0)) {
15154 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15155 << *S << " : Computed " << RecomputedMultiple
15156 << " but cache contains " << Multiple << "!\n";
15157 std::abort();
15158 }
15159 }
15160}
15161
15163 Function &F, const PreservedAnalyses &PA,
15164 FunctionAnalysisManager::Invalidator &Inv) {
15165 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15166 // of its dependencies is invalidated.
15167 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15168 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15169 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15170 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15171 Inv.invalidate<LoopAnalysis>(F, PA);
15172}
15173
15174AnalysisKey ScalarEvolutionAnalysis::Key;
15175
15178 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15179 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15180 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15181 auto &LI = AM.getResult<LoopAnalysis>(F);
15182 return ScalarEvolution(F, TLI, AC, DT, LI);
15183}
15184
15190
15193 // For compatibility with opt's -analyze feature under legacy pass manager
15194 // which was not ported to NPM. This keeps tests using
15195 // update_analyze_test_checks.py working.
15196 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15197 << F.getName() << "':\n";
15199 return PreservedAnalyses::all();
15200}
15201
15203 "Scalar Evolution Analysis", false, true)
15209 "Scalar Evolution Analysis", false, true)
15210
15212
15214
15216 SE.reset(new ScalarEvolution(
15218 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15220 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15221 return false;
15222}
15223
15225
15227 SE->print(OS);
15228}
15229
15231 if (!VerifySCEV)
15232 return;
15233
15234 SE->verify();
15235}
15236
15244
15246 const SCEV *RHS) {
15247 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15248}
15249
15250const SCEVPredicate *
15252 const SCEV *LHS, const SCEV *RHS) {
15254 assert(LHS->getType() == RHS->getType() &&
15255 "Type mismatch between LHS and RHS");
15256 // Unique this node based on the arguments
15257 ID.AddInteger(SCEVPredicate::P_Compare);
15258 ID.AddInteger(Pred);
15259 ID.AddPointer(LHS);
15260 ID.AddPointer(RHS);
15261 void *IP = nullptr;
15262 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
15263 return S;
15264 SCEVComparePredicate *Eq = new (SCEVAllocator)
15265 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15266 UniquePreds.InsertNode(Eq, IP);
15267 return Eq;
15268}
15269
15271 const SCEVAddRecExpr *AR,
15274 // Unique this node based on the arguments
15275 ID.AddInteger(SCEVPredicate::P_Wrap);
15276 ID.AddPointer(AR);
15277 ID.AddInteger(AddedFlags);
15278 void *IP = nullptr;
15279 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
15280 return S;
15281 auto *OF = new (SCEVAllocator)
15282 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15283 UniquePreds.InsertNode(OF, IP);
15284 return OF;
15285}
15286
15287namespace {
15288
15289class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15290public:
15291
15292 /// Rewrites \p S in the context of a loop L and the SCEV predication
15293 /// infrastructure.
15294 ///
15295 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15296 /// equivalences present in \p Pred.
15297 ///
15298 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15299 /// \p NewPreds such that the result will be an AddRecExpr.
15300 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15302 const SCEVPredicate *Pred) {
15303 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15304 return Rewriter.visit(S);
15305 }
15306
15307 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15308 if (Pred) {
15309 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15310 for (const auto *Pred : U->getPredicates())
15311 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15312 if (IPred->getLHS() == Expr &&
15313 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15314 return IPred->getRHS();
15315 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15316 if (IPred->getLHS() == Expr &&
15317 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15318 return IPred->getRHS();
15319 }
15320 }
15321 return convertToAddRecWithPreds(Expr);
15322 }
15323
15324 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15325 const SCEV *Operand = visit(Expr->getOperand());
15326 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15327 if (AR && AR->getLoop() == L && AR->isAffine()) {
15328 // This couldn't be folded because the operand didn't have the nuw
15329 // flag. Add the nusw flag as an assumption that we could make.
15330 const SCEV *Step = AR->getStepRecurrence(SE);
15331 Type *Ty = Expr->getType();
15332 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15333 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15334 SE.getSignExtendExpr(Step, Ty), L,
15335 AR->getNoWrapFlags());
15336 }
15337 return SE.getZeroExtendExpr(Operand, Expr->getType());
15338 }
15339
15340 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15341 const SCEV *Operand = visit(Expr->getOperand());
15342 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15343 if (AR && AR->getLoop() == L && AR->isAffine()) {
15344 // This couldn't be folded because the operand didn't have the nsw
15345 // flag. Add the nssw flag as an assumption that we could make.
15346 const SCEV *Step = AR->getStepRecurrence(SE);
15347 Type *Ty = Expr->getType();
15348 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15349 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15350 SE.getSignExtendExpr(Step, Ty), L,
15351 AR->getNoWrapFlags());
15352 }
15353 return SE.getSignExtendExpr(Operand, Expr->getType());
15354 }
15355
15356private:
15357 explicit SCEVPredicateRewriter(
15358 const Loop *L, ScalarEvolution &SE,
15359 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15360 const SCEVPredicate *Pred)
15361 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15362
15363 bool addOverflowAssumption(const SCEVPredicate *P) {
15364 if (!NewPreds) {
15365 // Check if we've already made this assumption.
15366 return Pred && Pred->implies(P, SE);
15367 }
15368 NewPreds->push_back(P);
15369 return true;
15370 }
15371
15372 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15374 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15375 return addOverflowAssumption(A);
15376 }
15377
15378 // If \p Expr represents a PHINode, we try to see if it can be represented
15379 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15380 // to add this predicate as a runtime overflow check, we return the AddRec.
15381 // If \p Expr does not meet these conditions (is not a PHI node, or we
15382 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15383 // return \p Expr.
15384 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15385 if (!isa<PHINode>(Expr->getValue()))
15386 return Expr;
15387 std::optional<
15388 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15389 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15390 if (!PredicatedRewrite)
15391 return Expr;
15392 for (const auto *P : PredicatedRewrite->second){
15393 // Wrap predicates from outer loops are not supported.
15394 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15395 if (L != WP->getExpr()->getLoop())
15396 return Expr;
15397 }
15398 if (!addOverflowAssumption(P))
15399 return Expr;
15400 }
15401 return PredicatedRewrite->first;
15402 }
15403
15404 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15405 const SCEVPredicate *Pred;
15406 const Loop *L;
15407};
15408
15409} // end anonymous namespace
15410
15411const SCEV *
15413 const SCEVPredicate &Preds) {
15414 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15415}
15416
15418 const SCEV *S, const Loop *L,
15421 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15422 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15423
15424 if (!AddRec)
15425 return nullptr;
15426
15427 // Check if any of the transformed predicates is known to be false. In that
15428 // case, it doesn't make sense to convert to a predicated AddRec, as the
15429 // versioned loop will never execute.
15430 for (const SCEVPredicate *Pred : TransformPreds) {
15431 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15432 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15433 continue;
15434
15435 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15436 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15437 if (isa<SCEVCouldNotCompute>(ExitCount))
15438 continue;
15439
15440 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15441 if (!Step->isOne())
15442 continue;
15443
15444 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15445 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15446 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15447 return nullptr;
15448 }
15449
15450 // Since the transformation was successful, we can now transfer the SCEV
15451 // predicates.
15452 Preds.append(TransformPreds.begin(), TransformPreds.end());
15453
15454 return AddRec;
15455}
15456
15457/// SCEV predicates
15461
15463 const ICmpInst::Predicate Pred,
15464 const SCEV *LHS, const SCEV *RHS)
15465 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15466 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15467 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15468}
15469
15471 ScalarEvolution &SE) const {
15472 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15473
15474 if (!Op)
15475 return false;
15476
15477 if (Pred != ICmpInst::ICMP_EQ)
15478 return false;
15479
15480 return Op->LHS == LHS && Op->RHS == RHS;
15481}
15482
15483bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15484
15486 if (Pred == ICmpInst::ICMP_EQ)
15487 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15488 else
15489 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15490 << *RHS << "\n";
15491
15492}
15493
15495 const SCEVAddRecExpr *AR,
15496 IncrementWrapFlags Flags)
15497 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15498
15499const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15500
15502 ScalarEvolution &SE) const {
15503 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15504 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15505 return false;
15506
15507 if (Op->AR == AR)
15508 return true;
15509
15510 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15512 return false;
15513
15514 const SCEV *Start = AR->getStart();
15515 const SCEV *OpStart = Op->AR->getStart();
15516 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15517 return false;
15518
15519 // Reject pointers to different address spaces.
15520 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15521 return false;
15522
15523 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15524 // narrower-type AddRec.
15525 if (SE.getTypeSizeInBits(AR->getType()) >
15526 SE.getTypeSizeInBits(Op->AR->getType()))
15527 return false;
15528
15529 const SCEV *Step = AR->getStepRecurrence(SE);
15530 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15531 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15532 return false;
15533
15534 // If both steps are positive, this implies N, if N's start and step are
15535 // ULE/SLE (for NSUW/NSSW) than this'.
15536 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15537 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15538 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15539
15540 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15541 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15542 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15543 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15544 : SE.getNoopOrSignExtend(Start, WiderTy);
15546 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15547 SE.isKnownPredicate(Pred, OpStart, Start);
15548}
15549
15551 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
15552 IncrementWrapFlags IFlags = Flags;
15553
15554 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15555 IFlags = clearFlags(IFlags, IncrementNSSW);
15556
15557 return IFlags == IncrementAnyWrap;
15558}
15559
15560void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15561 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15563 OS << "<nusw>";
15565 OS << "<nssw>";
15566 OS << "\n";
15567}
15568
15571 ScalarEvolution &SE) {
15572 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
15573 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
15574
15575 // We can safely transfer the NSW flag as NSSW.
15576 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
15577 ImpliedFlags = IncrementNSSW;
15578
15579 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
15580 // If the increment is positive, the SCEV NUW flag will also imply the
15581 // WrapPredicate NUSW flag.
15582 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
15583 if (Step->getValue()->getValue().isNonNegative())
15584 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
15585 }
15586
15587 return ImpliedFlags;
15588}
15589
15590/// Union predicates don't get cached so create a dummy set ID for it.
15592 ScalarEvolution &SE)
15593 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
15594 for (const auto *P : Preds)
15595 add(P, SE);
15596}
15597
15599 return all_of(Preds,
15600 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15601}
15602
15604 ScalarEvolution &SE) const {
15605 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15606 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15607 return this->implies(I, SE);
15608 });
15609
15610 if (any_of(Preds,
15611 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15612 return true;
15613
15614 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15615 // equal predicates.
15616 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15617 if (!NWrap)
15618 return false;
15619 const Loop *L = NWrap->getExpr()->getLoop();
15620 return any_of(Preds, [&](const SCEVPredicate *I) {
15621 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15622 if (!IWrap)
15623 return false;
15624 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15625 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15626 return RewrittenAR &&
15627 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15628 });
15629}
15630
15632 for (const auto *Pred : Preds)
15633 Pred->print(OS, Depth);
15634}
15635
15636void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15637 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15638 for (const auto *Pred : Set->Preds)
15639 add(Pred, SE);
15640 return;
15641 }
15642
15643 // Implication checks are quadratic in the number of predicates. Stop doing
15644 // them if there are many predicates, as they should be too expensive to use
15645 // anyway at that point.
15646 bool CheckImplies = Preds.size() < 16;
15647
15648 // Only add predicate if it is not already implied by this union predicate.
15649 if (CheckImplies && implies(N, SE))
15650 return;
15651
15652 // Build a new vector containing the current predicates, except the ones that
15653 // are implied by the new predicate N.
15655 for (auto *P : Preds) {
15656 if (CheckImplies && N->implies(P, SE))
15657 continue;
15658 PrunedPreds.push_back(P);
15659 }
15660 Preds = std::move(PrunedPreds);
15661 Preds.push_back(N);
15662}
15663
15665 Loop &L)
15666 : SE(SE), L(L) {
15668 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15669}
15670
15673 for (const auto *Op : Ops)
15674 // We do not expect that forgetting cached data for SCEVConstants will ever
15675 // open any prospects for sharpening or introduce any correctness issues,
15676 // so we don't bother storing their dependencies.
15677 if (!isa<SCEVConstant>(Op))
15678 SCEVUsers[Op].insert(User);
15679}
15680
15682 for (const SCEV *Op : Ops)
15683 // We do not expect that forgetting cached data for SCEVConstants will ever
15684 // open any prospects for sharpening or introduce any correctness issues,
15685 // so we don't bother storing their dependencies.
15686 if (!isa<SCEVConstant>(Op))
15687 SCEVUsers[Op].insert(User);
15688}
15689
15691 const SCEV *Expr = SE.getSCEV(V);
15692 return getPredicatedSCEV(Expr);
15693}
15694
15696 RewriteEntry &Entry = RewriteMap[Expr];
15697
15698 // If we already have an entry and the version matches, return it.
15699 if (Entry.second && Generation == Entry.first)
15700 return Entry.second;
15701
15702 // We found an entry but it's stale. Rewrite the stale entry
15703 // according to the current predicate.
15704 if (Entry.second)
15705 Expr = Entry.second;
15706
15707 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15708 Entry = {Generation, NewSCEV};
15709
15710 return NewSCEV;
15711}
15712
15714 if (!BackedgeCount) {
15716 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15717 for (const auto *P : Preds)
15718 addPredicate(*P);
15719 }
15720 return BackedgeCount;
15721}
15722
15724 if (!SymbolicMaxBackedgeCount) {
15726 SymbolicMaxBackedgeCount =
15727 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15728 for (const auto *P : Preds)
15729 addPredicate(*P);
15730 }
15731 return SymbolicMaxBackedgeCount;
15732}
15733
15735 if (!SmallConstantMaxTripCount) {
15737 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15738 for (const auto *P : Preds)
15739 addPredicate(*P);
15740 }
15741 return *SmallConstantMaxTripCount;
15742}
15743
15745 if (Preds->implies(&Pred, SE))
15746 return;
15747
15748 SmallVector<const SCEVPredicate *, 4> NewPreds(Preds->getPredicates());
15749 NewPreds.push_back(&Pred);
15750 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds, SE);
15751 updateGeneration();
15752}
15753
15756 for (const SCEVPredicate *P : Preds)
15757 addPredicate(*P);
15758}
15759
15761 return *Preds;
15762}
15763
15764void PredicatedScalarEvolution::updateGeneration() {
15765 // If the generation number wrapped recompute everything.
15766 if (++Generation == 0) {
15767 for (auto &II : RewriteMap) {
15768 const SCEV *Rewritten = II.second.second;
15769 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15770 }
15771 }
15772}
15773
15776 const auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V));
15777 if (!AR)
15778 return false;
15779
15781 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
15782
15784}
15785
15788 const SCEV *Expr = this->getSCEV(V);
15790 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15791
15792 if (!New)
15793 return nullptr;
15794
15795 if (ExtraPreds) {
15796 ExtraPreds->append(NewPreds);
15797 return New;
15798 }
15799
15800 addPredicates(NewPreds);
15801
15802 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15803 return New;
15804}
15805
15808 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15809 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates(),
15810 SE)),
15811 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15812
15814 // For each block.
15815 for (auto *BB : L.getBlocks())
15816 for (auto &I : *BB) {
15817 if (!SE.isSCEVable(I.getType()))
15818 continue;
15819
15820 auto *Expr = SE.getSCEV(&I);
15821 auto II = RewriteMap.find(Expr);
15822
15823 if (II == RewriteMap.end())
15824 continue;
15825
15826 // Don't print things that are not interesting.
15827 if (II->second.second == Expr)
15828 continue;
15829
15830 OS.indent(Depth) << "[PSE]" << I << ":\n";
15831 OS.indent(Depth + 2) << *Expr << "\n";
15832 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15833 }
15834}
15835
15838 BasicBlock *Header = L->getHeader();
15839 BasicBlock *Pred = L->getLoopPredecessor();
15840 LoopGuards Guards(SE);
15841 if (!Pred)
15842 return Guards;
15844 collectFromBlock(SE, Guards, Header, Pred, VisitedBlocks);
15845 return Guards;
15846}
15847
15848void ScalarEvolution::LoopGuards::collectFromPHI(
15852 unsigned Depth) {
15853 if (!SE.isSCEVable(Phi.getType()))
15854 return;
15855
15856 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15857 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15858 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15859 if (!VisitedBlocks.insert(InBlock).second)
15860 return {nullptr, scCouldNotCompute};
15861
15862 // Avoid analyzing unreachable blocks so that we don't get trapped
15863 // traversing cycles with ill-formed dominance or infinite cycles
15864 if (!SE.DT.isReachableFromEntry(InBlock))
15865 return {nullptr, scCouldNotCompute};
15866
15867 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15868 if (Inserted)
15869 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15870 Depth + 1);
15871 auto &RewriteMap = G->second.RewriteMap;
15872 if (RewriteMap.empty())
15873 return {nullptr, scCouldNotCompute};
15874 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15875 if (S == RewriteMap.end())
15876 return {nullptr, scCouldNotCompute};
15877 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15878 if (!SM)
15879 return {nullptr, scCouldNotCompute};
15880 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15881 return {C0, SM->getSCEVType()};
15882 return {nullptr, scCouldNotCompute};
15883 };
15884 auto MergeMinMaxConst = [](MinMaxPattern P1,
15885 MinMaxPattern P2) -> MinMaxPattern {
15886 auto [C1, T1] = P1;
15887 auto [C2, T2] = P2;
15888 if (!C1 || !C2 || T1 != T2)
15889 return {nullptr, scCouldNotCompute};
15890 switch (T1) {
15891 case scUMaxExpr:
15892 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15893 case scSMaxExpr:
15894 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15895 case scUMinExpr:
15896 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15897 case scSMinExpr:
15898 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15899 default:
15900 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15901 }
15902 };
15903 auto P = GetMinMaxConst(0);
15904 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15905 if (!P.first)
15906 break;
15907 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15908 }
15909 if (P.first) {
15910 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15911 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15912 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15913 Guards.RewriteMap.insert({LHS, RHS});
15914 }
15915}
15916
15917// Return a new SCEV that modifies \p Expr to the closest number divides by
15918// \p Divisor and less or equal than Expr. For now, only handle constant
15919// Expr.
15921 const APInt &DivisorVal,
15922 ScalarEvolution &SE) {
15923 const APInt *ExprVal;
15924 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15925 DivisorVal.isNonPositive())
15926 return Expr;
15927 APInt Rem = ExprVal->urem(DivisorVal);
15928 // return the SCEV: Expr - Expr % Divisor
15929 return SE.getConstant(*ExprVal - Rem);
15930}
15931
15932// Return a new SCEV that modifies \p Expr to the closest number divides by
15933// \p Divisor and greater or equal than Expr. For now, only handle constant
15934// Expr.
15935static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15936 const APInt &DivisorVal,
15937 ScalarEvolution &SE) {
15938 const APInt *ExprVal;
15939 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15940 DivisorVal.isNonPositive())
15941 return Expr;
15942 APInt Rem = ExprVal->urem(DivisorVal);
15943 if (Rem.isZero())
15944 return Expr;
15945 // return the SCEV: Expr + Divisor - Expr % Divisor
15946 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15947}
15948
15950 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15953 // If we have LHS == 0, check if LHS is computing a property of some unknown
15954 // SCEV %v which we can rewrite %v to express explicitly.
15956 return false;
15957 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15958 // explicitly express that.
15959 const SCEVUnknown *URemLHS = nullptr;
15960 const SCEV *URemRHS = nullptr;
15961 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15962 return false;
15963
15964 const SCEV *Multiple =
15965 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15966 DivInfo[URemLHS] = Multiple;
15967 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15968 Multiples[URemLHS] = C->getAPInt();
15969 return true;
15970}
15971
15972// Check if the condition is a divisibility guard (A % B == 0).
15973static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15974 ScalarEvolution &SE) {
15975 const SCEV *X, *Y;
15976 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15977}
15978
15979// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15980// recursively. This is done by aligning up/down the constant value to the
15981// Divisor.
15982static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15983 APInt Divisor,
15984 ScalarEvolution &SE) {
15985 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15986 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15987 // the non-constant operand and in \p LHS the constant operand.
15988 auto IsMinMaxSCEVWithNonNegativeConstant =
15989 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15990 const SCEV *&RHS) {
15991 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15992 if (MinMax->getNumOperands() != 2)
15993 return false;
15994 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15995 if (C->getAPInt().isNegative())
15996 return false;
15997 SCTy = MinMax->getSCEVType();
15998 LHS = MinMax->getOperand(0);
15999 RHS = MinMax->getOperand(1);
16000 return true;
16001 }
16002 }
16003 return false;
16004 };
16005
16006 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
16007 SCEVTypes SCTy;
16008 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
16009 MinMaxRHS))
16010 return MinMaxExpr;
16011 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
16012 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
16013 auto *DivisibleExpr =
16014 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
16015 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
16017 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
16018 return SE.getMinMaxExpr(SCTy, Ops);
16019}
16020
16021void ScalarEvolution::LoopGuards::collectFromBlock(
16022 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
16023 const BasicBlock *Block, const BasicBlock *Pred,
16024 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
16025
16027
16028 SmallVector<SCEVUse> ExprsToRewrite;
16029 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
16030 const SCEV *RHS,
16031 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
16032 const LoopGuards &DivGuards) {
16033 // WARNING: It is generally unsound to apply any wrap flags to the proposed
16034 // replacement SCEV which isn't directly implied by the structure of that
16035 // SCEV. In particular, using contextual facts to imply flags is *NOT*
16036 // legal. See the scoping rules for flags in the header to understand why.
16037
16038 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
16039 // and \p FromRewritten are the same (i.e. there has been no rewrite
16040 // registered for \p From), then puts this value in the list of rewritten
16041 // expressions.
16042 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
16043 const SCEV *To) {
16044 if (From == FromRewritten)
16045 ExprsToRewrite.push_back(From);
16046 RewriteMap[From] = To;
16047 };
16048
16049 // Checks whether \p S has already been rewritten. In that case returns the
16050 // existing rewrite because we want to chain further rewrites onto the
16051 // already rewritten value. Otherwise returns \p S.
16052 auto GetMaybeRewritten = [&](const SCEV *S) {
16053 return RewriteMap.lookup_or(S, S);
16054 };
16055
16056 // Check for a condition of the form (-C1 + X < C2). InstCombine will
16057 // create this form when combining two checks of the form (X u< C2 + C1) and
16058 // (X >=u C1).
16059 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
16060 const SCEV *MatchLHS,
16061 const SCEV *MatchRHS) {
16062 const SCEVConstant *C1;
16063 const SCEVUnknown *LHSUnknown;
16064 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
16065 if (!match(MatchLHS,
16066 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
16067 !C2)
16068 return false;
16069
16070 auto ExactRegion =
16071 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
16072 .sub(C1->getAPInt());
16073
16074 // Bail out, unless we have a non-wrapping, monotonic range.
16075 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
16076 return false;
16077 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
16078 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
16079 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
16080 const SCEV *ClampedLHS =
16081 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
16082 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
16083 return true;
16084 };
16085 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
16086 return;
16087
16088 // Do not apply information for constants or if RHS contains an AddRec.
16090 return;
16091
16092 // If RHS is SCEVUnknown, make sure the information is applied to it.
16094 std::swap(LHS, RHS);
16096 }
16097
16098 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
16099 // Apply divisibility information when computing the constant multiple.
16100 const APInt &DividesBy =
16101 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
16102
16103 // Collect rewrites for LHS and its transitive operands based on the
16104 // condition.
16105 // For min/max expressions, also apply the guard to its operands:
16106 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
16107 // 'min(a, b) > c' -> '(a > c) and (b > c)',
16108 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
16109 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
16110
16111 // We cannot express strict predicates in SCEV, so instead we replace them
16112 // with non-strict ones against plus or minus one of RHS depending on the
16113 // predicate.
16114 const SCEV *One = SE.getOne(RHS->getType());
16115 switch (Predicate) {
16116 case CmpInst::ICMP_ULT:
16117 if (RHS->getType()->isPointerTy())
16118 return;
16119 RHS = SE.getUMaxExpr(RHS, One);
16120 [[fallthrough]];
16121 case CmpInst::ICMP_SLT: {
16122 RHS = SE.getMinusSCEV(RHS, One);
16123 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16124 break;
16125 }
16126 case CmpInst::ICMP_UGT:
16127 case CmpInst::ICMP_SGT:
16128 RHS = SE.getAddExpr(RHS, One);
16129 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16130 break;
16131 case CmpInst::ICMP_ULE:
16132 case CmpInst::ICMP_SLE:
16133 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16134 break;
16135 case CmpInst::ICMP_UGE:
16136 case CmpInst::ICMP_SGE:
16137 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16138 break;
16139 default:
16140 break;
16141 }
16142
16143 SmallVector<SCEVUse, 16> Worklist(1, LHS);
16144 SmallPtrSet<const SCEV *, 16> Visited;
16145
16146 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
16147 append_range(Worklist, S->operands());
16148 };
16149
16150 while (!Worklist.empty()) {
16151 const SCEV *From = Worklist.pop_back_val();
16152 if (isa<SCEVConstant>(From))
16153 continue;
16154 if (!Visited.insert(From).second)
16155 continue;
16156 const SCEV *FromRewritten = GetMaybeRewritten(From);
16157 const SCEV *To = nullptr;
16158
16159 switch (Predicate) {
16160 case CmpInst::ICMP_ULT:
16161 case CmpInst::ICMP_ULE:
16162 To = SE.getUMinExpr(FromRewritten, RHS);
16163 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16164 EnqueueOperands(UMax);
16165 break;
16166 case CmpInst::ICMP_SLT:
16167 case CmpInst::ICMP_SLE:
16168 To = SE.getSMinExpr(FromRewritten, RHS);
16169 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16170 EnqueueOperands(SMax);
16171 break;
16172 case CmpInst::ICMP_UGT:
16173 case CmpInst::ICMP_UGE:
16174 To = SE.getUMaxExpr(FromRewritten, RHS);
16175 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16176 EnqueueOperands(UMin);
16177 break;
16178 case CmpInst::ICMP_SGT:
16179 case CmpInst::ICMP_SGE:
16180 To = SE.getSMaxExpr(FromRewritten, RHS);
16181 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16182 EnqueueOperands(SMin);
16183 break;
16184 case CmpInst::ICMP_EQ:
16186 To = RHS;
16187 break;
16188 case CmpInst::ICMP_NE:
16189 if (match(RHS, m_scev_Zero())) {
16190 const SCEV *OneAlignedUp =
16191 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16192 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16193 } else {
16194 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16195 // but creating the subtraction eagerly is expensive. Track the
16196 // inequalities in a separate map, and materialize the rewrite lazily
16197 // when encountering a suitable subtraction while re-writing.
16198 if (LHS->getType()->isPointerTy()) {
16202 break;
16203 }
16204 const SCEVConstant *C;
16205 const SCEV *A, *B;
16208 RHS = A;
16209 LHS = B;
16210 }
16211 if (LHS > RHS)
16212 std::swap(LHS, RHS);
16213 Guards.NotEqual.insert({LHS, RHS});
16214 continue;
16215 }
16216 break;
16217 default:
16218 break;
16219 }
16220
16221 if (To)
16222 AddRewrite(From, FromRewritten, To);
16223 }
16224 };
16225
16227 // First, collect information from assumptions dominating the loop.
16228 for (auto &AssumeVH : SE.AC.assumptions()) {
16229 if (!AssumeVH)
16230 continue;
16231 auto *AssumeI = cast<CallInst>(AssumeVH);
16232 if (!SE.DT.dominates(AssumeI, Block))
16233 continue;
16234 Terms.emplace_back(AssumeI->getOperand(0), true);
16235 }
16236
16237 // Second, collect information from llvm.experimental.guards dominating the loop.
16238 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16239 SE.F.getParent(), Intrinsic::experimental_guard);
16240 if (GuardDecl)
16241 for (const auto *GU : GuardDecl->users())
16242 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16243 if (Guard->getFunction() == Block->getParent() &&
16244 SE.DT.dominates(Guard, Block))
16245 Terms.emplace_back(Guard->getArgOperand(0), true);
16246
16247 // Third, collect conditions from dominating branches. Starting at the loop
16248 // predecessor, climb up the predecessor chain, as long as there are
16249 // predecessors that can be found that have unique successors leading to the
16250 // original header.
16251 // TODO: share this logic with isLoopEntryGuardedByCond.
16252 unsigned NumCollectedConditions = 0;
16254 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16255 for (; Pair.first;
16256 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16257 VisitedBlocks.insert(Pair.second);
16258 const CondBrInst *LoopEntryPredicate =
16259 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16260 if (!LoopEntryPredicate)
16261 continue;
16262
16263 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16264 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16265 NumCollectedConditions++;
16266
16267 // If we are recursively collecting guards stop after 2
16268 // conditions to limit compile-time impact for now.
16269 if (Depth > 0 && NumCollectedConditions == 2)
16270 break;
16271 }
16272 // Finally, if we stopped climbing the predecessor chain because
16273 // there wasn't a unique one to continue, try to collect conditions
16274 // for PHINodes by recursively following all of their incoming
16275 // blocks and try to merge the found conditions to build a new one
16276 // for the Phi.
16277 if (Pair.second->hasNPredecessorsOrMore(2) &&
16279 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16280 for (auto &Phi : Pair.second->phis())
16281 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16282 }
16283
16284 // Now apply the information from the collected conditions to
16285 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16286 // earliest conditions is processed first, except guards with divisibility
16287 // information, which are moved to the back. This ensures the SCEVs with the
16288 // shortest dependency chains are constructed first.
16290 GuardsToProcess;
16291 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16292 SmallVector<Value *, 8> Worklist;
16293 SmallPtrSet<Value *, 8> Visited;
16294 Worklist.push_back(Term);
16295 while (!Worklist.empty()) {
16296 Value *Cond = Worklist.pop_back_val();
16297 if (!Visited.insert(Cond).second)
16298 continue;
16299
16300 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16301 auto Predicate =
16302 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16303 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16304 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16305 // If LHS is a constant, apply information to the other expression.
16306 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16307 // can improve results.
16308 if (isa<SCEVConstant>(LHS)) {
16309 std::swap(LHS, RHS);
16311 }
16312 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16313 continue;
16314 }
16315
16316 Value *L, *R;
16317 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16318 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16319 Worklist.push_back(L);
16320 Worklist.push_back(R);
16321 }
16322 }
16323 }
16324
16325 // Process divisibility guards in reverse order to populate DivGuards early.
16326 DenseMap<const SCEV *, APInt> Multiples;
16327 LoopGuards DivGuards(SE);
16328 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16329 if (!isDivisibilityGuard(LHS, RHS, SE))
16330 continue;
16331 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16332 Multiples, SE);
16333 }
16334
16335 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16336 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16337
16338 // Apply divisibility information last. This ensures it is applied to the
16339 // outermost expression after other rewrites for the given value.
16340 for (const auto &[K, Divisor] : Multiples) {
16341 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16342 Guards.RewriteMap[K] =
16344 Guards.rewrite(K), Divisor, SE),
16345 DivisorSCEV),
16346 DivisorSCEV);
16347 ExprsToRewrite.push_back(K);
16348 }
16349
16350 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16351 // the replacement expressions are contained in the ranges of the replaced
16352 // expressions.
16353 Guards.PreserveNUW = true;
16354 Guards.PreserveNSW = true;
16355 for (const SCEV *Expr : ExprsToRewrite) {
16356 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16357 Guards.PreserveNUW &=
16358 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16359 Guards.PreserveNSW &=
16360 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16361 }
16362
16363 // Now that all rewrite information is collect, rewrite the collected
16364 // expressions with the information in the map. This applies information to
16365 // sub-expressions.
16366 if (ExprsToRewrite.size() > 1) {
16367 for (const SCEV *Expr : ExprsToRewrite) {
16368 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16369 Guards.RewriteMap.erase(Expr);
16370 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16371 }
16372 }
16373}
16374
16376 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16377 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16378 /// replacement is loop invariant in the loop of the AddRec.
16379 class SCEVLoopGuardRewriter
16380 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16383
16385
16386 public:
16387 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16388 const ScalarEvolution::LoopGuards &Guards)
16389 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16390 NotEqual(Guards.NotEqual) {
16391 if (Guards.PreserveNUW)
16392 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16393 if (Guards.PreserveNSW)
16394 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16395 }
16396
16397 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16398
16399 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16400 return Map.lookup_or(Expr, Expr);
16401 }
16402
16403 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16404 if (const SCEV *S = Map.lookup(Expr))
16405 return S;
16406
16407 // If we didn't find the extact ZExt expr in the map, check if there's
16408 // an entry for a smaller ZExt we can use instead.
16409 Type *Ty = Expr->getType();
16410 const SCEV *Op = Expr->getOperand(0);
16411 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16412 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16413 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16414 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16415 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16416 if (const SCEV *S = Map.lookup(NarrowExt))
16417 return SE.getZeroExtendExpr(S, Ty);
16418 Bitwidth = Bitwidth / 2;
16419 }
16420
16422 Expr);
16423 }
16424
16425 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16426 if (const SCEV *S = Map.lookup(Expr))
16427 return S;
16429 Expr);
16430 }
16431
16432 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16433 if (const SCEV *S = Map.lookup(Expr))
16434 return S;
16436 }
16437
16438 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16439 if (const SCEV *S = Map.lookup(Expr))
16440 return S;
16442 }
16443
16444 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16445 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16446 // return UMax(S, 1).
16447 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16448 SCEVUse LHS, RHS;
16449 if (MatchBinarySub(S, LHS, RHS)) {
16450 if (LHS > RHS)
16451 std::swap(LHS, RHS);
16452 if (NotEqual.contains({LHS, RHS})) {
16453 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16454 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16455 return SE.getUMaxExpr(OneAlignedUp, S);
16456 }
16457 }
16458 return nullptr;
16459 };
16460
16461 // Check if Expr itself is a subtraction pattern with guard info.
16462 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16463 return Rewritten;
16464
16465 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16466 // (Const + A + B). There may be guard info for A + B, and if so, apply
16467 // it.
16468 // TODO: Could more generally apply guards to Add sub-expressions.
16469 if (isa<SCEVConstant>(Expr->getOperand(0)) &&
16470 Expr->getNumOperands() == 3) {
16471 const SCEV *Add =
16472 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16473 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16474 return SE.getAddExpr(
16475 Expr->getOperand(0), Rewritten,
16476 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16477 if (const SCEV *S = Map.lookup(Add))
16478 return SE.getAddExpr(Expr->getOperand(0), S);
16479 }
16480 SmallVector<SCEVUse, 2> Operands;
16481 bool Changed = false;
16482 for (SCEVUse Op : Expr->operands()) {
16483 Operands.push_back(
16485 Changed |= Op != Operands.back();
16486 }
16487 // We are only replacing operands with equivalent values, so transfer the
16488 // flags from the original expression.
16489 return !Changed ? Expr
16490 : SE.getAddExpr(Operands,
16492 Expr->getNoWrapFlags(), FlagMask));
16493 }
16494
16495 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16496 SmallVector<SCEVUse, 2> Operands;
16497 bool Changed = false;
16498 for (SCEVUse Op : Expr->operands()) {
16499 Operands.push_back(
16501 Changed |= Op != Operands.back();
16502 }
16503 // We are only replacing operands with equivalent values, so transfer the
16504 // flags from the original expression.
16505 return !Changed ? Expr
16506 : SE.getMulExpr(Operands,
16508 Expr->getNoWrapFlags(), FlagMask));
16509 }
16510 };
16511
16512 if (RewriteMap.empty() && NotEqual.empty())
16513 return Expr;
16514
16515 SCEVLoopGuardRewriter Rewriter(SE, *this);
16516 return Rewriter.visit(Expr);
16517}
16518
16519const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16520 return applyLoopGuards(Expr, LoopGuards::collect(L, *this));
16521}
16522
16524 const LoopGuards &Guards) {
16525 return Guards.rewrite(Expr);
16526}
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 IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space.
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 in 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 PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
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 * getLosslessPtrToIntExpr(const SCEV *Op)
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)
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:31
constexpr double e
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:392
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:374
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
IntPtrTy
Definition InstrProf.h:82
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.