LLVM 24.0.0git
ScalarEvolution.cpp
Go to the documentation of this file.
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution analysis
10// engine, which is used primarily to analyze expressions involving induction
11// variables in loops.
12//
13// There are several aspects to this library. First is the representation of
14// scalar expressions, which are represented as subclasses of the SCEV class.
15// These classes are used to represent certain types of subexpressions that we
16// can handle. We only create one SCEV of a particular shape, so
17// pointer-comparisons for equality are legal.
18//
19// One important aspect of the SCEV objects is that they are never cyclic, even
20// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21// the PHI node is one of the idioms that we can represent (e.g., a polynomial
22// recurrence) then we represent it directly as a recurrence node, otherwise we
23// represent it as a SCEVUnknown node.
24//
25// In addition to being able to represent expressions of various types, we also
26// have folders that are used to build the *canonical* representation for a
27// particular expression. These folders are capable of using a variety of
28// rewrite rules to simplify the expressions.
29//
30// Once the folders are defined, we can implement the more interesting
31// higher-level code, such as the code that recognizes PHI nodes of various
32// types, computes the execution count of a loop, etc.
33//
34// TODO: We should use these routines and value representations to implement
35// dependence analysis!
36//
37//===----------------------------------------------------------------------===//
38//
39// There are several good references for the techniques used in this analysis.
40//
41// Chains of recurrences -- a method to expedite the evaluation
42// of closed-form functions
43// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44//
45// On computational properties of chains of recurrences
46// Eugene V. Zima
47//
48// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49// Robert A. van Engelen
50//
51// Efficient Symbolic Analysis for Optimizing Compilers
52// Robert A. van Engelen
53//
54// Using the chains of recurrences algebra for data dependence testing and
55// induction variable substitution
56// MS Thesis, Johnie Birch
57//
58//===----------------------------------------------------------------------===//
59
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.h"
65#include "llvm/ADT/FoldingSet.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/ScopeExit.h"
68#include "llvm/ADT/Sequence.h"
71#include "llvm/ADT/Statistic.h"
73#include "llvm/ADT/StringRef.h"
83#include "llvm/Config/llvm-config.h"
84#include "llvm/IR/Argument.h"
85#include "llvm/IR/BasicBlock.h"
86#include "llvm/IR/CFG.h"
87#include "llvm/IR/Constant.h"
89#include "llvm/IR/Constants.h"
90#include "llvm/IR/DataLayout.h"
92#include "llvm/IR/Dominators.h"
93#include "llvm/IR/Function.h"
94#include "llvm/IR/GlobalAlias.h"
95#include "llvm/IR/GlobalValue.h"
97#include "llvm/IR/InstrTypes.h"
98#include "llvm/IR/Instruction.h"
101#include "llvm/IR/Intrinsics.h"
102#include "llvm/IR/LLVMContext.h"
103#include "llvm/IR/Operator.h"
104#include "llvm/IR/PatternMatch.h"
105#include "llvm/IR/Type.h"
106#include "llvm/IR/Use.h"
107#include "llvm/IR/User.h"
108#include "llvm/IR/Value.h"
109#include "llvm/IR/Verifier.h"
111#include "llvm/Pass.h"
112#include "llvm/Support/Casting.h"
115#include "llvm/Support/Debug.h"
121#include <algorithm>
122#include <cassert>
123#include <climits>
124#include <cstdint>
125#include <cstdlib>
126#include <map>
127#include <memory>
128#include <numeric>
129#include <optional>
130#include <tuple>
131#include <utility>
132#include <vector>
133
134using namespace llvm;
135using namespace PatternMatch;
136using namespace SCEVPatternMatch;
137
138#define DEBUG_TYPE "scalar-evolution"
139
140STATISTIC(NumExitCountsComputed,
141 "Number of loop exits with predictable exit counts");
142STATISTIC(NumExitCountsNotComputed,
143 "Number of loop exits without predictable exit counts");
144STATISTIC(NumBruteForceTripCountsComputed,
145 "Number of loops with trip counts computed by force");
146
147#ifdef EXPENSIVE_CHECKS
148bool llvm::VerifySCEV = true;
149#else
150bool llvm::VerifySCEV = false;
151#endif
152
154 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
155 cl::desc("Maximum number of iterations SCEV will "
156 "symbolically execute a constant "
157 "derived loop"),
158 cl::init(100));
159
161 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
164 "verify-scev-strict", cl::Hidden,
165 cl::desc("Enable stricter verification with -verify-scev is passed"));
166
168 "scev-verify-ir", cl::Hidden,
169 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
170 cl::init(false));
171
173 "scev-mulops-inline-threshold", cl::Hidden,
174 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
175 cl::init(32));
176
178 "scev-addops-inline-threshold", cl::Hidden,
179 cl::desc("Threshold for inlining addition operands into a SCEV"),
180 cl::init(500));
181
183 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
184 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
185 cl::init(32));
186
188 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
189 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
190 cl::init(2));
191
193 "scalar-evolution-max-value-compare-depth", cl::Hidden,
194 cl::desc("Maximum depth of recursive value complexity comparisons"),
195 cl::init(2));
196
198 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
199 cl::desc("Maximum depth of recursive arithmetics"),
200 cl::init(32));
201
203 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
204 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
205
207 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
208 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
209 cl::init(8));
210
212 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
213 cl::desc("Max coefficients in AddRec during evolving"),
214 cl::init(8));
215
217 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
218 cl::desc("Size of the expression which is considered huge"),
219 cl::init(4096));
220
222 "scev-range-iter-threshold", cl::Hidden,
223 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
224 cl::init(32));
225
227 "scalar-evolution-max-loop-guard-collection-depth", cl::Hidden,
228 cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1));
229
230static cl::opt<bool>
231ClassifyExpressions("scalar-evolution-classify-expressions",
232 cl::Hidden, cl::init(true),
233 cl::desc("When printing analysis, include information on every instruction"));
234
236 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
237 cl::init(false),
238 cl::desc("Use more powerful methods of sharpening expression ranges. May "
239 "be costly in terms of compile time"));
240
241static cl::opt<bool>
242 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
243 cl::desc("Handle <= and >= in finite loops"),
244 cl::init(true));
245
247 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
248 cl::desc("Infer nuw/nsw flags using context where suitable"),
249 cl::init(true));
250
251//===----------------------------------------------------------------------===//
252// SCEV class definitions
253//===----------------------------------------------------------------------===//
254
256 // Leaf nodes are always their own canonical.
257 switch (getSCEVType()) {
258 case scConstant:
259 case scVScale:
260 case scUnknown:
261 CanonicalSCEV = this;
262 return;
263 default:
264 break;
265 }
266
267 // For all other expressions, check whether any immediate operand has a
268 // different canonical. Since operands are always created before their parent,
269 // their canonical pointers are already set — no recursion needed.
270 bool Changed = false;
272 for (SCEVUse Op : operands()) {
273 CanonOps.push_back(Op->getCanonical());
274 Changed |= CanonOps.back() != Op;
275 }
276
277 if (!Changed) {
278 CanonicalSCEV = this;
279 return;
280 }
281
282 // Rebuild the expression from the canonical operands, stripping use flags.
283 CanonicalSCEV = SE.getWithOperands(this, CanonOps);
284}
285
286//===----------------------------------------------------------------------===//
287// Implementation of the SCEV class.
288//
289
290#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
292 print(dbgs());
293 dbgs() << '\n';
294}
295#endif
296
297void SCEV::print(raw_ostream &OS) const {
298 switch (getSCEVType()) {
299 case scConstant:
300 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
301 return;
302 case scVScale:
303 OS << "vscale";
304 return;
305 case scPtrToAddr: {
306 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(this);
307 SCEVUse Op = PtrCast->getOperand();
308 OS << "(ptrtoaddr " << *Op->getType() << " " << Op << " to "
309 << *PtrCast->getType() << ")";
310 return;
311 }
312 case scTruncate: {
313 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
314 SCEVUse Op = Trunc->getOperand();
315 OS << "(trunc " << *Op->getType() << " " << Op << " to "
316 << *Trunc->getType() << ")";
317 return;
318 }
319 case scZeroExtend: {
321 SCEVUse Op = ZExt->getOperand();
322 OS << "(zext " << *Op->getType() << " " << Op << " to " << *ZExt->getType()
323 << ")";
324 return;
325 }
326 case scSignExtend: {
328 SCEVUse Op = SExt->getOperand();
329 OS << "(sext " << *Op->getType() << " " << Op << " to " << *SExt->getType()
330 << ")";
331 return;
332 }
333 case scAddRecExpr: {
334 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
335 OS << "{" << AR->getOperand(0);
336 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
337 OS << ",+," << AR->getOperand(i);
338 OS << "}<";
339 if (AR->hasNoUnsignedWrap())
340 OS << "nuw><";
341 if (AR->hasNoSignedWrap())
342 OS << "nsw><";
343 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
344 !AR->hasNoSignedWrap())
345 OS << "nw><";
346 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
347 OS << ">";
348 return;
349 }
350 case scAddExpr:
351 case scMulExpr:
352 case scUMaxExpr:
353 case scSMaxExpr:
354 case scUMinExpr:
355 case scSMinExpr:
357 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
358 const char *OpStr = nullptr;
359 switch (NAry->getSCEVType()) {
360 case scAddExpr: OpStr = " + "; break;
361 case scMulExpr: OpStr = " * "; break;
362 case scUMaxExpr: OpStr = " umax "; break;
363 case scSMaxExpr: OpStr = " smax "; break;
364 case scUMinExpr:
365 OpStr = " umin ";
366 break;
367 case scSMinExpr:
368 OpStr = " smin ";
369 break;
371 OpStr = " umin_seq ";
372 break;
373 default:
374 llvm_unreachable("There are no other nary expression types.");
375 }
376 OS << "(" << llvm::interleaved(NAry->operands(), OpStr) << ")";
377 switch (NAry->getSCEVType()) {
378 case scAddExpr:
379 case scMulExpr:
380 if (NAry->hasNoUnsignedWrap())
381 OS << "<nuw>";
382 if (NAry->hasNoSignedWrap())
383 OS << "<nsw>";
384 break;
385 default:
386 // Nothing to print for other nary expressions.
387 break;
388 }
389 return;
390 }
391 case scUDivExpr: {
392 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
393 OS << "(" << UDiv->getLHS() << " /u " << UDiv->getRHS() << ")";
394 return;
395 }
396 case scUnknown:
397 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
398 return;
400 OS << "***COULDNOTCOMPUTE***";
401 return;
402 }
403 llvm_unreachable("Unknown SCEV kind!");
404}
405
407 switch (getSCEVType()) {
408 case scConstant:
409 case scVScale:
410 case scUnknown:
411 return {};
412 case scPtrToAddr:
413 case scTruncate:
414 case scZeroExtend:
415 case scSignExtend:
416 return cast<SCEVCastExpr>(this)->operands();
417 case scAddRecExpr:
418 case scAddExpr:
419 case scMulExpr:
420 case scUMaxExpr:
421 case scSMaxExpr:
422 case scUMinExpr:
423 case scSMinExpr:
425 return cast<SCEVNAryExpr>(this)->operands();
426 case scUDivExpr:
427 return cast<SCEVUDivExpr>(this)->operands();
429 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
430 }
431 llvm_unreachable("Unknown SCEV kind!");
432}
433
434bool SCEV::isZero() const { return match(this, m_scev_Zero()); }
435
436bool SCEV::isOne() const { return match(this, m_scev_One()); }
437
438bool SCEV::isAllOnesValue() const { return match(this, m_scev_AllOnes()); }
439
442 if (!Mul) return false;
443
444 // If there is a constant factor, it will be first.
445 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
446 if (!SC) return false;
447
448 // Return true if the value is negative, this matches things like (-42 * V).
449 return SC->getAPInt().isNegative();
450}
451
454
456 return S->getSCEVType() == scCouldNotCompute;
457}
458
460 auto &Entry = ConstantSCEVs[V];
461 if (Entry)
462 return Entry;
463
466 ID.AddPointer(V);
468 if (SCEVConstant *S =
469 static_cast<SCEVConstant *>(UniqueSCEVs.lookup(ID, Token)))
470 return Entry = S;
471 SCEVConstant *S =
472 new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
473 UniqueSCEVs.insert(S, Token);
474 S->computeAndSetCanonical(*this);
475 return Entry = S;
476}
477
479 return getConstant(ConstantInt::get(getContext(), Val));
480}
481
482const SCEV *
485 // TODO: Avoid implicit trunc?
486 // See https://github.com/llvm/llvm-project/issues/112510.
487 return getConstant(
488 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
489}
490
494 ID.AddPointer(Ty);
496 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
497 return S;
498 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
499 UniqueSCEVs.insert(S, Token);
500 S->computeAndSetCanonical(*this);
501 return S;
502}
503
505 SCEV::NoWrapFlags Flags) {
506 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
507 if (EC.isScalable())
508 Res = getMulExpr(Res, getVScale(Ty), Flags);
509 return Res;
510}
511
513 SCEVUse op, Type *ty)
514 : SCEV(ID, SCEVTy, computeExpressionSize(op), ty), Op(op) {}
515
516SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
517 const SCEV *Op, Type *ITy)
518 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
519 assert(getOperand()->getType()->isPointerTy() && getType()->isIntegerTy() &&
520 "Must be a non-bit-width-changing pointer-to-integer cast!");
521}
522
527
528SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
529 Type *ty)
531 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
532 "Cannot truncate non-integer value!");
533}
534
535SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
536 Type *ty)
538 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
539 "Cannot zero extend non-integer value!");
540}
541
542SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
543 Type *ty)
545 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
546 "Cannot sign extend non-integer value!");
547}
548
550 // Clear this SCEVUnknown from various maps.
551 SE->forgetMemoizedResults({this});
552
553 // Remove this SCEVUnknown from the uniquing map.
554 SE->UniqueSCEVs.erase(this);
555
556 // Release the value.
557 setValPtr(nullptr);
558}
559
560void SCEVUnknown::allUsesReplacedWith(Value *New) {
561 // Clear this SCEVUnknown from various maps.
562 SE->forgetMemoizedResults({this});
563
564 // Remove this SCEVUnknown from the uniquing map.
565 SE->UniqueSCEVs.erase(this);
566
567 // Replace the value pointer in case someone is still using this SCEVUnknown.
568 setValPtr(New);
569}
570
571//===----------------------------------------------------------------------===//
572// SCEV Utilities
573//===----------------------------------------------------------------------===//
574
575/// Compare the two values \p LV and \p RV in terms of their "complexity" where
576/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
577/// operands in SCEV expressions.
578static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
579 Value *RV, unsigned Depth) {
581 return 0;
582
583 // Order pointer values after integer values. This helps SCEVExpander form
584 // GEPs.
585 bool LIsPointer = LV->getType()->isPointerTy(),
586 RIsPointer = RV->getType()->isPointerTy();
587 if (LIsPointer != RIsPointer)
588 return (int)LIsPointer - (int)RIsPointer;
589
590 // Compare getValueID values.
591 unsigned LID = LV->getValueID(), RID = RV->getValueID();
592 if (LID != RID)
593 return (int)LID - (int)RID;
594
595 // Sort arguments by their position.
596 if (const auto *LA = dyn_cast<Argument>(LV)) {
597 const auto *RA = cast<Argument>(RV);
598 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
599 return (int)LArgNo - (int)RArgNo;
600 }
601
602 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
603 const auto *RGV = cast<GlobalValue>(RV);
604
605 if (auto L = LGV->getLinkage() - RGV->getLinkage())
606 return L;
607
608 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
609 auto LT = GV->getLinkage();
610 return !(GlobalValue::isPrivateLinkage(LT) ||
612 };
613
614 // Use the names to distinguish the two values, but only if the
615 // names are semantically important.
616 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
617 return LGV->getName().compare(RGV->getName());
618 }
619
620 // For instructions, compare their loop depth, and their operand count. This
621 // is pretty loose.
622 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
623 const auto *RInst = cast<Instruction>(RV);
624
625 // Compare loop depths.
626 const BasicBlock *LParent = LInst->getParent(),
627 *RParent = RInst->getParent();
628 if (LParent != RParent) {
629 unsigned LDepth = LI->getLoopDepth(LParent),
630 RDepth = LI->getLoopDepth(RParent);
631 if (LDepth != RDepth)
632 return (int)LDepth - (int)RDepth;
633 }
634
635 // Compare the number of operands.
636 unsigned LNumOps = LInst->getNumOperands(),
637 RNumOps = RInst->getNumOperands();
638 if (LNumOps != RNumOps)
639 return (int)LNumOps - (int)RNumOps;
640
641 for (unsigned Idx : seq(LNumOps)) {
642 int Result = CompareValueComplexity(LI, LInst->getOperand(Idx),
643 RInst->getOperand(Idx), Depth + 1);
644 if (Result != 0)
645 return Result;
646 }
647 }
648
649 return 0;
650}
651
652// Return negative, zero, or positive, if LHS is less than, equal to, or greater
653// than RHS, respectively. A three-way result allows recursive comparisons to be
654// more efficient.
655// If the max analysis depth was reached, return std::nullopt, assuming we do
656// not know if they are equivalent for sure.
657static std::optional<int>
658CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS,
659 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
660 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
661 if (LHS == RHS)
662 return 0;
663
664 // Primarily, sort the SCEVs by their getSCEVType().
665 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
666 if (LType != RType)
667 return (int)LType - (int)RType;
668
670 return std::nullopt;
671
672 // Aside from the getSCEVType() ordering, the particular ordering
673 // isn't very important except that it's beneficial to be consistent,
674 // so that (a + b) and (b + a) don't end up as different expressions.
675 switch (LType) {
676 case scUnknown: {
677 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
678 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
679
680 int X =
681 CompareValueComplexity(LI, LU->getValue(), RU->getValue(), Depth + 1);
682 return X;
683 }
684
685 case scConstant: {
688
689 // Compare constant values.
690 const APInt &LA = LC->getAPInt();
691 const APInt &RA = RC->getAPInt();
692 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
693 if (LBitWidth != RBitWidth)
694 return (int)LBitWidth - (int)RBitWidth;
695 return LA.ult(RA) ? -1 : 1;
696 }
697
698 case scVScale: {
699 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
700 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
701 return LTy->getBitWidth() - RTy->getBitWidth();
702 }
703
704 case scAddRecExpr: {
707
708 // There is always a dominance between two recs that are used by one SCEV,
709 // so we can safely sort recs by loop header dominance. We require such
710 // order in getAddExpr.
711 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
712 if (LLoop != RLoop) {
713 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
714 assert(LHead != RHead && "Two loops share the same header?");
715 if (DT.dominates(LHead, RHead))
716 return 1;
717 assert(DT.dominates(RHead, LHead) &&
718 "No dominance between recurrences used by one SCEV?");
719 return -1;
720 }
721
722 [[fallthrough]];
723 }
724
725 case scTruncate:
726 case scZeroExtend:
727 case scSignExtend:
728 case scPtrToAddr:
729 case scAddExpr:
730 case scMulExpr:
731 case scUDivExpr:
732 case scSMaxExpr:
733 case scUMaxExpr:
734 case scSMinExpr:
735 case scUMinExpr:
737 ArrayRef<SCEVUse> LOps = LHS->operands();
738 ArrayRef<SCEVUse> ROps = RHS->operands();
739
740 // Lexicographically compare n-ary-like expressions.
741 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
742 if (LNumOps != RNumOps)
743 return (int)LNumOps - (int)RNumOps;
744
745 for (unsigned i = 0; i != LNumOps; ++i) {
746 auto X = CompareSCEVComplexity(LI, LOps[i].getPointer(),
747 ROps[i].getPointer(), DT, Depth + 1);
748 if (X != 0)
749 return X;
750 }
751 return 0;
752 }
753
755 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
756 }
757 llvm_unreachable("Unknown SCEV kind!");
758}
759
760/// Given a list of SCEV objects, order them by their complexity, and group
761/// objects of the same complexity together by value. When this routine is
762/// finished, we know that any duplicates in the vector are consecutive and that
763/// complexity is monotonically increasing.
764///
765/// Note that we go take special precautions to ensure that we get deterministic
766/// results from this routine. In other words, we don't want the results of
767/// this to depend on where the addresses of various SCEV objects happened to
768/// land in memory.
770 DominatorTree &DT) {
771 if (Ops.size() < 2) return; // Noop
772
773 // Whether LHS has provably less complexity than RHS.
774 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
775 auto Complexity = CompareSCEVComplexity(LI, LHS, RHS, DT);
776 return Complexity && *Complexity < 0;
777 };
778 if (Ops.size() == 2) {
779 // This is the common case, which also happens to be trivially simple.
780 // Special case it.
781 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
782 if (IsLessComplex(RHS, LHS))
783 std::swap(LHS, RHS);
784 return;
785 }
786
787 // Do the rough sort by complexity.
789 Ops, [&](SCEVUse LHS, SCEVUse RHS) { return IsLessComplex(LHS, RHS); });
790
791 // Now that we are sorted by complexity, group elements of the same
792 // complexity. Note that this is, at worst, N^2, but the vector is likely to
793 // be extremely short in practice. Note that we take this approach because we
794 // do not want to depend on the addresses of the objects we are grouping.
795 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
796 const SCEV *S = Ops[i];
797 unsigned Complexity = S->getSCEVType();
798
799 // If there are any objects of the same complexity and same value as this
800 // one, group them.
801 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
802 if (Ops[j] == S) { // Found a duplicate.
803 // Move it to immediately after i'th element.
804 std::swap(Ops[i+1], Ops[j]);
805 ++i; // no need to rescan it.
806 if (i == e-2) return; // Done!
807 }
808 }
809 }
810}
811
812/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
813/// least HugeExprThreshold nodes).
815 return any_of(Ops, [](const SCEV *S) {
817 });
818}
819
820/// Performs a number of common optimizations on the passed \p Ops. If the
821/// whole expression reduces down to a single operand, it will be returned.
822///
823/// The following optimizations are performed:
824/// * Fold constants using the \p Fold function.
825/// * Remove identity constants satisfying \p IsIdentity.
826/// * If a constant satisfies \p IsAbsorber, return it.
827/// * Sort operands by complexity.
828template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
829static const SCEV *
831 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
832 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
833 const SCEVConstant *Folded = nullptr;
834 for (unsigned Idx = 0; Idx < Ops.size();) {
835 const SCEV *Op = Ops[Idx];
836 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
837 if (!Folded)
838 Folded = C;
839 else
840 Folded = cast<SCEVConstant>(
841 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
842 Ops.erase(Ops.begin() + Idx);
843 continue;
844 }
845 ++Idx;
846 }
847
848 if (Ops.empty()) {
849 assert(Folded && "Must have folded value");
850 return Folded;
851 }
852
853 if (Folded && IsAbsorber(Folded->getAPInt()))
854 return Folded;
855
856 GroupByComplexity(Ops, &LI, DT);
857 if (Folded && !IsIdentity(Folded->getAPInt()))
858 Ops.insert(Ops.begin(), Folded);
859
860 return Ops.size() == 1 ? Ops[0] : nullptr;
861}
862
863//===----------------------------------------------------------------------===//
864// Simple SCEV method implementations
865//===----------------------------------------------------------------------===//
866
867/// Compute BC(It, K). The result has width W. Assume, K > 0.
868static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
869 ScalarEvolution &SE,
870 Type *ResultTy) {
871 // Handle the simplest case efficiently.
872 if (K == 1)
873 return SE.getTruncateOrZeroExtend(It, ResultTy);
874
875 // We are using the following formula for BC(It, K):
876 //
877 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
878 //
879 // Suppose, W is the bitwidth of the return value. We must be prepared for
880 // overflow. Hence, we must assure that the result of our computation is
881 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
882 // safe in modular arithmetic.
883 //
884 // However, this code doesn't use exactly that formula; the formula it uses
885 // is something like the following, where T is the number of factors of 2 in
886 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
887 // exponentiation:
888 //
889 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
890 //
891 // This formula is trivially equivalent to the previous formula. However,
892 // this formula can be implemented much more efficiently. The trick is that
893 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
894 // arithmetic. To do exact division in modular arithmetic, all we have
895 // to do is multiply by the inverse. Therefore, this step can be done at
896 // width W.
897 //
898 // The next issue is how to safely do the division by 2^T. The way this
899 // is done is by doing the multiplication step at a width of at least W + T
900 // bits. This way, the bottom W+T bits of the product are accurate. Then,
901 // when we perform the division by 2^T (which is equivalent to a right shift
902 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
903 // truncated out after the division by 2^T.
904 //
905 // In comparison to just directly using the first formula, this technique
906 // is much more efficient; using the first formula requires W * K bits,
907 // but this formula less than W + K bits. Also, the first formula requires
908 // a division step, whereas this formula only requires multiplies and shifts.
909 //
910 // It doesn't matter whether the subtraction step is done in the calculation
911 // width or the input iteration count's width; if the subtraction overflows,
912 // the result must be zero anyway. We prefer here to do it in the width of
913 // the induction variable because it helps a lot for certain cases; CodeGen
914 // isn't smart enough to ignore the overflow, which leads to much less
915 // efficient code if the width of the subtraction is wider than the native
916 // register width.
917 //
918 // (It's possible to not widen at all by pulling out factors of 2 before
919 // the multiplication; for example, K=2 can be calculated as
920 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
921 // extra arithmetic, so it's not an obvious win, and it gets
922 // much more complicated for K > 3.)
923
924 // Protection from insane SCEVs; this bound is conservative,
925 // but it probably doesn't matter.
926 if (K > 1000)
927 return SE.getCouldNotCompute();
928
929 unsigned W = SE.getTypeSizeInBits(ResultTy);
930
931 // Calculate K! / 2^T and T; we divide out the factors of two before
932 // multiplying for calculating K! / 2^T to avoid overflow.
933 // Other overflow doesn't matter because we only care about the bottom
934 // W bits of the result.
935 APInt OddFactorial(W, 1);
936 unsigned T = 1;
937 for (unsigned i = 3; i <= K; ++i) {
938 unsigned TwoFactors = countr_zero(i);
939 T += TwoFactors;
940 OddFactorial *= (i >> TwoFactors);
941 }
942
943 // We need at least W + T bits for the multiplication step
944 unsigned CalculationBits = W + T;
945
946 // Calculate 2^T, at width T+W.
947 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
948
949 // Calculate the multiplicative inverse of K! / 2^T;
950 // this multiplication factor will perform the exact division by
951 // K! / 2^T.
952 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
953
954 // Calculate the product, at width T+W
955 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
956 CalculationBits);
957 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
958 for (unsigned i = 1; i != K; ++i) {
959 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
960 Dividend = SE.getMulExpr(Dividend,
961 SE.getTruncateOrZeroExtend(S, CalculationTy));
962 }
963
964 // Divide by 2^T
965 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
966
967 // Truncate the result, and divide by K! / 2^T.
968
969 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
970 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
971}
972
973/// Return the value of this chain of recurrences at the specified iteration
974/// number. We can evaluate this recurrence by multiplying each element in the
975/// chain by the binomial coefficient corresponding to it. In other words, we
976/// can evaluate {A,+,B,+,C,+,D} as:
977///
978/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
979///
980/// where BC(It, k) stands for binomial coefficient.
982 ScalarEvolution &SE) const {
983 return evaluateAtIteration(operands(), It, SE);
984}
985
987 const SCEV *It,
988 ScalarEvolution &SE) {
989 assert(Operands.size() > 0);
990 const SCEV *Result = Operands[0].getPointer();
991 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
992 // The computation is correct in the face of overflow provided that the
993 // multiplication is performed _after_ the evaluation of the binomial
994 // coefficient.
995 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
996 if (isa<SCEVCouldNotCompute>(Coeff))
997 return Coeff;
998
999 Result =
1000 SE.getAddExpr(Result, SE.getMulExpr(Operands[i].getPointer(), Coeff));
1001 }
1002 return Result;
1003}
1004
1005//===----------------------------------------------------------------------===//
1006// SCEV Expression folder implementations
1007//===----------------------------------------------------------------------===//
1008
1009/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
1010/// which computes a pointer-typed value, and rewrites the whole expression
1011/// tree so that *all* the computations are done on integers, and the only
1012/// pointer-typed operands in the expression are SCEVUnknown.
1013/// The CreatePtrCast callback is invoked to create the actual conversion
1014/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
1016 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1018 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1019 Type *TargetTy;
1020 ConversionFn CreatePtrCast;
1021
1022public:
1024 ConversionFn CreatePtrCast)
1025 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1026
1027 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1028 Type *TargetTy, ConversionFn CreatePtrCast) {
1029 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1030 return Rewriter.visit(Scev);
1031 }
1032
1033 const SCEV *visit(const SCEV *S) {
1034 Type *STy = S->getType();
1035 // If the expression is not pointer-typed, just keep it as-is.
1036 if (!STy->isPointerTy())
1037 return S;
1038 // Else, recursively sink the cast down into it.
1039 return Base::visit(S);
1040 }
1041
1042 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1043 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1044 // implementation drops.
1046 bool Changed = false;
1047 for (SCEVUse Op : Expr->operands()) {
1048 Operands.push_back(visit(Op.getPointer()));
1049 Changed |= Op.getPointer() != Operands.back();
1050 }
1051 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1052 }
1053
1054 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1055 assert(Expr->getType()->isPointerTy() &&
1056 "Should only reach pointer-typed SCEVUnknown's.");
1057 // Perform some basic constant folding. If the operand of the cast is a
1058 // null pointer, don't create a cast SCEV expression (that will be left
1059 // as-is), but produce a zero constant.
1061 return SE.getZero(TargetTy);
1062 return CreatePtrCast(Expr);
1063 }
1064};
1065
1067 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1068
1069 // Treat pointers with unstable representation conservatively, since the
1070 // address bits may change.
1071 if (DL.hasUnstableRepresentation(Op->getType()))
1072 return getCouldNotCompute();
1073
1074 Type *Ty = DL.getAddressType(Op->getType());
1075
1076 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1077 // The rewriter handles null pointer constant folding.
1079 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1082 ID.AddPointer(U);
1083 ID.AddPointer(Ty);
1085 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1086 return S;
1087 SCEV *S = new (SCEVAllocator)
1088 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1089 UniqueSCEVs.insert(S, Token);
1090 S->computeAndSetCanonical(*this);
1091 registerUser(S, U);
1092 return static_cast<const SCEV *>(S);
1093 });
1094 assert(IntOp->getType()->isIntegerTy() &&
1095 "We must have succeeded in sinking the cast, "
1096 "and ending up with an integer-typed expression!");
1097 return IntOp;
1098}
1099
1101 unsigned Depth) {
1102 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1103 "This is not a truncating conversion!");
1104 assert(isSCEVable(Ty) &&
1105 "This is not a conversion to a SCEVable type!");
1106 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1107 Ty = getEffectiveSCEVType(Ty);
1108
1111 ID.AddPointer(Op.getOpaqueValue());
1112 ID.AddPointer(Ty);
1114 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1115 return S;
1116
1117 // Fold if the operand is constant.
1118 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1119 return getConstant(
1120 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1121
1122 // trunc(trunc(x)) --> trunc(x)
1124 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1125
1126 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1128 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1129
1130 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1132 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1133
1134 if (Depth > MaxCastDepth) {
1135 SCEV *S =
1136 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1137 UniqueSCEVs.insert(S, Token);
1138 S->computeAndSetCanonical(*this);
1139 registerUser(S, Op);
1140 return S;
1141 }
1142
1143 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1144 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1145 // if after transforming we have at most one truncate, not counting truncates
1146 // that replace other casts.
1148 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1150 unsigned numTruncs = 0;
1151 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1152 ++i) {
1153 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1154 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1156 numTruncs++;
1157 Operands.push_back(S);
1158 }
1159 if (numTruncs < 2) {
1160 if (isa<SCEVAddExpr>(Op))
1161 return getAddExpr(Operands);
1162 if (isa<SCEVMulExpr>(Op))
1163 return getMulExpr(Operands);
1164 llvm_unreachable("Unexpected SCEV type for Op.");
1165 }
1166 // Although we checked in the beginning that ID is not in the cache, it is
1167 // possible that during recursion and different modification ID was inserted
1168 // into the cache. So if we find it, just return it.
1169 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1170 return S;
1171 }
1172
1173 // If the input value is a chrec scev, truncate the chrec's operands.
1174 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1176 for (const SCEV *Op : AddRec->operands())
1177 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1178 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1179 }
1180
1181 // Return zero if truncating to known zeros.
1182 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1183 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1184 return getZero(Ty);
1185
1186 // The cast wasn't folded; create an explicit cast node. We can reuse
1187 // the existing insert position since if we get here, we won't have
1188 // made any changes which would invalidate it.
1189 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1190 Op, Ty);
1191 UniqueSCEVs.insert(S, Token);
1192 S->computeAndSetCanonical(*this);
1193 registerUser(S, Op);
1194 return S;
1195}
1196
1197// Get the limit of a recurrence such that incrementing by Step cannot cause
1198// signed overflow as long as the value of the recurrence within the
1199// loop does not exceed this limit before incrementing.
1200static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1201 ICmpInst::Predicate *Pred,
1202 ScalarEvolution *SE) {
1203 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1204 if (SE->isKnownPositive(Step)) {
1205 *Pred = ICmpInst::ICMP_SLT;
1207 SE->getSignedRangeMax(Step));
1208 }
1209 if (SE->isKnownNegative(Step)) {
1210 *Pred = ICmpInst::ICMP_SGT;
1212 SE->getSignedRangeMin(Step));
1213 }
1214 return nullptr;
1215}
1216
1217// Get the limit of a recurrence such that incrementing by Step cannot cause
1218// unsigned overflow as long as the value of the recurrence within the loop does
1219// not exceed this limit before incrementing.
1221 ICmpInst::Predicate *Pred,
1222 ScalarEvolution *SE) {
1223 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1224 *Pred = ICmpInst::ICMP_ULT;
1225
1227 SE->getUnsignedRangeMax(Step));
1228}
1229
1230namespace {
1231
1232struct ExtendOpTraitsBase {
1233 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(SCEVUse, Type *,
1234 unsigned);
1235};
1236
1237// Used to make code generic over signed and unsigned overflow.
1238template <typename ExtendOp> struct ExtendOpTraits {
1239 // Members present:
1240 //
1241 // static const SCEV::NoWrapFlags WrapType;
1242 //
1243 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1244 //
1245 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1246 // ICmpInst::Predicate *Pred,
1247 // ScalarEvolution *SE);
1248};
1249
1250template <>
1251struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1252 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1253
1254 static const GetExtendExprTy GetExtendExpr;
1255
1256 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1257 ICmpInst::Predicate *Pred,
1258 ScalarEvolution *SE) {
1259 return getSignedOverflowLimitForStep(Step, Pred, SE);
1260 }
1261};
1262
1263const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1265
1266template <>
1267struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1268 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1269
1270 static const GetExtendExprTy GetExtendExpr;
1271
1272 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1273 ICmpInst::Predicate *Pred,
1274 ScalarEvolution *SE) {
1275 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1276 }
1277};
1278
1279const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1281
1282} // end anonymous namespace
1283
1284// The recurrence AR has been shown to have no signed/unsigned wrap or something
1285// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1286// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1287// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1288// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1289// expression "Step + sext/zext(PreIncAR)" is congruent with
1290// "sext/zext(PostIncAR)"
1291template <typename ExtendOpTy>
1293 ScalarEvolution *SE, unsigned Depth) {
1294 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1295 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1296
1297 const Loop *L = AR->getLoop();
1298 const SCEV *Start = AR->getStart();
1299 const SCEV *Step = AR->getStepRecurrence(*SE);
1300
1301 // Check for a simple looking step prior to loop entry.
1302 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1303 if (!SA)
1304 return nullptr;
1305
1306 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1307 // subtraction is expensive. For this purpose, perform a quick and dirty
1308 // difference, by checking for Step in the operand list. Note, that
1309 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1310 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1311 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1312 if (*It == Step) {
1313 DiffOps.erase(It);
1314 break;
1315 }
1316
1317 if (DiffOps.size() == SA->getNumOperands())
1318 return nullptr;
1319
1320 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1321 // `Step`:
1322
1323 // 1. NSW/NUW flags on the step increment.
1324 auto PreStartFlags =
1326 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1328 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1329
1330 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1331 // "S+X does not sign/unsign-overflow".
1332 //
1333
1334 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1335 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1336 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1337 return PreStart;
1338
1339 // 2. Direct overflow check on the step operation's expression.
1340 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1341 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1342 const SCEV *OperandExtendedStart =
1343 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1344 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1345 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1346 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1347 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1348 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1349 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1350 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1351 }
1352 return PreStart;
1353 }
1354
1355 // 3. Loop precondition.
1357 const SCEV *OverflowLimit =
1358 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1359
1360 if (OverflowLimit &&
1361 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1362 return PreStart;
1363
1364 return nullptr;
1365}
1366
1367// Get the normalized zero or sign extended expression for this AddRec's Start.
1368template <typename ExtendOpTy>
1369static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1370 ScalarEvolution *SE,
1371 unsigned Depth) {
1372 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1373
1374 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, SE, Depth);
1375 if (!PreStart)
1376 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1377
1378 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1379 Depth),
1380 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1381}
1382
1383// Try to prove away overflow by looking at "nearby" add recurrences. A
1384// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1385// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1386//
1387// Formally:
1388//
1389// {S,+,X} == {S-T,+,X} + T
1390// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1391//
1392// If ({S-T,+,X} + T) does not overflow ... (1)
1393//
1394// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1395//
1396// If {S-T,+,X} does not overflow ... (2)
1397//
1398// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1399// == {Ext(S-T)+Ext(T),+,Ext(X)}
1400//
1401// If (S-T)+T does not overflow ... (3)
1402//
1403// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1404// == {Ext(S),+,Ext(X)} == LHS
1405//
1406// Thus, if (1), (2) and (3) are true for some T, then
1407// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1408//
1409// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1410// does not overflow" restricted to the 0th iteration. Therefore we only need
1411// to check for (1) and (2).
1412//
1413// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1414// is `Delta` (defined below).
1415template <typename ExtendOpTy>
1416bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1417 const SCEV *Step,
1418 const Loop *L) {
1419 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1420
1421 // We restrict `Start` to a constant to prevent SCEV from spending too much
1422 // time here. It is correct (but more expensive) to continue with a
1423 // non-constant `Start` and do a general SCEV subtraction to compute
1424 // `PreStart` below.
1425 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1426 if (!StartC)
1427 return false;
1428
1429 APInt StartAI = StartC->getAPInt();
1430
1431 for (unsigned Delta : {-2, -1, 1, 2}) {
1432 const SCEV *PreStart = getConstant(StartAI - Delta);
1433
1434 FoldingSetNodeID ID;
1435 ID.AddInteger(scAddRecExpr);
1436 ID.AddPointer(PreStart);
1437 ID.AddPointer(Step);
1438 ID.AddPointer(L);
1439 FoldingSetInsertToken Token;
1440 const auto *PreAR =
1441 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
1442
1443 // Give up if we don't already have the add recurrence we need because
1444 // actually constructing an add recurrence is relatively expensive.
1445 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1446 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1448 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1449 DeltaS, &Pred, this);
1450 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1451 return true;
1452 }
1453 }
1454
1455 return false;
1456}
1457
1458// Finds an integer D for an expression (C + x + y + ...) such that the top
1459// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1460// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1461// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1462// the (C + x + y + ...) expression is \p WholeAddExpr.
1464 const SCEVConstant *ConstantTerm,
1465 const SCEVAddExpr *WholeAddExpr) {
1466 const APInt &C = ConstantTerm->getAPInt();
1467 const unsigned BitWidth = C.getBitWidth();
1468 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1469 uint32_t TZ = BitWidth;
1470 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1471 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1472 if (TZ) {
1473 // Set D to be as many least significant bits of C as possible while still
1474 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1475 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1476 }
1477 return APInt(BitWidth, 0);
1478}
1479
1480// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1481// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1482// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1483// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1485 const APInt &ConstantStart,
1486 const SCEV *Step) {
1487 const unsigned BitWidth = ConstantStart.getBitWidth();
1488 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1489 if (TZ)
1490 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1491 : ConstantStart;
1492 return APInt(BitWidth, 0);
1493}
1494
1496 const ScalarEvolution::FoldID &ID, const SCEV *S,
1499 &FoldCacheUser) {
1500 auto I = FoldCache.insert({ID, S});
1501 if (!I.second) {
1502 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1503 // entry.
1504 auto &UserIDs = FoldCacheUser[I.first->second];
1505 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1506 for (unsigned I = 0; I != UserIDs.size(); ++I)
1507 if (UserIDs[I] == ID) {
1508 std::swap(UserIDs[I], UserIDs.back());
1509 break;
1510 }
1511 UserIDs.pop_back();
1512 I.first->second = S;
1513 }
1514 FoldCacheUser[S].push_back(ID);
1515}
1516
1518 unsigned Depth) {
1519 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1520 "This is not an extending conversion!");
1521 assert(isSCEVable(Ty) &&
1522 "This is not a conversion to a SCEVable type!");
1523 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1524 Ty = getEffectiveSCEVType(Ty);
1525
1526 FoldID ID(scZeroExtend, Op, Ty);
1527 if (const SCEV *S = FoldCache.lookup(ID))
1528 return S;
1529
1530 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1532 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1533 return S;
1534}
1535
1537 unsigned Depth) {
1538 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1539 "This is not an extending conversion!");
1540 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1541 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1542
1543 // Fold if the operand is constant.
1544 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1545 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1546
1547 // zext(zext(x)) --> zext(x)
1549 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1550
1551 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1552 // zero-extension distributes over the recurrence.
1553 const SCEV *Start, *Step;
1554 const Loop *L;
1555 if (Depth <= MaxCastDepth &&
1556 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1557 const auto *AR = cast<SCEVAddRecExpr>(Op);
1558 if (AR->hasNoUnsignedWrap()) {
1559 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1560 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1561 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1562 }
1563 }
1564
1565 // Before doing any expensive analysis, check to see if we've already
1566 // computed a SCEV for this Op and Ty.
1569 ID.AddPointer(Op.getOpaqueValue());
1570 ID.AddPointer(Ty);
1572 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1573 return S;
1574 if (Depth > MaxCastDepth) {
1575 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1576 Op, Ty);
1577 UniqueSCEVs.insert(S, Token);
1578 S->computeAndSetCanonical(*this);
1579 registerUser(S, Op);
1580 return S;
1581 }
1582
1583 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1585 // It's possible the bits taken off by the truncate were all zero bits. If
1586 // so, we should be able to simplify this further.
1587 const SCEV *X = ST->getOperand();
1589 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1590 unsigned NewBits = getTypeSizeInBits(Ty);
1591 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1592 CR.zextOrTrunc(NewBits)))
1593 return getTruncateOrZeroExtend(X, Ty, Depth);
1594 }
1595
1596 // If the input value is a chrec scev, and we can prove that the value
1597 // did not overflow the old, smaller, value, we can zero extend all of the
1598 // operands (often constants). This allows analysis of something like
1599 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1600 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1601 const auto *AR = cast<SCEVAddRecExpr>(Op);
1602 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1603
1604 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1605
1606 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1607 // Note that this serves two purposes: It filters out loops that are
1608 // simply not analyzable, and it covers the case where this code is
1609 // being called from within backedge-taken count analysis, such that
1610 // attempting to ask for the backedge-taken count would likely result
1611 // in infinite recursion. In the later case, the analysis code will
1612 // cope with a conservative value, and it will take care to purge
1613 // that value once it has finished.
1614 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1615 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1616 // Manually compute the final value for AR, checking for overflow.
1617
1618 // Check whether the backedge-taken count can be losslessly casted to
1619 // the addrec's type. The count is always unsigned.
1620 const SCEV *CastedMaxBECount =
1621 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1622 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1623 CastedMaxBECount, MaxBECount->getType(), Depth);
1624 if (MaxBECount == RecastedMaxBECount) {
1625 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1626 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1627 const SCEV *ZMul =
1628 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
1629 const SCEV *ZAdd = getZeroExtendExpr(
1630 getAddExpr(Start, ZMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
1631 Depth + 1);
1632 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1633 const SCEV *WideMaxBECount =
1634 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1635 const SCEV *OperandExtendedAdd =
1636 getAddExpr(WideStart,
1637 getMulExpr(WideMaxBECount,
1638 getZeroExtendExpr(Step, WideTy, Depth + 1),
1641 if (ZAdd == OperandExtendedAdd) {
1642 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1643 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1644 // Return the expression with the addrec on the outside.
1645 Start =
1647 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1648 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1649 }
1650 // Similar to above, only this time treat the step value as signed.
1651 // This covers loops that count down.
1652 OperandExtendedAdd =
1653 getAddExpr(WideStart,
1654 getMulExpr(WideMaxBECount,
1655 getSignExtendExpr(Step, WideTy, Depth + 1),
1658 if (ZAdd == OperandExtendedAdd) {
1659 // Cache knowledge of AR NW, which is propagated to this AddRec.
1660 // Negative step causes unsigned wrap, but it still can't self-wrap.
1661 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1662 // Return the expression with the addrec on the outside.
1663 Start =
1665 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1666 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1667 }
1668 }
1669 }
1670
1671 // Normally, in the cases we can prove no-overflow via a
1672 // backedge guarding condition, we can also compute a backedge
1673 // taken count for the loop. The exceptions are assumptions and
1674 // guards present in the loop -- SCEV is not great at exploiting
1675 // these to compute max backedge taken counts, but can still use
1676 // these to prove lack of overflow. Use this fact to avoid
1677 // doing extra work that may not pay off.
1678 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1679 !AC.assumptions().empty()) {
1680
1681 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1682 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1683 if (AR->hasNoUnsignedWrap()) {
1684 // Same as nuw case above - duplicated here to avoid a compile time
1685 // issue. It's not clear that the order of checks does matter, but
1686 // it's one of two issue possible causes for a change which was
1687 // reverted. Be conservative for the moment.
1688 Start =
1690 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1691 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1692 }
1693
1694 // For a negative step, we can extend the operands iff doing so only
1695 // traverses values in the range zext([0,UINT_MAX]).
1696 if (isKnownNegative(Step)) {
1697 const SCEV *N =
1701 // Cache knowledge of AR NW, which is propagated to this
1702 // AddRec. Negative step causes unsigned wrap, but it
1703 // still can't self-wrap.
1704 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1705 // Return the expression with the addrec on the outside.
1706 Start =
1708 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1709 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1710 }
1711 }
1712 }
1713
1714 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1715 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1716 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1717 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1718 const APInt &C = SC->getAPInt();
1719 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1720 if (D != 0) {
1721 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1722 const SCEV *SResidual =
1723 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1724 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1725 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1726 Depth + 1);
1727 }
1728 }
1729
1730 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1731 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1732 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1733 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1734 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1735 }
1736 }
1737
1738 // zext(A % B) --> zext(A) % zext(B)
1739 {
1740 const SCEV *LHS;
1741 const SCEV *RHS;
1742 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1743 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1744 getZeroExtendExpr(RHS, Ty, Depth + 1));
1745 }
1746
1747 // zext(A / B) --> zext(A) / zext(B).
1748 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1749 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1750 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1751
1752 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1753 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1754 if (SA->hasNoUnsignedWrap()) {
1755 // If the addition does not unsign overflow then we can, by definition,
1756 // commute the zero extension with the addition operation.
1758 for (SCEVUse Op : SA->operands())
1759 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1760 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1761 }
1762
1763 const APInt *C, *C2;
1764 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1765 // Currently the non-negative check is done manually, as isKnownNonNegative
1766 // is too expensive.
1767 if (SA->hasNoSignedWrap() &&
1769 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1770 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1771 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1772 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1773 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1774 SCEV::FlagNSW, Depth + 1);
1775 }
1776
1777 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1778 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1779 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1780 //
1781 // Often address arithmetics contain expressions like
1782 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1783 // This transformation is useful while proving that such expressions are
1784 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1785 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1786 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1787 if (D != 0) {
1788 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1789 const SCEV *SResidual =
1791 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1792 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1793 Depth + 1);
1794 }
1795 }
1796 }
1797
1798 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1799 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1800 if (SM->hasNoUnsignedWrap()) {
1801 // If the multiply does not unsign overflow then we can, by definition,
1802 // commute the zero extension with the multiply operation.
1804 for (SCEVUse Op : SM->operands())
1805 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1806 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1807 }
1808
1809 // zext(2^K * (trunc X to iN)) to iM ->
1810 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1811 //
1812 // Proof:
1813 //
1814 // zext(2^K * (trunc X to iN)) to iM
1815 // = zext((trunc X to iN) << K) to iM
1816 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1817 // (because shl removes the top K bits)
1818 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1819 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1820 //
1821 const APInt *C;
1822 const SCEV *TruncRHS;
1823 if (match(SM,
1824 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1825 C->isPowerOf2()) {
1826 int NewTruncBits =
1827 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1828 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1829 return getMulExpr(
1830 getZeroExtendExpr(SM->getOperand(0), Ty),
1831 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1832 SCEV::FlagNUW, Depth + 1);
1833 }
1834 }
1835
1836 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1837 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1841 for (SCEVUse Operand : MinMax->operands())
1842 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1844 return getUMinExpr(Operands);
1845 return getUMaxExpr(Operands);
1846 }
1847
1848 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1850 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1852 for (SCEVUse Operand : MinMax->operands())
1853 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1854 return getUMinExpr(Operands, /*Sequential*/ true);
1855 }
1856
1857 // The cast wasn't folded; create an explicit cast node.
1858 // Recompute the insert position, as it may have been invalidated.
1859 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1860 return S;
1861 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1862 Op, Ty);
1863 UniqueSCEVs.insert(S, Token);
1864 S->computeAndSetCanonical(*this);
1865 registerUser(S, Op);
1866 return S;
1867}
1868
1870 unsigned Depth) {
1871 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1872 "This is not an extending conversion!");
1873 assert(isSCEVable(Ty) &&
1874 "This is not a conversion to a SCEVable type!");
1875 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1876 Ty = getEffectiveSCEVType(Ty);
1877
1878 FoldID ID(scSignExtend, Op, Ty);
1879 if (const SCEV *S = FoldCache.lookup(ID))
1880 return S;
1881
1882 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1884 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1885 return S;
1886}
1887
1889 unsigned Depth) {
1890 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1891 "This is not an extending conversion!");
1892 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1893 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1894 Ty = getEffectiveSCEVType(Ty);
1895
1896 // Fold if the operand is constant.
1897 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1898 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1899
1900 // sext(sext(x)) --> sext(x)
1902 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1903
1904 // sext(zext(x)) --> zext(x)
1906 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1907
1908 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1909 // sign-extension distributes over the recurrence.
1910 const SCEV *Start, *Step;
1911 const Loop *L;
1912 if (Depth <= MaxCastDepth &&
1913 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1914 const auto *AR = cast<SCEVAddRecExpr>(Op);
1915 if (AR->hasNoSignedWrap()) {
1916 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1917 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1918 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1919 }
1920 }
1921
1922 // Before doing any expensive analysis, check to see if we've already
1923 // computed a SCEV for this Op and Ty.
1926 ID.AddPointer(Op.getOpaqueValue());
1927 ID.AddPointer(Ty);
1929 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1930 return S;
1931 // Limit recursion depth.
1932 if (Depth > MaxCastDepth) {
1933 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1934 Op, Ty);
1935 UniqueSCEVs.insert(S, Token);
1936 S->computeAndSetCanonical(*this);
1937 registerUser(S, Op);
1938 return S;
1939 }
1940
1941 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1943 // It's possible the bits taken off by the truncate were all sign bits. If
1944 // so, we should be able to simplify this further.
1945 const SCEV *X = ST->getOperand();
1947 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1948 unsigned NewBits = getTypeSizeInBits(Ty);
1949 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1950 CR.sextOrTrunc(NewBits)))
1951 return getTruncateOrSignExtend(X, Ty, Depth);
1952 }
1953
1954 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1955 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1956 if (SA->hasNoSignedWrap()) {
1957 // If the addition does not sign overflow then we can, by definition,
1958 // commute the sign extension with the addition operation.
1960 for (SCEVUse Op : SA->operands())
1961 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1962 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1963 }
1964
1965 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1966 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1967 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1968 //
1969 // For instance, this will bring two seemingly different expressions:
1970 // 1 + sext(5 + 20 * %x + 24 * %y) and
1971 // sext(6 + 20 * %x + 24 * %y)
1972 // to the same form:
1973 // 2 + sext(4 + 20 * %x + 24 * %y)
1974 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1975 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1976 if (D != 0) {
1977 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1978 const SCEV *SResidual =
1980 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1981 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1982 Depth + 1);
1983 }
1984 }
1985 }
1986 // If the input value is a chrec scev, and we can prove that the value
1987 // did not overflow the old, smaller, value, we can sign extend all of the
1988 // operands (often constants). This allows analysis of something like
1989 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1990 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1991 const auto *AR = cast<SCEVAddRecExpr>(Op);
1992 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1993
1994 // The no-signed-wrap case is handled before the uniquing lookup above.
1995
1996 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1997 // Note that this serves two purposes: It filters out loops that are
1998 // simply not analyzable, and it covers the case where this code is
1999 // being called from within backedge-taken count analysis, such that
2000 // attempting to ask for the backedge-taken count would likely result
2001 // in infinite recursion. In the later case, the analysis code will
2002 // cope with a conservative value, and it will take care to purge
2003 // that value once it has finished.
2004 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2005 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2006 // Manually compute the final value for AR, checking for
2007 // overflow.
2008
2009 // Check whether the backedge-taken count can be losslessly casted to
2010 // the addrec's type. The count is always unsigned.
2011 const SCEV *CastedMaxBECount =
2012 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2013 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2014 CastedMaxBECount, MaxBECount->getType(), Depth);
2015 if (MaxBECount == RecastedMaxBECount) {
2016 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2017 // Check whether Start+Step*MaxBECount has no signed overflow.
2018 const SCEV *SMul =
2019 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
2020 const SCEV *SAdd = getSignExtendExpr(
2021 getAddExpr(Start, SMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
2022 Depth + 1);
2023 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2024 const SCEV *WideMaxBECount =
2025 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2026 const SCEV *OperandExtendedAdd =
2027 getAddExpr(WideStart,
2028 getMulExpr(WideMaxBECount,
2029 getSignExtendExpr(Step, WideTy, Depth + 1),
2032 if (SAdd == OperandExtendedAdd) {
2033 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2034 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2035 // Return the expression with the addrec on the outside.
2036 Start =
2038 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2039 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2040 }
2041 // Similar to above, only this time treat the step value as unsigned.
2042 // This covers loops that count up with an unsigned step.
2043 OperandExtendedAdd =
2044 getAddExpr(WideStart,
2045 getMulExpr(WideMaxBECount,
2046 getZeroExtendExpr(Step, WideTy, Depth + 1),
2049 if (SAdd == OperandExtendedAdd) {
2050 // If AR wraps around then
2051 //
2052 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2053 // => SAdd != OperandExtendedAdd
2054 //
2055 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2056 // (SAdd == OperandExtendedAdd => AR is NW)
2057
2058 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2059
2060 // Return the expression with the addrec on the outside.
2061 Start =
2063 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2064 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2065 }
2066 }
2067 }
2068
2069 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2070 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2071 if (AR->hasNoSignedWrap()) {
2072 // Same as nsw case above - duplicated here to avoid a compile time
2073 // issue. It's not clear that the order of checks does matter, but
2074 // it's one of two issue possible causes for a change which was
2075 // reverted. Be conservative for the moment.
2076 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2077 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2078 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2079 }
2080
2081 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2082 // if D + (C - D + Step * n) could be proven to not signed wrap
2083 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2084 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2085 const APInt &C = SC->getAPInt();
2086 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2087 if (D != 0) {
2088 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2089 const SCEV *SResidual =
2090 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2091 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2092 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2093 Depth + 1);
2094 }
2095 }
2096
2097 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2098 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2099 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2100 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2101 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2102 }
2103 }
2104
2105 // If the input value is provably positive and we could not simplify
2106 // away the sext build a zext instead.
2108 return getZeroExtendExpr(Op, Ty, Depth + 1);
2109
2110 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2111 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2115 for (SCEVUse Operand : MinMax->operands())
2116 Operands.push_back(getSignExtendExpr(Operand, Ty));
2118 return getSMinExpr(Operands);
2119 return getSMaxExpr(Operands);
2120 }
2121
2122 // The cast wasn't folded; create an explicit cast node.
2123 // Recompute the insert position, as it may have been invalidated.
2124 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
2125 return S;
2126 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2127 Op, Ty);
2128 UniqueSCEVs.insert(S, Token);
2129 S->computeAndSetCanonical(*this);
2130 registerUser(S, Op);
2131 return S;
2132}
2133
2135 switch (Kind) {
2136 case scTruncate:
2137 return getTruncateExpr(Op, Ty);
2138 case scZeroExtend:
2139 return getZeroExtendExpr(Op, Ty);
2140 case scSignExtend:
2141 return getSignExtendExpr(Op, Ty);
2142 case scPtrToAddr: {
2143 const SCEV *Expr = getPtrToAddrExpr(Op);
2144 assert(Expr->getType() == Ty && "requested type must match");
2145 return Expr;
2146 }
2147 default:
2148 llvm_unreachable("Not a SCEV cast expression!");
2149 }
2150}
2151
2152/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2153/// unspecified bits out to the given type.
2155 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2156 "This is not an extending conversion!");
2157 assert(isSCEVable(Ty) &&
2158 "This is not a conversion to a SCEVable type!");
2159 Ty = getEffectiveSCEVType(Ty);
2160
2161 // Sign-extend negative constants.
2162 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2163 if (SC->getAPInt().isNegative())
2164 return getSignExtendExpr(Op, Ty);
2165
2166 // Peel off a truncate cast.
2168 const SCEV *NewOp = T->getOperand();
2169 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2170 return getAnyExtendExpr(NewOp, Ty);
2171 return getTruncateOrNoop(NewOp, Ty);
2172 }
2173
2174 // Next try a zext cast. If the cast is folded, use it.
2175 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2176 if (!isa<SCEVZeroExtendExpr>(ZExt))
2177 return ZExt;
2178
2179 // Next try a sext cast. If the cast is folded, use it.
2180 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2181 if (!isa<SCEVSignExtendExpr>(SExt))
2182 return SExt;
2183
2184 // Force the cast to be folded into the operands of an addrec.
2185 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2187 for (const SCEV *Op : AR->operands())
2188 Ops.push_back(getAnyExtendExpr(Op, Ty));
2189 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2190 }
2191
2192 // If the expression is obviously signed, use the sext cast value.
2193 if (isa<SCEVSMaxExpr>(Op))
2194 return SExt;
2195
2196 // Absent any other information, use the zext cast value.
2197 return ZExt;
2198}
2199
2200/// Process the given Ops list, which is a list of operands to be added under
2201/// the given scale, update the given map. This is a helper function for
2202/// getAddRecExpr. As an example of what it does, given a sequence of operands
2203/// that would form an add expression like this:
2204///
2205/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2206///
2207/// where A and B are constants, update the map with these values:
2208///
2209/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2210///
2211/// and add 13 + A*B*29 to AccumulatedConstant.
2212/// This will allow getAddRecExpr to produce this:
2213///
2214/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2215///
2216/// This form often exposes folding opportunities that are hidden in
2217/// the original operand list.
2218///
2219/// Return true iff it appears that any interesting folding opportunities
2220/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2221/// the common case where no interesting opportunities are present, and
2222/// is also used as a check to avoid infinite recursion.
2225 APInt &AccumulatedConstant,
2227 const APInt &Scale,
2228 ScalarEvolution &SE) {
2229 bool Interesting = false;
2230
2231 // Iterate over the add operands. They are sorted, with constants first.
2232 unsigned i = 0;
2233 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2234 ++i;
2235 // Pull a buried constant out to the outside.
2236 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2237 Interesting = true;
2238 AccumulatedConstant += Scale * C->getAPInt();
2239 }
2240
2241 // Next comes everything else. We're especially interested in multiplies
2242 // here, but they're in the middle, so just visit the rest with one loop.
2243 for (; i != Ops.size(); ++i) {
2245 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2246 APInt NewScale =
2247 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2248 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2249 // A multiplication of a constant with another add; recurse.
2250 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2251 Interesting |= CollectAddOperandsWithScales(
2252 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2253 } else {
2254 // A multiplication of a constant with some other value. Update
2255 // the map.
2256 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2257 const SCEV *Key = SE.getMulExpr(MulOps);
2258 auto Pair = M.insert({Key, NewScale});
2259 if (Pair.second) {
2260 NewOps.push_back(Pair.first->first);
2261 } else {
2262 Pair.first->second += NewScale;
2263 // The map already had an entry for this value, which may indicate
2264 // a folding opportunity.
2265 Interesting = true;
2266 }
2267 }
2268 } else {
2269 // An ordinary operand. Update the map.
2270 auto Pair = M.insert({Ops[i], Scale});
2271 if (Pair.second) {
2272 NewOps.push_back(Pair.first->first);
2273 } else {
2274 Pair.first->second += Scale;
2275 // The map already had an entry for this value, which may indicate
2276 // a folding opportunity.
2277 Interesting = true;
2278 }
2279 }
2280 }
2281
2282 return Interesting;
2283}
2284
2286 const SCEV *LHS, const SCEV *RHS,
2287 const Instruction *CtxI) {
2289 unsigned);
2290 switch (BinOp) {
2291 default:
2292 llvm_unreachable("Unsupported binary op");
2293 case Instruction::Add:
2295 break;
2296 case Instruction::Sub:
2298 break;
2299 case Instruction::Mul:
2301 break;
2302 }
2303
2304 const SCEV *(ScalarEvolution::*Extension)(SCEVUse, Type *, unsigned) =
2307
2308 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2309 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2310 auto *WideTy =
2311 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2312
2313 const SCEV *A = (this->*Extension)(
2314 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2315 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2316 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2317 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2318 if (A == B)
2319 return true;
2320 // Can we use context to prove the fact we need?
2321 if (!CtxI)
2322 return false;
2323 // TODO: Support mul.
2324 if (BinOp == Instruction::Mul)
2325 return false;
2326 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2327 // TODO: Lift this limitation.
2328 if (!RHSC)
2329 return false;
2330 APInt C = RHSC->getAPInt();
2331 unsigned NumBits = C.getBitWidth();
2332 bool IsSub = (BinOp == Instruction::Sub);
2333 bool IsNegativeConst = (Signed && C.isNegative());
2334 // Compute the direction and magnitude by which we need to check overflow.
2335 bool OverflowDown = IsSub ^ IsNegativeConst;
2336 APInt Magnitude = C;
2337 if (IsNegativeConst) {
2338 if (C == APInt::getSignedMinValue(NumBits))
2339 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2340 // want to deal with that.
2341 return false;
2342 Magnitude = -C;
2343 }
2344
2346 if (OverflowDown) {
2347 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2348 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2349 : APInt::getMinValue(NumBits);
2350 APInt Limit = Min + Magnitude;
2351 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2352 } else {
2353 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2354 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2355 : APInt::getMaxValue(NumBits);
2356 APInt Limit = Max - Magnitude;
2357 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2358 }
2359}
2360
2361std::optional<SCEV::NoWrapFlags>
2363 const OverflowingBinaryOperator *OBO) {
2364 // It cannot be done any better.
2365 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2366 return std::nullopt;
2367
2368 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2369
2370 if (OBO->hasNoUnsignedWrap())
2372 if (OBO->hasNoSignedWrap())
2374
2375 bool Deduced = false;
2376
2378 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2379 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2380
2381 bool CanUseNSW = true;
2382 const APInt *ShiftAmt;
2383 // Treat `shl %a, C` as `mul %a, 1 << C`.
2384 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2385 unsigned BitWidth = ShiftAmt->getBitWidth();
2386 if (ShiftAmt->uge(BitWidth))
2387 return std::nullopt;
2388 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2389 // overflows.
2390 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2391 Opcode = Instruction::Mul;
2393 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2394 Opcode != Instruction::Mul) {
2395 return std::nullopt;
2396 }
2397
2398 const Instruction *CtxI =
2400 if (!OBO->hasNoUnsignedWrap() &&
2401 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2403 Deduced = true;
2404 }
2405
2406 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2407 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2409 Deduced = true;
2410 }
2411
2412 if (Deduced)
2413 return Flags;
2414 return std::nullopt;
2415}
2416
2417// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2418// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2419// can't-overflow flags for the operation if possible.
2423 SCEV::NoWrapFlags Flags) {
2424 using namespace std::placeholders;
2425
2426 using OBO = OverflowingBinaryOperator;
2427
2428 bool CanAnalyze =
2430 (void)CanAnalyze;
2431 assert(CanAnalyze && "don't call from other places!");
2432
2433 SCEV::NoWrapFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2434 SCEV::NoWrapFlags SignOrUnsignWrap =
2435 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2436
2437 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2438 auto IsKnownNonNegative = [&](SCEVUse U) {
2439 return SE->isKnownNonNegative(U);
2440 };
2441
2442 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2443 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2444
2445 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2446
2447 if (SignOrUnsignWrap != SignOrUnsignMask &&
2448 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2449 isa<SCEVConstant>(Ops[0])) {
2450
2451 auto Opcode = [&] {
2452 switch (Type) {
2453 case scAddExpr:
2454 return Instruction::Add;
2455 case scMulExpr:
2456 return Instruction::Mul;
2457 default:
2458 llvm_unreachable("Unexpected SCEV op.");
2459 }
2460 }();
2461
2462 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2463
2464 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2465 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2467 Opcode, C, OBO::NoSignedWrap);
2468 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2470 }
2471
2472 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2473 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2475 Opcode, C, OBO::NoUnsignedWrap);
2476 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2478 }
2479 }
2480
2481 // <0,+,nonnegative><nw> is also nuw
2482 // TODO: Add corresponding nsw case
2484 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2485 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2487
2488 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2490 Ops.size() == 2) {
2491 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2492 if (UDiv->getOperand(1) == Ops[1])
2494 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2495 if (UDiv->getOperand(1) == Ops[0])
2497 }
2498
2499 return Flags;
2500}
2501
2503 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2504}
2505
2506/// Get a canonical add expression, or something simpler if possible.
2508 SCEV::NoWrapFlags OrigFlags,
2509 unsigned Depth) {
2510 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2511 "only nuw or nsw allowed");
2512 assert(!Ops.empty() && "Cannot get empty add!");
2513 if (Ops.size() == 1) return Ops[0];
2514#ifndef NDEBUG
2515 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2516 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2517 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2518 "SCEVAddExpr operand types don't match!");
2519 unsigned NumPtrs = count_if(
2520 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2521 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2522#endif
2523
2524 const SCEV *Folded = constantFoldAndGroupOps(
2525 *this, LI, DT, Ops,
2526 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2527 [](const APInt &C) { return C.isZero(); }, // identity
2528 [](const APInt &C) { return false; }); // absorber
2529 if (Folded)
2530 return Folded;
2531
2532 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2533
2534 // Delay expensive flag strengthening until necessary.
2535 auto ComputeFlags = [this, OrigFlags](ArrayRef<SCEVUse> Ops) {
2536 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2537 };
2538
2539 // Limit recursion calls depth.
2541 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2542
2543 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2544 // Don't strengthen flags if we have no new information.
2545 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2546 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2547 Add->setNoWrapFlags(ComputeFlags(Ops));
2548 return S;
2549 }
2550
2551 // Okay, check to see if the same value occurs in the operand list more than
2552 // once. If so, merge them together into an multiply expression. Since we
2553 // sorted the list, these values are required to be adjacent.
2554 Type *Ty = Ops[0]->getType();
2555 bool FoundMatch = false;
2556 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2557 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2558 // Scan ahead to count how many equal operands there are.
2559 unsigned Count = 2;
2560 while (i+Count != e && Ops[i+Count] == Ops[i])
2561 ++Count;
2562 // Merge the values into a multiply.
2563 SCEVUse Scale = getConstant(Ty, Count);
2564 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2565 if (Ops.size() == Count)
2566 return Mul;
2567 Ops[i] = Mul;
2568 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2569 --i; e -= Count - 1;
2570 FoundMatch = true;
2571 }
2572 if (FoundMatch)
2573 return getAddExpr(Ops, OrigFlags, Depth + 1);
2574
2575 // Check for truncates. If all the operands are truncated from the same
2576 // type, see if factoring out the truncate would permit the result to be
2577 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2578 // if the contents of the resulting outer trunc fold to something simple.
2579 auto FindTruncSrcType = [&]() -> Type * {
2580 // We're ultimately looking to fold an addrec of truncs and muls of only
2581 // constants and truncs, so if we find any other types of SCEV
2582 // as operands of the addrec then we bail and return nullptr here.
2583 // Otherwise, we return the type of the operand of a trunc that we find.
2584 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2585 return T->getOperand()->getType();
2586 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2587 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2588 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2589 return T->getOperand()->getType();
2590 }
2591 return nullptr;
2592 };
2593 if (auto *SrcType = FindTruncSrcType()) {
2594 SmallVector<SCEVUse, 8> LargeOps;
2595 bool Ok = true;
2596 // Check all the operands to see if they can be represented in the
2597 // source type of the truncate.
2598 for (const SCEV *Op : Ops) {
2600 if (T->getOperand()->getType() != SrcType) {
2601 Ok = false;
2602 break;
2603 }
2604 LargeOps.push_back(T->getOperand());
2605 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2606 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2607 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2608 SmallVector<SCEVUse, 8> LargeMulOps;
2609 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2610 if (const SCEVTruncateExpr *T =
2611 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2612 if (T->getOperand()->getType() != SrcType) {
2613 Ok = false;
2614 break;
2615 }
2616 LargeMulOps.push_back(T->getOperand());
2617 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2618 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2619 } else {
2620 Ok = false;
2621 break;
2622 }
2623 }
2624 if (Ok)
2625 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2626 } else {
2627 Ok = false;
2628 break;
2629 }
2630 }
2631 if (Ok) {
2632 // Evaluate the expression in the larger type.
2633 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2634 // If it folds to something simple, use it. Otherwise, don't.
2635 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2636 return getTruncateExpr(Fold, Ty);
2637 }
2638 }
2639
2640 if (Ops.size() == 2) {
2641 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2642 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2643 // C1).
2644 const SCEV *A = Ops[0];
2645 const SCEV *B = Ops[1];
2646 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2647 auto *C = dyn_cast<SCEVConstant>(A);
2648 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2649 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2650 auto C2 = C->getAPInt();
2651 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2652
2653 APInt ConstAdd = C1 + C2;
2654 auto AddFlags = AddExpr->getNoWrapFlags();
2655 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2657 ConstAdd.ule(C1)) {
2658 PreservedFlags =
2660 }
2661
2662 // Adding a constant with the same sign and small magnitude is NSW, if the
2663 // original AddExpr was NSW.
2665 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2666 ConstAdd.abs().ule(C1.abs())) {
2667 PreservedFlags =
2669 }
2670
2671 if (PreservedFlags != SCEV::FlagAnyWrap) {
2672 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2673 NewOps[0] = getConstant(ConstAdd);
2674 return getAddExpr(NewOps, PreservedFlags);
2675 }
2676 }
2677
2678 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2679 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2680 const SCEVAddExpr *InnerAdd;
2681 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2682 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2683 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2684 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2685 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2687 SCEV::FlagNUW)) {
2688 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2689 }
2690 }
2691 }
2692
2693 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2694 const SCEV *Y;
2695 if (Ops.size() == 2 &&
2696 match(Ops[0],
2698 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2699 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2700
2701 // Skip past any other cast SCEVs.
2702 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2703 ++Idx;
2704
2705 // If there are add operands they would be next.
2706 if (Idx < Ops.size()) {
2707 bool DeletedAdd = false;
2708 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2709 // common NUW flag for expression after inlining. Other flags cannot be
2710 // preserved, because they may depend on the original order of operations.
2711 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2712 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2713 if (Ops.size() > AddOpsInlineThreshold ||
2714 Add->getNumOperands() > AddOpsInlineThreshold)
2715 break;
2716 // If we have an add, expand the add operands onto the end of the operands
2717 // list.
2718 Ops.erase(Ops.begin()+Idx);
2719 append_range(Ops, Add->operands());
2720 DeletedAdd = true;
2721 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2722 }
2723
2724 // If we deleted at least one add, we added operands to the end of the list,
2725 // and they are not necessarily sorted. Recurse to resort and resimplify
2726 // any operands we just acquired.
2727 if (DeletedAdd)
2728 return getAddExpr(Ops, CommonFlags, Depth + 1);
2729 }
2730
2731 // Skip over the add expression until we get to a multiply.
2732 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2733 ++Idx;
2734
2735 // Check to see if there are any folding opportunities present with
2736 // operands multiplied by constant values.
2737 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2738 uint64_t BitWidth = getTypeSizeInBits(Ty);
2741 APInt AccumulatedConstant(BitWidth, 0);
2742 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2743 Ops, APInt(BitWidth, 1), *this)) {
2744 struct APIntCompare {
2745 bool operator()(const APInt &LHS, const APInt &RHS) const {
2746 return LHS.ult(RHS);
2747 }
2748 };
2749
2750 // Some interesting folding opportunity is present, so its worthwhile to
2751 // re-generate the operands list. Group the operands by constant scale,
2752 // to avoid multiplying by the same constant scale multiple times.
2753 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2754 for (const SCEV *NewOp : NewOps)
2755 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2756 // Re-generate the operands list.
2757 Ops.clear();
2758 if (AccumulatedConstant != 0)
2759 Ops.push_back(getConstant(AccumulatedConstant));
2760 for (auto &MulOp : MulOpLists) {
2761 if (MulOp.first == 1) {
2762 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2763 } else if (MulOp.first != 0) {
2764 Ops.push_back(getMulExpr(
2765 getConstant(MulOp.first),
2766 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2767 SCEV::FlagAnyWrap, Depth + 1));
2768 }
2769 }
2770 if (Ops.empty())
2771 return getZero(Ty);
2772 if (Ops.size() == 1)
2773 return Ops[0];
2774 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2775 }
2776 }
2777
2778 // Given a SCEVMulExpr and an operand index, return the product of all
2779 // operands except the one at OpIdx.
2780 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2781 if (M->getNumOperands() == 2)
2782 return M->getOperand(OpIdx == 0);
2783 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2784 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2785 return getMulExpr(Remaining, SCEV::FlagAnyWrap, Depth + 1);
2786 };
2787
2788 // If we are adding something to a multiply expression, make sure the
2789 // something is not already an operand of the multiply. If so, merge it into
2790 // the multiply.
2791 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2792 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2793 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2794 // Scan all terms to find every occurrence of common factor MulOpSCEV
2795 // and fold them in one shot:
2796 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2797 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2798 if (isa<SCEVConstant>(MulOpSCEV))
2799 continue;
2800
2801 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2802 // remaining product for multiply terms containing MulOpSCEV.
2803 SmallVector<SCEVUse, 4> Cofactors;
2804 SmallVector<unsigned, 4> DeadIndices;
2805 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2806 if (MulOpSCEV == Ops[AddOp]) {
2807 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2808 Cofactors.push_back(getOne(Ty));
2809 DeadIndices.push_back(AddOp);
2810 continue;
2811 }
2812
2813 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2814 continue;
2815
2816 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2817 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2818 ++OMulOp) {
2819 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2820 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2821 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2822 DeadIndices.push_back(AddOp);
2823 break;
2824 }
2825 }
2826 }
2827
2828 // Fold all collected cofactors with the anchor multiply's cofactor:
2829 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2830 if (!Cofactors.empty()) {
2831 Cofactors.push_back(StripFactor(Mul, MulOp));
2832
2833 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagAnyWrap, Depth + 1);
2834 SCEVUse OuterMul =
2835 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagAnyWrap, Depth + 1);
2836
2837 // DeadIndices does not include Idx (the anchor), hence +1.
2838 if (Ops.size() == DeadIndices.size() + 1)
2839 return OuterMul;
2840
2841 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2842 // The -1 adjustment accounts for the shift from removing Idx;
2843 // reverse order means each erasure only shifts later positions,
2844 // which have already been processed.
2845 Ops.erase(Ops.begin() + Idx);
2846 for (unsigned Dead : reverse(DeadIndices))
2847 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2848
2849 Ops.push_back(OuterMul);
2850 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2851 }
2852 }
2853 }
2854
2855 // If there are any add recurrences in the operands list, see if any other
2856 // added values are loop invariant. If so, we can fold them into the
2857 // recurrence.
2858 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2859 ++Idx;
2860
2861 // Scan over all recurrences, trying to fold loop invariants into them.
2862 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2863 // Scan all of the other operands to this add and add them to the vector if
2864 // they are loop invariant w.r.t. the recurrence.
2866 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2867 const Loop *AddRecLoop = AddRec->getLoop();
2868 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2869 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2870 LIOps.push_back(Ops[i]);
2871 Ops.erase(Ops.begin()+i);
2872 --i; --e;
2873 }
2874
2875 // If we found some loop invariants, fold them into the recurrence.
2876 if (!LIOps.empty()) {
2877 // Compute nowrap flags for the addition of the loop-invariant ops and
2878 // the addrec. Temporarily push it as an operand for that purpose. These
2879 // flags are valid in the scope of the addrec only.
2880 LIOps.push_back(AddRec);
2881 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2882 LIOps.pop_back();
2883
2884 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2885 LIOps.push_back(AddRec->getStart());
2886
2887 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2888
2889 // It is not in general safe to propagate flags valid on an add within
2890 // the addrec scope to one outside it. We must prove that the inner
2891 // scope is guaranteed to execute if the outer one does to be able to
2892 // safely propagate. We know the program is undefined if poison is
2893 // produced on the inner scoped addrec. We also know that *for this use*
2894 // the outer scoped add can't overflow (because of the flags we just
2895 // computed for the inner scoped add) without the program being undefined.
2896 // Proving that entry to the outer scope neccesitates entry to the inner
2897 // scope, thus proves the program undefined if the flags would be violated
2898 // in the outer scope.
2899 SCEV::NoWrapFlags AddFlags = Flags;
2900 if (AddFlags != SCEV::FlagAnyWrap) {
2901 auto *DefI = getDefiningScopeBound(LIOps);
2902 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2903 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2904 AddFlags = SCEV::FlagAnyWrap;
2905 }
2906 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2907
2908 // Build the new addrec. Propagate the NUW and NSW flags if both the
2909 // outer add and the inner addrec are guaranteed to have no overflow.
2910 // Always propagate NW.
2911 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2912 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2913
2914 // If all of the other operands were loop invariant, we are done.
2915 if (Ops.size() == 1) return NewRec;
2916
2917 // Otherwise, add the folded AddRec by the non-invariant parts.
2918 for (unsigned i = 0;; ++i)
2919 if (Ops[i] == AddRec) {
2920 Ops[i] = NewRec;
2921 break;
2922 }
2923 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2924 }
2925
2926 // Okay, if there weren't any loop invariants to be folded, check to see if
2927 // there are multiple AddRec's with the same loop induction variable being
2928 // added together. If so, we can fold them.
2929 for (unsigned OtherIdx = Idx+1;
2930 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2931 ++OtherIdx) {
2932 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2933 // so that the 1st found AddRecExpr is dominated by all others.
2934 assert(DT.dominates(
2935 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2936 AddRec->getLoop()->getHeader()) &&
2937 "AddRecExprs are not sorted in reverse dominance order?");
2938 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2939 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2940 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2941 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2942 ++OtherIdx) {
2943 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2944 if (OtherAddRec->getLoop() == AddRecLoop) {
2945 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2946 i != e; ++i) {
2947 if (i >= AddRecOps.size()) {
2948 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2949 break;
2950 }
2951 AddRecOps[i] =
2952 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
2954 }
2955 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2956 }
2957 }
2958 // Step size has changed, so we cannot guarantee no self-wraparound.
2959 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2960 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2961 }
2962 }
2963
2964 // Otherwise couldn't fold anything into this recurrence. Move onto the
2965 // next one.
2966 }
2967
2968 // Okay, it looks like we really DO need an add expr. Check to see if we
2969 // already have one, otherwise create a new one.
2970 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2971}
2972
2973const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
2974 SCEV::NoWrapFlags Flags) {
2977 for (SCEVUse Op : Ops)
2978 ID.AddPointer(Op.getOpaqueValue());
2980 SCEVAddExpr *S = static_cast<SCEVAddExpr *>(UniqueSCEVs.lookup(ID, Token));
2981 if (!S) {
2982 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2984 S = new (SCEVAllocator)
2985 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2986 UniqueSCEVs.insert(S, Token);
2987 S->computeAndSetCanonical(*this);
2988 registerUser(S, Ops);
2989 }
2990 S->setNoWrapFlags(Flags);
2991 return S;
2992}
2993
2994const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
2995 const Loop *L,
2996 SCEV::NoWrapFlags Flags) {
2997 FoldingSetNodeID ID;
2998 ID.AddInteger(scAddRecExpr);
2999 for (SCEVUse Op : Ops)
3000 ID.AddPointer(Op.getOpaqueValue());
3001 ID.AddPointer(L);
3002 FoldingSetInsertToken Token;
3003 SCEVAddRecExpr *S =
3004 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
3005 if (!S) {
3006 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3008 S = new (SCEVAllocator)
3009 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3010 UniqueSCEVs.insert(S, Token);
3011 S->computeAndSetCanonical(*this);
3012 LoopUsers[L].push_back(S);
3013 registerUser(S, Ops);
3014 }
3015 setNoWrapFlags(S, Flags);
3016 return S;
3017}
3018
3019const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3020 SCEV::NoWrapFlags Flags) {
3021 FoldingSetNodeID ID;
3022 ID.AddInteger(scMulExpr);
3023 for (SCEVUse Op : Ops)
3024 ID.AddPointer(Op.getOpaqueValue());
3025 FoldingSetInsertToken Token;
3026 SCEVMulExpr *S = static_cast<SCEVMulExpr *>(UniqueSCEVs.lookup(ID, Token));
3027 if (!S) {
3028 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3030 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3031 O, Ops.size());
3032 UniqueSCEVs.insert(S, Token);
3033 S->computeAndSetCanonical(*this);
3034 registerUser(S, Ops);
3035 }
3036 S->setNoWrapFlags(Flags);
3037 return S;
3038}
3039
3040const SCEV *ScalarEvolution::getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS) {
3041 FoldingSetNodeID ID;
3042 ID.AddInteger(scUDivExpr);
3043 ID.AddPointer(LHS.getOpaqueValue());
3044 ID.AddPointer(RHS.getOpaqueValue());
3045 FoldingSetInsertToken Token;
3046 SCEV *S = UniqueSCEVs.lookup(ID, Token);
3047 if (!S) {
3048 S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), LHS, RHS);
3049 UniqueSCEVs.insert(S, Token);
3050 S->computeAndSetCanonical(*this);
3052 }
3053 return S;
3054}
3055
3056static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3057 uint64_t k = i*j;
3058 if (j > 1 && k / j != i) Overflow = true;
3059 return k;
3060}
3061
3062/// Compute the result of "n choose k", the binomial coefficient. If an
3063/// intermediate computation overflows, Overflow will be set and the return will
3064/// be garbage. Overflow is not cleared on absence of overflow.
3065static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3066 // We use the multiplicative formula:
3067 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3068 // At each iteration, we take the n-th term of the numeral and divide by the
3069 // (k-n)th term of the denominator. This division will always produce an
3070 // integral result, and helps reduce the chance of overflow in the
3071 // intermediate computations. However, we can still overflow even when the
3072 // final result would fit.
3073
3074 if (n == 0 || n == k) return 1;
3075 if (k > n) return 0;
3076
3077 if (k > n/2)
3078 k = n-k;
3079
3080 uint64_t r = 1;
3081 for (uint64_t i = 1; i <= k; ++i) {
3082 r = umul_ov(r, n-(i-1), Overflow);
3083 r /= i;
3084 }
3085 return r;
3086}
3087
3088/// Determine if any of the operands in this SCEV are a constant or if
3089/// any of the add or multiply expressions in this SCEV contain a constant.
3090static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3091 struct FindConstantInAddMulChain {
3092 bool FoundConstant = false;
3093
3094 bool follow(const SCEV *S) {
3095 FoundConstant |= isa<SCEVConstant>(S);
3096 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3097 }
3098
3099 bool isDone() const {
3100 return FoundConstant;
3101 }
3102 };
3103
3104 FindConstantInAddMulChain F;
3106 ST.visitAll(StartExpr);
3107 return F.FoundConstant;
3108}
3109
3110/// Get a canonical multiply expression, or something simpler if possible.
3112 SCEV::NoWrapFlags OrigFlags,
3113 unsigned Depth) {
3114 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3115 "only nuw or nsw allowed");
3116 assert(!Ops.empty() && "Cannot get empty mul!");
3117 if (Ops.size() == 1) return Ops[0];
3118#ifndef NDEBUG
3119 Type *ETy = Ops[0]->getType();
3120 assert(!ETy->isPointerTy());
3121 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3122 assert(Ops[i]->getType() == ETy &&
3123 "SCEVMulExpr operand types don't match!");
3124#endif
3125
3126 const SCEV *Folded = constantFoldAndGroupOps(
3127 *this, LI, DT, Ops,
3128 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3129 [](const APInt &C) { return C.isOne(); }, // identity
3130 [](const APInt &C) { return C.isZero(); }); // absorber
3131 if (Folded)
3132 return Folded;
3133
3134 // Delay expensive flag strengthening until necessary.
3135 auto ComputeFlags = [this, OrigFlags](const ArrayRef<SCEVUse> Ops) {
3136 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3137 };
3138
3139 // Limit recursion calls depth.
3141 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3142
3143 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3144 // Don't strengthen flags if we have no new information.
3145 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3146 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3147 Mul->setNoWrapFlags(ComputeFlags(Ops));
3148 return S;
3149 }
3150
3151 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3152 if (Ops.size() == 2) {
3153 // C1*(C2+V) -> C1*C2 + C1*V
3154 // If any of Add's ops are Adds or Muls with a constant, apply this
3155 // transformation as well.
3156 //
3157 // TODO: There are some cases where this transformation is not
3158 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3159 // this transformation should be narrowed down.
3160 const SCEV *Op0, *Op1;
3161 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3163 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagAnyWrap, Depth + 1);
3164 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagAnyWrap, Depth + 1);
3165 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3166 }
3167
3168 if (Ops[0]->isAllOnesValue()) {
3169 // If we have a mul by -1 of an add, try distributing the -1 among the
3170 // add operands.
3171 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3173 bool AnyFolded = false;
3174 for (const SCEV *AddOp : Add->operands()) {
3175 const SCEV *Mul = getMulExpr(Ops[0], SCEVUse(AddOp),
3177 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3178 NewOps.push_back(Mul);
3179 }
3180 if (AnyFolded)
3181 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3182 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3183 // Negation preserves a recurrence's no self-wrap property.
3185 for (const SCEV *AddRecOp : AddRec->operands())
3186 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3187 SCEV::FlagAnyWrap, Depth + 1));
3188 // Let M be the minimum representable signed value. AddRec with nsw
3189 // multiplied by -1 can have signed overflow if and only if it takes a
3190 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3191 // maximum signed value. In all other cases signed overflow is
3192 // impossible.
3193 auto FlagsMask = SCEV::FlagNW;
3194 if (AddRec->hasNoSignedWrap()) {
3195 auto MinInt =
3196 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3197 if (getSignedRangeMin(AddRec) != MinInt)
3198 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3199 }
3200 return getAddRecExpr(Operands, AddRec->getLoop(),
3201 AddRec->getNoWrapFlags(FlagsMask));
3202 }
3203 }
3204
3205 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3206 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3207 const SCEVAddExpr *InnerAdd;
3208 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3209 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3210 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3211 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3212 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3214 SCEV::FlagNUW)) {
3215 auto *Res = getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3216 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3217 };
3218 }
3219
3220 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3221 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3222 // of C1, fold to (D /u (C2 /u C1)).
3223 const SCEV *D;
3224 APInt C1V = LHSC->getAPInt();
3225 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3226 // as -1 * 1, as it won't enable additional folds.
3227 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3228 C1V = C1V.abs();
3229 const SCEVConstant *C2;
3230 if (C1V.isPowerOf2() &&
3232 C2->getAPInt().isPowerOf2() &&
3233 C1V.logBase2() <= getMinTrailingZeros(D)) {
3234 const SCEV *NewMul = nullptr;
3235 if (C1V.uge(C2->getAPInt())) {
3236 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3237 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3238 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3239 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3240 }
3241 if (NewMul)
3242 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3243 }
3244 }
3245 }
3246
3247 // Skip over the add expression until we get to a multiply.
3248 unsigned Idx = 0;
3249 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3250 ++Idx;
3251
3252 // If there are mul operands inline them all into this expression.
3253 if (Idx < Ops.size()) {
3254 bool DeletedMul = false;
3255 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3256 if (Ops.size() > MulOpsInlineThreshold)
3257 break;
3258 // If we have an mul, expand the mul operands onto the end of the
3259 // operands list.
3260 Ops.erase(Ops.begin()+Idx);
3261 append_range(Ops, Mul->operands());
3262 DeletedMul = true;
3263 }
3264
3265 // If we deleted at least one mul, we added operands to the end of the
3266 // list, and they are not necessarily sorted. Recurse to resort and
3267 // resimplify any operands we just acquired.
3268 if (DeletedMul)
3269 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3270 }
3271
3272 // If there are any add recurrences in the operands list, see if any other
3273 // added values are loop invariant. If so, we can fold them into the
3274 // recurrence.
3275 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3276 ++Idx;
3277
3278 // Scan over all recurrences, trying to fold loop invariants into them.
3279 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3280 // Scan all of the other operands to this mul and add them to the vector
3281 // if they are loop invariant w.r.t. the recurrence.
3283 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3284 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3285 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3286 LIOps.push_back(Ops[i]);
3287 Ops.erase(Ops.begin()+i);
3288 --i; --e;
3289 }
3290
3291 // If we found some loop invariants, fold them into the recurrence.
3292 if (!LIOps.empty()) {
3293 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3295 NewOps.reserve(AddRec->getNumOperands());
3296 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3297
3298 // If both the mul and addrec are nuw, we can preserve nuw.
3299 // If both the mul and addrec are nsw, we can only preserve nsw if either
3300 // a) they are also nuw, or
3301 // b) all multiplications of addrec operands with scale are nsw.
3302 SCEV::NoWrapFlags Flags =
3303 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3304
3305 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3306 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3307 SCEV::FlagAnyWrap, Depth + 1));
3308
3309 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3311 Instruction::Mul, getSignedRange(Scale),
3313 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3314 Flags = clearFlags(Flags, SCEV::FlagNSW);
3315 }
3316 }
3317
3318 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3319
3320 // If all of the other operands were loop invariant, we are done.
3321 if (Ops.size() == 1) return NewRec;
3322
3323 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3324 for (unsigned i = 0;; ++i)
3325 if (Ops[i] == AddRec) {
3326 Ops[i] = NewRec;
3327 break;
3328 }
3329 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3330 }
3331
3332 // Okay, if there weren't any loop invariants to be folded, check to see
3333 // if there are multiple AddRec's with the same loop induction variable
3334 // being multiplied together. If so, we can fold them.
3335
3336 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3337 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3338 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3339 // ]]],+,...up to x=2n}.
3340 // Note that the arguments to choose() are always integers with values
3341 // known at compile time, never SCEV objects.
3342 //
3343 // The implementation avoids pointless extra computations when the two
3344 // addrec's are of different length (mathematically, it's equivalent to
3345 // an infinite stream of zeros on the right).
3346 bool OpsModified = false;
3347 for (unsigned OtherIdx = Idx+1;
3348 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3349 ++OtherIdx) {
3350 const SCEVAddRecExpr *OtherAddRec =
3351 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3352 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3353 continue;
3354
3355 // Limit max number of arguments to avoid creation of unreasonably big
3356 // SCEVAddRecs with very complex operands.
3357 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3358 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3359 continue;
3360
3361 bool Overflow = false;
3362 Type *Ty = AddRec->getType();
3363 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3364 SmallVector<SCEVUse, 7> AddRecOps;
3365 for (int x = 0, xe = AddRec->getNumOperands() +
3366 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3368 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3369 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3370 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3371 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3372 z < ze && !Overflow; ++z) {
3373 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3374 uint64_t Coeff;
3375 if (LargerThan64Bits)
3376 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3377 else
3378 Coeff = Coeff1*Coeff2;
3379 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3380 const SCEV *Term1 = AddRec->getOperand(y-z);
3381 const SCEV *Term2 = OtherAddRec->getOperand(z);
3382 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3383 SCEV::FlagAnyWrap, Depth + 1));
3384 }
3385 }
3386 if (SumOps.empty())
3387 SumOps.push_back(getZero(Ty));
3388 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3389 }
3390 if (!Overflow) {
3391 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3393 if (Ops.size() == 2) return NewAddRec;
3394 Ops[Idx] = NewAddRec;
3395 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3396 OpsModified = true;
3397 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3398 if (!AddRec)
3399 break;
3400 }
3401 }
3402 if (OpsModified)
3403 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3404
3405 // Otherwise couldn't fold anything into this recurrence. Move onto the
3406 // next one.
3407 }
3408
3409 // Okay, it looks like we really DO need an mul expr. Check to see if we
3410 // already have one, otherwise create a new one.
3411 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3412}
3413
3414/// Represents an unsigned remainder expression based on unsigned division.
3416 assert(getEffectiveSCEVType(LHS->getType()) ==
3417 getEffectiveSCEVType(RHS->getType()) &&
3418 "SCEVURemExpr operand types don't match!");
3419
3420 // Short-circuit easy cases
3421 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3422 // If constant is one, the result is trivial
3423 if (RHSC->getValue()->isOne())
3424 return getZero(LHS->getType()); // X urem 1 --> 0
3425
3426 // If constant is a power of two, fold into a zext(trunc(LHS)).
3427 if (RHSC->getAPInt().isPowerOf2()) {
3428 Type *FullTy = LHS->getType();
3429 Type *TruncTy =
3430 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3431 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3432 }
3433 }
3434
3435 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3436 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3437 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3438 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3439}
3440
3441/// Get a canonical unsigned division expression, or something simpler if
3442/// possible.
3444 assert(!LHS->getType()->isPointerTy() &&
3445 "SCEVUDivExpr operand can't be pointer!");
3446 assert(LHS->getType() == RHS->getType() &&
3447 "SCEVUDivExpr operand types don't match!");
3448
3449 if (SCEV *S =
3450 findExistingSCEVInCache(scUDivExpr, ArrayRef<SCEVUse>({LHS, RHS})))
3451 return S;
3452
3453 // 0 udiv Y == 0
3454 if (match(LHS, m_scev_Zero()))
3455 return LHS;
3456
3457 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3458 if (RHSC->getValue()->isOne())
3459 return LHS; // X udiv 1 --> x
3460 // If the denominator is zero, the result of the udiv is undefined. Don't
3461 // try to analyze it, because the resolution chosen here may differ from
3462 // the resolution chosen in other parts of the compiler.
3463 if (!RHSC->getValue()->isZero()) {
3464 // Determine if the division can be folded into the operands of
3465 // its operands.
3466 // TODO: Generalize this to non-constants by using known-bits information.
3467 Type *Ty = LHS->getType();
3468 unsigned LZ = RHSC->getAPInt().countl_zero();
3469 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3470 // For non-power-of-two values, effectively round the value up to the
3471 // nearest power of two.
3472 if (!RHSC->getAPInt().isPowerOf2())
3473 ++MaxShiftAmt;
3474 IntegerType *ExtTy =
3475 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3476 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3477 if (const SCEVConstant *Step =
3478 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3479 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3480 const APInt &StepInt = Step->getAPInt();
3481 const APInt &DivInt = RHSC->getAPInt();
3482 if (!StepInt.urem(DivInt) &&
3483 getZeroExtendExpr(AR, ExtTy) ==
3484 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3485 getZeroExtendExpr(Step, ExtTy),
3486 AR->getLoop(), SCEV::FlagAnyWrap)) {
3488 for (const SCEV *Op : AR->operands())
3489 Operands.push_back(getUDivExpr(Op, RHS));
3490 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3491 }
3492 /// Get a canonical UDivExpr for a recurrence.
3493 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3494 const APInt *StartRem;
3495 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3496 m_scev_APInt(StartRem))) {
3497 bool NoWrap =
3498 getZeroExtendExpr(AR, ExtTy) ==
3499 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3500 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3502
3503 // With N <= C and both N, C as powers-of-2, the transformation
3504 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3505 // if wrapping occurs, as the division results remain equivalent for
3506 // all offsets in [[(X - X%N), X).
3507 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3508 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3509 // Only fold if the subtraction can be folded in the start
3510 // expression.
3511 const SCEV *NewStart =
3512 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3513 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3514 !isa<SCEVAddExpr>(NewStart)) {
3515 const SCEV *NewLHS =
3516 getAddRecExpr(NewStart, Step, AR->getLoop(),
3517 NoWrap ? SCEV::FlagNW : SCEV::FlagAnyWrap);
3518 if (LHS != NewLHS)
3519 return getUDivExpr(NewLHS, RHS);
3520 }
3521 }
3522 }
3523 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3524 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3525 if (M->hasNoUnsignedWrap()) {
3526 // Find an operand that's safely divisible.
3527 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3528 const SCEV *Op = M->getOperand(i);
3529 const SCEV *Div = getUDivExpr(Op, RHSC);
3530 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3531 SmallVector<SCEVUse, 4> Operands(M->operands());
3532 Operands[i] = Div;
3533 return getMulExpr(Operands);
3534 }
3535 }
3536
3537 // Even if it's not divisible, try to remove a common factor.
3538 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3539 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3540 RHSC->getAPInt());
3541 if (!Factor.isIntN(1)) {
3542 SmallVector<SCEVUse, 2> NewOperands;
3543 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3544 append_range(NewOperands, M->operands().drop_front());
3545 const SCEV *NewMul = getMulExpr(NewOperands);
3546 return getUDivExpr(NewMul,
3547 getConstant(RHSC->getAPInt().udiv(Factor)));
3548 }
3549 }
3550 }
3551 }
3552
3553 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3554 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3555 if (auto *DivisorConstant =
3556 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3557 bool Overflow = false;
3558 APInt NewRHS =
3559 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3560 if (Overflow) {
3561 return getConstant(RHSC->getType(), 0, false);
3562 }
3563 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3564 }
3565 }
3566
3567 // (A+B)/C --> (A/C + B/C) if the add does not unsigned wrap and A/C and
3568 // B/C can be folded.
3569 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3570 if (A->hasNoUnsignedWrap()) {
3572 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3573 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3574 if (isa<SCEVUDivExpr>(Op) ||
3575 getMulExpr(Op, RHS) != A->getOperand(i))
3576 break;
3577 Operands.push_back(Op);
3578 }
3579 if (Operands.size() == A->getNumOperands())
3580 return getAddExpr(Operands);
3581 }
3582 }
3583
3584 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3585 // This is an idiom for rounding A up to the next multiple of N, where A
3586 // is aready known to be a multiple of M. In this case, instcombine can
3587 // see that some low bits of the added constant are unused, so can clear
3588 // them, but we want to canonicalise to set the low bits. This makes the
3589 // pattern easier to match, without needing to check for known bits in
3590 // A*M.
3591 const APInt &N = RHSC->getAPInt();
3592 const APInt *NMinusM, *M;
3593 const SCEV *A;
3594 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3595 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3596 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3597 *NMinusM == N - *M) {
3598 return getUDivExpr(
3600 RHS);
3601 }
3602 }
3603
3604 // Fold if both operands are constant.
3605 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3606 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3607 }
3608 }
3609
3610 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3611 const APInt *NegC, *C;
3612 if (match(LHS,
3615 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3616 return getZero(LHS->getType());
3617
3618 // (%a * %b)<nuw> / %b -> %a
3619 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3620 if (Mul && Mul->hasNoUnsignedWrap()) {
3621 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3622 if (Mul->getOperand(i) == RHS) {
3624 append_range(Operands, Mul->operands().take_front(i));
3625 append_range(Operands, Mul->operands().drop_front(i + 1));
3626 return getMulExpr(Operands);
3627 }
3628 }
3629 }
3630
3631 // TODO: Generalize to handle any common factors.
3632 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3633 const SCEV *NewLHS, *NewRHS;
3634 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3635 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3636 return getUDivExpr(NewLHS, NewRHS);
3637
3638 return getOrCreateUDivExpr(LHS, RHS);
3639}
3640
3641/// Get a canonical unsigned division expression, or something simpler if
3642/// possible. There is no representation for an exact udiv in SCEV IR, but we
3643/// can attempt to optimize it prior to construction.
3645 // Currently there is no exact specific logic.
3646
3647 return getUDivExpr(LHS, RHS);
3648}
3649
3650/// Get an add recurrence expression for the specified loop. Simplify the
3651/// expression as much as possible.
3653 const Loop *L,
3654 SCEV::NoWrapFlags Flags) {
3656 Operands.push_back(Start);
3657 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3658 if (StepChrec->getLoop() == L) {
3659 append_range(Operands, StepChrec->operands());
3660 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3661 }
3662
3663 Operands.push_back(Step);
3664 return getAddRecExpr(Operands, L, Flags);
3665}
3666
3667/// Get an add recurrence expression for the specified loop. Simplify the
3668/// expression as much as possible.
3670 const Loop *L,
3671 SCEV::NoWrapFlags Flags) {
3672 if (Operands.size() == 1) return Operands[0];
3673#ifndef NDEBUG
3675 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3676 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3677 "SCEVAddRecExpr operand types don't match!");
3678 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3679 }
3680 for (const SCEV *Op : Operands)
3682 "SCEVAddRecExpr operand is not available at loop entry!");
3683#endif
3684
3685 if (Operands.back()->isZero()) {
3686 Operands.pop_back();
3687 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3688 }
3689
3690 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3691 // use that information to infer NUW and NSW flags. However, computing a
3692 // BE count requires calling getAddRecExpr, so we may not yet have a
3693 // meaningful BE count at this point (and if we don't, we'd be stuck
3694 // with a SCEVCouldNotCompute as the cached BE count).
3695
3696 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3697
3698 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3699 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3700 const Loop *NestedLoop = NestedAR->getLoop();
3701 if (L->contains(NestedLoop)
3702 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3703 : (!NestedLoop->contains(L) &&
3704 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3705 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3706 Operands[0] = NestedAR->getStart();
3707 // AddRecs require their operands be loop-invariant with respect to their
3708 // loops. Don't perform this transformation if it would break this
3709 // requirement.
3710 bool AllInvariant = all_of(
3711 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3712
3713 if (AllInvariant) {
3714 // Create a recurrence for the outer loop with the same step size.
3715 //
3716 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3717 // inner recurrence has the same property.
3718 SCEV::NoWrapFlags OuterFlags =
3719 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3720
3721 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3722 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3723 return isLoopInvariant(Op, NestedLoop);
3724 });
3725
3726 if (AllInvariant) {
3727 // Ok, both add recurrences are valid after the transformation.
3728 //
3729 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3730 // the outer recurrence has the same property.
3731 SCEV::NoWrapFlags InnerFlags =
3732 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3733 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3734 }
3735 }
3736 // Reset Operands to its original state.
3737 Operands[0] = NestedAR;
3738 }
3739 }
3740
3741 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3742 // already have one, otherwise create a new one.
3743 return getOrCreateAddRecExpr(Operands, L, Flags);
3744}
3745
3747 ArrayRef<SCEVUse> IndexExprs) {
3748 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3749 // getSCEV(Base)->getType() has the same address space as Base->getType()
3750 // because SCEV::getType() preserves the address space.
3751 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3752 if (NW != GEPNoWrapFlags::none()) {
3753 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3754 // but to do that, we have to ensure that said flag is valid in the entire
3755 // defined scope of the SCEV.
3756 // TODO: non-instructions have global scope. We might be able to prove
3757 // some global scope cases
3758 auto *GEPI = dyn_cast<Instruction>(GEP);
3759 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3760 NW = GEPNoWrapFlags::none();
3761 }
3762
3763 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3764}
3765
3767 ArrayRef<SCEVUse> IndexExprs,
3768 Type *SrcElementTy, GEPNoWrapFlags NW) {
3770 if (NW.hasNoUnsignedSignedWrap())
3771 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3772 if (NW.hasNoUnsignedWrap())
3773 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3774
3775 Type *CurTy = BaseExpr->getType();
3776 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3777 bool FirstIter = true;
3779 for (SCEVUse IndexExpr : IndexExprs) {
3780 // Compute the (potentially symbolic) offset in bytes for this index.
3781 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3782 // For a struct, add the member offset.
3783 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3784 unsigned FieldNo = Index->getZExtValue();
3785 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3786 Offsets.push_back(FieldOffset);
3787
3788 // Update CurTy to the type of the field at Index.
3789 CurTy = STy->getTypeAtIndex(Index);
3790 } else {
3791 // Update CurTy to its element type.
3792 if (FirstIter) {
3793 assert(isa<PointerType>(CurTy) &&
3794 "The first index of a GEP indexes a pointer");
3795 CurTy = SrcElementTy;
3796 FirstIter = false;
3797 } else {
3798 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3799 }
3800 // For an array, add the element offset, explicitly scaled.
3801 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3802 // Getelementptr indices are signed.
3803 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3804
3805 // Multiply the index by the element size to compute the element offset.
3806 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3807 Offsets.push_back(LocalOffset);
3808 }
3809 }
3810
3811 // Handle degenerate case of GEP without offsets.
3812 if (Offsets.empty())
3813 return BaseExpr;
3814
3815 // Add the offsets together, assuming nsw if inbounds.
3816 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3817 // Add the base address and the offset. We cannot use the nsw flag, as the
3818 // base address is unsigned. However, if we know that the offset is
3819 // non-negative, we can use nuw.
3820 bool NUW = NW.hasNoUnsignedWrap() ||
3823 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3824 assert(BaseExpr->getType() == GEPExpr->getType() &&
3825 "GEP should not change type mid-flight.");
3826 return GEPExpr;
3827}
3828
3829SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3832 ID.AddInteger(SCEVType);
3833 for (SCEVUse Op : Ops)
3834 ID.AddPointer(Op.getOpaqueValue());
3836 return UniqueSCEVs.lookup(ID, Token);
3837}
3838
3839const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3841 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3842}
3843
3846 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3847 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3848 if (Ops.size() == 1) return Ops[0];
3849#ifndef NDEBUG
3850 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3851 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3852 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3853 "Operand types don't match!");
3854 assert(Ops[0]->getType()->isPointerTy() ==
3855 Ops[i]->getType()->isPointerTy() &&
3856 "min/max should be consistently pointerish");
3857 }
3858#endif
3859
3860 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3861 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3862
3863 const SCEV *Folded = constantFoldAndGroupOps(
3864 *this, LI, DT, Ops,
3865 [&](const APInt &C1, const APInt &C2) {
3866 switch (Kind) {
3867 case scSMaxExpr:
3868 return APIntOps::smax(C1, C2);
3869 case scSMinExpr:
3870 return APIntOps::smin(C1, C2);
3871 case scUMaxExpr:
3872 return APIntOps::umax(C1, C2);
3873 case scUMinExpr:
3874 return APIntOps::umin(C1, C2);
3875 default:
3876 llvm_unreachable("Unknown SCEV min/max opcode");
3877 }
3878 },
3879 [&](const APInt &C) {
3880 // identity
3881 if (IsMax)
3882 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3883 else
3884 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3885 },
3886 [&](const APInt &C) {
3887 // absorber
3888 if (IsMax)
3889 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3890 else
3891 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3892 });
3893 if (Folded)
3894 return Folded;
3895
3896 // Check if we have created the same expression before.
3897 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3898 return S;
3899 }
3900
3901 // Find the first operation of the same kind
3902 unsigned Idx = 0;
3903 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3904 ++Idx;
3905
3906 // Check to see if one of the operands is of the same kind. If so, expand its
3907 // operands onto our operand list, and recurse to simplify.
3908 if (Idx < Ops.size()) {
3909 bool DeletedAny = false;
3910 while (Ops[Idx]->getSCEVType() == Kind) {
3911 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3912 Ops.erase(Ops.begin()+Idx);
3913 append_range(Ops, SMME->operands());
3914 DeletedAny = true;
3915 }
3916
3917 if (DeletedAny)
3918 return getMinMaxExpr(Kind, Ops);
3919 }
3920
3921 // Okay, check to see if the same value occurs in the operand list twice. If
3922 // so, delete one. Since we sorted the list, these values are required to
3923 // be adjacent.
3928 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3929 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3930 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3931 if (Ops[i] == Ops[i + 1] ||
3932 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3933 // X op Y op Y --> X op Y
3934 // X op Y --> X, if we know X, Y are ordered appropriately
3935 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3936 --i;
3937 --e;
3938 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3939 Ops[i + 1])) {
3940 // X op Y --> Y, if we know X, Y are ordered appropriately
3941 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3942 --i;
3943 --e;
3944 }
3945 }
3946
3947 if (Ops.size() == 1) return Ops[0];
3948
3949 assert(!Ops.empty() && "Reduced smax down to nothing!");
3950
3951 // Okay, it looks like we really DO need an expr. Check to see if we
3952 // already have one, otherwise create a new one.
3954 ID.AddInteger(Kind);
3955 for (SCEVUse Op : Ops)
3956 ID.AddPointer(Op.getOpaqueValue());
3958 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
3959 if (ExistingSCEV)
3960 return ExistingSCEV;
3961 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3963 SCEV *S = new (SCEVAllocator)
3964 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3965
3966 UniqueSCEVs.insert(S, Token);
3967 S->computeAndSetCanonical(*this);
3968 registerUser(S, Ops);
3969 return S;
3970}
3971
3972namespace {
3973
3974class SCEVSequentialMinMaxDeduplicatingVisitor final
3975 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3976 std::optional<const SCEV *>> {
3977 using RetVal = std::optional<const SCEV *>;
3979
3980 ScalarEvolution &SE;
3981 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3982 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3984
3985 bool canRecurseInto(SCEVTypes Kind) const {
3986 // We can only recurse into the SCEV expression of the same effective type
3987 // as the type of our root SCEV expression.
3988 return RootKind == Kind || NonSequentialRootKind == Kind;
3989 };
3990
3991 RetVal visitAnyMinMaxExpr(const SCEV *S) {
3993 "Only for min/max expressions.");
3994 SCEVTypes Kind = S->getSCEVType();
3995
3996 if (!canRecurseInto(Kind))
3997 return S;
3998
3999 auto *NAry = cast<SCEVNAryExpr>(S);
4000 SmallVector<SCEVUse> NewOps;
4001 bool Changed = visit(Kind, NAry->operands(), NewOps);
4002
4003 if (!Changed)
4004 return S;
4005 if (NewOps.empty())
4006 return std::nullopt;
4007
4009 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4010 : SE.getMinMaxExpr(Kind, NewOps);
4011 }
4012
4013 RetVal visit(const SCEV *S) {
4014 // Has the whole operand been seen already?
4015 if (!SeenOps.insert(S).second)
4016 return std::nullopt;
4017 return Base::visit(S);
4018 }
4019
4020public:
4021 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4022 SCEVTypes RootKind)
4023 : SE(SE), RootKind(RootKind),
4024 NonSequentialRootKind(
4025 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4026 RootKind)) {}
4027
4028 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4029 SmallVectorImpl<SCEVUse> &NewOps) {
4030 bool Changed = false;
4032 Ops.reserve(OrigOps.size());
4033
4034 for (const SCEV *Op : OrigOps) {
4035 RetVal NewOp = visit(Op);
4036 if (NewOp != Op)
4037 Changed = true;
4038 if (NewOp)
4039 Ops.emplace_back(*NewOp);
4040 }
4041
4042 if (Changed)
4043 NewOps = std::move(Ops);
4044 return Changed;
4045 }
4046
4047 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4048
4049 RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4050
4051 RetVal visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) { return Expr; }
4052
4053 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4054
4055 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4056
4057 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4058
4059 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4060
4061 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4062
4063 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4064
4065 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4066
4067 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4068 return visitAnyMinMaxExpr(Expr);
4069 }
4070
4071 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4072 return visitAnyMinMaxExpr(Expr);
4073 }
4074
4075 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4076 return visitAnyMinMaxExpr(Expr);
4077 }
4078
4079 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4080 return visitAnyMinMaxExpr(Expr);
4081 }
4082
4083 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4084 return visitAnyMinMaxExpr(Expr);
4085 }
4086
4087 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4088
4089 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4090};
4091
4092} // namespace
4093
4095 switch (Kind) {
4096 case scConstant:
4097 case scVScale:
4098 case scTruncate:
4099 case scZeroExtend:
4100 case scSignExtend:
4101 case scPtrToAddr:
4102 case scAddExpr:
4103 case scMulExpr:
4104 case scUDivExpr:
4105 case scAddRecExpr:
4106 case scUMaxExpr:
4107 case scSMaxExpr:
4108 case scUMinExpr:
4109 case scSMinExpr:
4110 case scUnknown:
4111 // If any operand is poison, the whole expression is poison.
4112 return true;
4114 // FIXME: if the *first* operand is poison, the whole expression is poison.
4115 return false; // Pessimistically, say that it does not propagate poison.
4116 case scCouldNotCompute:
4117 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4118 }
4119 llvm_unreachable("Unknown SCEV kind!");
4120}
4121
4122namespace {
4123// The only way poison may be introduced in a SCEV expression is from a
4124// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4125// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4126// introduce poison -- they encode guaranteed, non-speculated knowledge.
4127//
4128// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4129// with the notable exception of umin_seq, where only poison from the first
4130// operand is (unconditionally) propagated.
4131struct SCEVPoisonCollector {
4132 bool LookThroughMaybePoisonBlocking;
4133 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4134 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4135 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4136
4137 bool follow(const SCEV *S) {
4138 if (!LookThroughMaybePoisonBlocking &&
4140 return false;
4141
4142 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4143 if (!isGuaranteedNotToBePoison(SU->getValue()))
4144 MaybePoison.insert(SU);
4145 }
4146 return true;
4147 }
4148 bool isDone() const { return false; }
4149};
4150} // namespace
4151
4152/// Return true if V is poison given that AssumedPoison is already poison.
4153static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4154 // First collect all SCEVs that might result in AssumedPoison to be poison.
4155 // We need to look through potentially poison-blocking operations here,
4156 // because we want to find all SCEVs that *might* result in poison, not only
4157 // those that are *required* to.
4158 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4159 visitAll(AssumedPoison, PC1);
4160
4161 // AssumedPoison is never poison. As the assumption is false, the implication
4162 // is true. Don't bother walking the other SCEV in this case.
4163 if (PC1.MaybePoison.empty())
4164 return true;
4165
4166 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4167 // as well. We cannot look through potentially poison-blocking operations
4168 // here, as their arguments only *may* make the result poison.
4169 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4170 visitAll(S, PC2);
4171
4172 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4173 // it will also make S poison by being part of PC2.MaybePoison.
4174 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4175}
4176
4178 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4179 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4180 visitAll(S, PC);
4181 for (const SCEVUnknown *SU : PC.MaybePoison)
4182 Result.insert(SU->getValue());
4183}
4184
4186 const SCEV *S, Instruction *I,
4187 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4188 // If the instruction cannot be poison, it's always safe to reuse.
4190 return true;
4191
4192 // Otherwise, it is possible that I is more poisonous that S. Collect the
4193 // poison-contributors of S, and then check whether I has any additional
4194 // poison-contributors. Poison that is contributed through poison-generating
4195 // flags is handled by dropping those flags instead.
4197 getPoisonGeneratingValues(PoisonVals, S);
4198
4199 SmallVector<Value *> Worklist;
4201 Worklist.push_back(I);
4202 while (!Worklist.empty()) {
4203 Value *V = Worklist.pop_back_val();
4204 if (!Visited.insert(V).second)
4205 continue;
4206
4207 // Avoid walking large instruction graphs.
4208 if (Visited.size() > 16)
4209 return false;
4210
4211 // Either the value can't be poison, or the S would also be poison if it
4212 // is.
4213 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4214 continue;
4215
4216 auto *I = dyn_cast<Instruction>(V);
4217 if (!I)
4218 return false;
4219
4220 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4221 // can't replace an arbitrary add with disjoint or, even if we drop the
4222 // flag. We would need to convert the or into an add.
4223 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4224 if (PDI->isDisjoint())
4225 return false;
4226
4227 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4228 // because SCEV currently assumes it can't be poison. Remove this special
4229 // case once we proper model when vscale can be poison.
4230 if (auto *II = dyn_cast<IntrinsicInst>(I);
4231 II && II->getIntrinsicID() == Intrinsic::vscale)
4232 continue;
4233
4234 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4235 return false;
4236
4237 // If the instruction can't create poison, we can recurse to its operands.
4238 if (I->hasPoisonGeneratingAnnotations())
4239 DropPoisonGeneratingInsts.push_back(I);
4240
4241 llvm::append_range(Worklist, I->operands());
4242 }
4243 return true;
4244}
4245
4246const SCEV *
4249 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4250 "Not a SCEVSequentialMinMaxExpr!");
4251 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4252 if (Ops.size() == 1)
4253 return Ops[0];
4254#ifndef NDEBUG
4255 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4256 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4257 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4258 "Operand types don't match!");
4259 assert(Ops[0]->getType()->isPointerTy() ==
4260 Ops[i]->getType()->isPointerTy() &&
4261 "min/max should be consistently pointerish");
4262 }
4263#endif
4264
4265 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4266 // so we can *NOT* do any kind of sorting of the expressions!
4267
4268 // Check if we have created the same expression before.
4269 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4270 return S;
4271
4272 // FIXME: there are *some* simplifications that we can do here.
4273
4274 // Keep only the first instance of an operand.
4275 {
4276 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4277 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4278 if (Changed)
4279 return getSequentialMinMaxExpr(Kind, Ops);
4280 }
4281
4282 // Check to see if one of the operands is of the same kind. If so, expand its
4283 // operands onto our operand list, and recurse to simplify.
4284 {
4285 unsigned Idx = 0;
4286 bool DeletedAny = false;
4287 while (Idx < Ops.size()) {
4288 if (Ops[Idx]->getSCEVType() != Kind) {
4289 ++Idx;
4290 continue;
4291 }
4292 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4293 Ops.erase(Ops.begin() + Idx);
4294 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4295 SMME->operands().end());
4296 DeletedAny = true;
4297 }
4298
4299 if (DeletedAny)
4300 return getSequentialMinMaxExpr(Kind, Ops);
4301 }
4302
4303 const SCEV *SaturationPoint;
4305 switch (Kind) {
4307 SaturationPoint = getZero(Ops[0]->getType());
4308 Pred = ICmpInst::ICMP_ULE;
4309 break;
4310 default:
4311 llvm_unreachable("Not a sequential min/max type.");
4312 }
4313
4314 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4315 if (!isGuaranteedNotToCauseUB(Ops[i]))
4316 continue;
4317 // We can replace %x umin_seq %y with %x umin %y if either:
4318 // * %y being poison implies %x is also poison.
4319 // * %x cannot be the saturating value (e.g. zero for umin).
4320 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4321 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4322 SaturationPoint)) {
4323 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4324 Ops[i - 1] = getMinMaxExpr(
4326 SeqOps);
4327 Ops.erase(Ops.begin() + i);
4328 return getSequentialMinMaxExpr(Kind, Ops);
4329 }
4330 // Fold %x umin_seq %y to %x if %x ule %y.
4331 // TODO: We might be able to prove the predicate for a later operand.
4332 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4333 Ops.erase(Ops.begin() + i);
4334 return getSequentialMinMaxExpr(Kind, Ops);
4335 }
4336 }
4337
4338 // Okay, it looks like we really DO need an expr. Check to see if we
4339 // already have one, otherwise create a new one.
4341 ID.AddInteger(Kind);
4342 for (SCEVUse Op : Ops)
4343 ID.AddPointer(Op.getOpaqueValue());
4345 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4346 if (ExistingSCEV)
4347 return ExistingSCEV;
4348
4349 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4351 SCEV *S = new (SCEVAllocator)
4352 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4353
4354 UniqueSCEVs.insert(S, Token);
4355 S->computeAndSetCanonical(*this);
4356 registerUser(S, Ops);
4357 return S;
4358}
4359
4364
4368
4373
4377
4382
4386
4388 bool Sequential) {
4389 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4390 return getUMinExpr(Ops, Sequential);
4391}
4392
4398
4399const SCEV *
4401 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4402 if (Size.isScalable())
4403 Res = getMulExpr(Res, getVScale(IntTy));
4404 return Res;
4405}
4406
4408 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4409}
4410
4412 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4413}
4414
4416 StructType *STy,
4417 unsigned FieldNo) {
4418 // We can bypass creating a target-independent constant expression and then
4419 // folding it back into a ConstantInt. This is just a compile-time
4420 // optimization.
4421 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4422 assert(!SL->getSizeInBits().isScalable() &&
4423 "Cannot get offset for structure containing scalable vector types");
4424 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4425}
4426
4428 // Don't attempt to do anything other than create a SCEVUnknown object
4429 // here. createSCEV only calls getUnknown after checking for all other
4430 // interesting possibilities, and any other code that calls getUnknown
4431 // is doing so in order to hide a value from SCEV canonicalization.
4432
4435 ID.AddPointer(V);
4437 if (SCEV *S = UniqueSCEVs.lookup(ID, Token)) {
4438 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4439 "Stale SCEVUnknown in uniquing map!");
4440 return S;
4441 }
4442 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4443 FirstUnknown);
4444 FirstUnknown = cast<SCEVUnknown>(S);
4445 UniqueSCEVs.insert(S, Token);
4446 S->computeAndSetCanonical(*this);
4447 return S;
4448}
4449
4450//===----------------------------------------------------------------------===//
4451// Basic SCEV Analysis and PHI Idiom Recognition Code
4452//
4453
4454/// Test if values of the given type are analyzable within the SCEV
4455/// framework. This primarily includes integer types, and it can optionally
4456/// include pointer types if the ScalarEvolution class has access to
4457/// target-specific information.
4459 // Integers and pointers are always SCEVable.
4460 return Ty->isIntOrPtrTy();
4461}
4462
4463/// Return the size in bits of the specified type, for which isSCEVable must
4464/// return true.
4466 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4467 if (Ty->isPointerTy())
4469 return getDataLayout().getTypeSizeInBits(Ty);
4470}
4471
4472/// Return a type with the same bitwidth as the given type and which represents
4473/// how SCEV will treat the given type, for which isSCEVable must return
4474/// true. For pointer types, this is the pointer index sized integer type.
4476 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4477
4478 if (Ty->isIntegerTy())
4479 return Ty;
4480
4481 // The only other support type is pointer.
4482 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4483 return getDataLayout().getIndexType(Ty);
4484}
4485
4487 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4488}
4489
4491 const SCEV *B) {
4492 /// For a valid use point to exist, the defining scope of one operand
4493 /// must dominate the other.
4494 bool PreciseA, PreciseB;
4495 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4496 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4497 if (!PreciseA || !PreciseB)
4498 // Can't tell.
4499 return false;
4500 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4501 DT.dominates(ScopeB, ScopeA);
4502}
4503
4505 return CouldNotCompute.get();
4506}
4507
4508bool ScalarEvolution::checkValidity(const SCEV *S) const {
4509 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4510 auto *SU = dyn_cast<SCEVUnknown>(S);
4511 return SU && SU->getValue() == nullptr;
4512 });
4513
4514 return !ContainsNulls;
4515}
4516
4518 HasRecMapType::iterator I = HasRecMap.find(S);
4519 if (I != HasRecMap.end())
4520 return I->second;
4521
4522 bool FoundAddRec =
4523 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4524 HasRecMap.insert({S, FoundAddRec});
4525 return FoundAddRec;
4526}
4527
4528/// Return the ValueOffsetPair set for \p S. \p S can be represented
4529/// by the value and offset from any ValueOffsetPair in the set.
4530ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4531 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4532 if (SI == ExprValueMap.end())
4533 return {};
4534 return SI->second.getArrayRef();
4535}
4536
4537/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4538/// cannot be used separately. eraseValueFromMap should be used to remove
4539/// V from ValueExprMap and ExprValueMap at the same time.
4540void ScalarEvolution::eraseValueFromMap(Value *V) {
4541 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4542 if (I != ValueExprMap.end()) {
4543 auto EVIt = ExprValueMap.find(I->second);
4544 bool Removed = EVIt->second.remove(V);
4545 (void) Removed;
4546 assert(Removed && "Value not in ExprValueMap?");
4547 ValueExprMap.erase(I);
4548 }
4549}
4550
4551void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4552 // A recursive query may have already computed the SCEV. It should be
4553 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4554 // inferred nowrap flags.
4555 auto It = ValueExprMap.find_as(V);
4556 if (It == ValueExprMap.end()) {
4557 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4558 ExprValueMap[S].insert(V);
4559 }
4560}
4561
4562/// Return an existing SCEV if it exists, otherwise analyze the expression and
4563/// create a new one.
4565 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4566
4567 if (const SCEV *S = getExistingSCEV(V))
4568 return S;
4569 return createSCEVIter(V);
4570}
4571
4573 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4574
4575 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4576 if (I != ValueExprMap.end()) {
4577 const SCEV *S = I->second;
4578 assert(checkValidity(S) &&
4579 "existing SCEV has not been properly invalidated");
4580 return S;
4581 }
4582 return nullptr;
4583}
4584
4585/// Return a SCEV corresponding to -V = -1*V
4587 SCEV::NoWrapFlags Flags) {
4588 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4589 return getConstant(
4590 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4591
4592 Type *Ty = V->getType();
4593 Ty = getEffectiveSCEVType(Ty);
4594 return getMulExpr(V, getMinusOne(Ty), Flags);
4595}
4596
4597/// If Expr computes ~A, return A else return nullptr
4598static const SCEV *MatchNotExpr(const SCEV *Expr) {
4599 const SCEV *MulOp;
4600 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4601 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4602 return MulOp;
4603 return nullptr;
4604}
4605
4606/// Return a SCEV corresponding to ~V = -1-V
4608 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4609
4610 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4611 return getConstant(
4612 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4613
4614 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4615 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4616 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4617 SmallVector<SCEVUse, 2> MatchedOperands;
4618 for (const SCEV *Operand : MME->operands()) {
4619 const SCEV *Matched = MatchNotExpr(Operand);
4620 if (!Matched)
4621 return (const SCEV *)nullptr;
4622 MatchedOperands.push_back(Matched);
4623 }
4624 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4625 MatchedOperands);
4626 };
4627 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4628 return Replaced;
4629 }
4630
4631 Type *Ty = V->getType();
4632 Ty = getEffectiveSCEVType(Ty);
4633 return getMinusSCEV(getMinusOne(Ty), V);
4634}
4635
4637 assert(P->getType()->isPointerTy());
4638
4639 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4640 // The base of an AddRec is the first operand.
4641 SmallVector<SCEVUse> Ops{AddRec->operands()};
4642 Ops[0] = removePointerBase(Ops[0]);
4643 // Don't try to transfer nowrap flags for now. We could in some cases
4644 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4645 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4646 }
4647 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4648 // The base of an Add is the pointer operand.
4649 SmallVector<SCEVUse> Ops{Add->operands()};
4650 SCEVUse *PtrOp = nullptr;
4651 for (SCEVUse &AddOp : Ops) {
4652 if (AddOp->getType()->isPointerTy()) {
4653 assert(!PtrOp && "Cannot have multiple pointer ops");
4654 PtrOp = &AddOp;
4655 }
4656 }
4657 *PtrOp = removePointerBase(*PtrOp);
4658 // Don't try to transfer nowrap flags for now. We could in some cases
4659 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4660 return getAddExpr(Ops);
4661 }
4662 // Any other expression must be a pointer base.
4663 return getZero(P->getType());
4664}
4665
4667 SCEV::NoWrapFlags Flags,
4668 unsigned Depth) {
4669 // Fast path: X - X --> 0.
4670 if (LHS == RHS)
4671 return getZero(LHS->getType());
4672
4673 // If we subtract two pointers with different pointer bases, bail.
4674 // Eventually, we're going to add an assertion to getMulExpr that we
4675 // can't multiply by a pointer.
4676 if (RHS->getType()->isPointerTy()) {
4677 if (!LHS->getType()->isPointerTy() ||
4678 getPointerBase(LHS) != getPointerBase(RHS))
4679 return getCouldNotCompute();
4680 LHS = removePointerBase(LHS);
4681 RHS = removePointerBase(RHS);
4682 }
4683
4684 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4685 // makes it so that we cannot make much use of NUW.
4686 auto AddFlags = SCEV::FlagAnyWrap;
4687 const bool RHSIsNotMinSigned =
4689 if (hasFlags(Flags, SCEV::FlagNSW)) {
4690 // Let M be the minimum representable signed value. Then (-1)*RHS
4691 // signed-wraps if and only if RHS is M. That can happen even for
4692 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4693 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4694 // (-1)*RHS, we need to prove that RHS != M.
4695 //
4696 // If LHS is non-negative and we know that LHS - RHS does not
4697 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4698 // either by proving that RHS > M or that LHS >= 0.
4699 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4700 AddFlags = SCEV::FlagNSW;
4701 }
4702 }
4703
4704 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4705 // RHS is NSW and LHS >= 0.
4706 //
4707 // The difficulty here is that the NSW flag may have been proven
4708 // relative to a loop that is to be found in a recurrence in LHS and
4709 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4710 // larger scope than intended.
4711 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4712
4713 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4714}
4715
4717 unsigned Depth) {
4718 Type *SrcTy = V->getType();
4719 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4720 "Cannot truncate or zero extend with non-integer arguments!");
4721 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4722 return V; // No conversion
4723 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4724 return getTruncateExpr(V, Ty, Depth);
4725 return getZeroExtendExpr(V, Ty, Depth);
4726}
4727
4729 unsigned Depth) {
4730 Type *SrcTy = V->getType();
4731 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4732 "Cannot truncate or zero extend with non-integer arguments!");
4733 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4734 return V; // No conversion
4735 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4736 return getTruncateExpr(V, Ty, Depth);
4737 return getSignExtendExpr(V, Ty, Depth);
4738}
4739
4741 Type *SrcTy = V->getType();
4742 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4743 "Cannot noop or zero extend with non-integer arguments!");
4745 "getNoopOrZeroExtend cannot truncate!");
4746 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4747 return V; // No conversion
4748 return getZeroExtendExpr(V, Ty);
4749}
4750
4752 Type *SrcTy = V->getType();
4753 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4754 "Cannot noop or sign extend with non-integer arguments!");
4756 "getNoopOrSignExtend cannot truncate!");
4757 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4758 return V; // No conversion
4759 return getSignExtendExpr(V, Ty);
4760}
4761
4763 Type *SrcTy = V->getType();
4764 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4765 "Cannot noop or any extend with non-integer arguments!");
4767 "getNoopOrAnyExtend cannot truncate!");
4768 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4769 return V; // No conversion
4770 return getAnyExtendExpr(V, Ty);
4771}
4772
4774 Type *SrcTy = V->getType();
4775 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4776 "Cannot truncate or noop with non-integer arguments!");
4778 "getTruncateOrNoop cannot extend!");
4779 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4780 return V; // No conversion
4781 return getTruncateExpr(V, Ty);
4782}
4783
4785 const SCEV *RHS) {
4786 const SCEV *PromotedLHS = LHS;
4787 const SCEV *PromotedRHS = RHS;
4788
4789 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4790 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4791 else
4792 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4793
4794 return getUMaxExpr(PromotedLHS, PromotedRHS);
4795}
4796
4798 const SCEV *RHS,
4799 bool Sequential) {
4800 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4801 return getUMinFromMismatchedTypes(Ops, Sequential);
4802}
4803
4804const SCEV *
4806 bool Sequential) {
4807 assert(!Ops.empty() && "At least one operand must be!");
4808 // Trivial case.
4809 if (Ops.size() == 1)
4810 return Ops[0];
4811
4812 // Find the max type first.
4813 Type *MaxType = nullptr;
4814 for (SCEVUse S : Ops)
4815 if (MaxType)
4816 MaxType = getWiderType(MaxType, S->getType());
4817 else
4818 MaxType = S->getType();
4819 assert(MaxType && "Failed to find maximum type!");
4820
4821 // Extend all ops to max type.
4822 SmallVector<SCEVUse, 2> PromotedOps;
4823 for (SCEVUse S : Ops)
4824 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4825
4826 // Generate umin.
4827 return getUMinExpr(PromotedOps, Sequential);
4828}
4829
4831 // A pointer operand may evaluate to a nonpointer expression, such as null.
4832 if (!V->getType()->isPointerTy())
4833 return V;
4834
4835 while (true) {
4836 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4837 V = AddRec->getStart();
4838 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4839 const SCEV *PtrOp = nullptr;
4840 for (const SCEV *AddOp : Add->operands()) {
4841 if (AddOp->getType()->isPointerTy()) {
4842 assert(!PtrOp && "Cannot have multiple pointer ops");
4843 PtrOp = AddOp;
4844 }
4845 }
4846 assert(PtrOp && "Must have pointer op");
4847 V = PtrOp;
4848 } else // Not something we can look further into.
4849 return V;
4850 }
4851}
4852
4853/// Push users of the given Instruction onto the given Worklist.
4857 // Push the def-use children onto the Worklist stack.
4858 for (User *U : I->users()) {
4859 auto *UserInsn = cast<Instruction>(U);
4860 if (Visited.insert(UserInsn).second)
4861 Worklist.push_back(UserInsn);
4862 }
4863}
4864
4865namespace {
4866
4867/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4868/// expression in case its Loop is L. If it is not L then
4869/// if IgnoreOtherLoops is true then use AddRec itself
4870/// otherwise rewrite cannot be done.
4871/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4872class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4873public:
4874 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4875 bool IgnoreOtherLoops = true) {
4876 SCEVInitRewriter Rewriter(L, SE);
4877 const SCEV *Result = Rewriter.visit(S);
4878 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4879 return SE.getCouldNotCompute();
4880 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4881 ? SE.getCouldNotCompute()
4882 : Result;
4883 }
4884
4885 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4886 if (!SE.isLoopInvariant(Expr, L))
4887 SeenLoopVariantSCEVUnknown = true;
4888 return Expr;
4889 }
4890
4891 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4892 // Only re-write AddRecExprs for this loop.
4893 if (Expr->getLoop() == L)
4894 return Expr->getStart();
4895 SeenOtherLoops = true;
4896 return Expr;
4897 }
4898
4899 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4900
4901 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4902
4903private:
4904 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4905 : SCEVRewriteVisitor(SE), L(L) {}
4906
4907 const Loop *L;
4908 bool SeenLoopVariantSCEVUnknown = false;
4909 bool SeenOtherLoops = false;
4910};
4911
4912/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4913/// increment expression in case its Loop is L. If it is not L then
4914/// use AddRec itself.
4915/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4916class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4917public:
4918 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4919 SCEVPostIncRewriter Rewriter(L, SE);
4920 const SCEV *Result = Rewriter.visit(S);
4921 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4922 ? SE.getCouldNotCompute()
4923 : Result;
4924 }
4925
4926 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4927 if (!SE.isLoopInvariant(Expr, L))
4928 SeenLoopVariantSCEVUnknown = true;
4929 return Expr;
4930 }
4931
4932 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4933 // Only re-write AddRecExprs for this loop.
4934 if (Expr->getLoop() == L)
4935 return Expr->getPostIncExpr(SE);
4936 SeenOtherLoops = true;
4937 return Expr;
4938 }
4939
4940 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4941
4942 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4943
4944private:
4945 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4946 : SCEVRewriteVisitor(SE), L(L) {}
4947
4948 const Loop *L;
4949 bool SeenLoopVariantSCEVUnknown = false;
4950 bool SeenOtherLoops = false;
4951};
4952
4953/// This class evaluates the compare condition by matching it against the
4954/// condition of loop latch. If there is a match we assume a true value
4955/// for the condition while building SCEV nodes.
4956class SCEVBackedgeConditionFolder
4957 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4958public:
4959 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4960 ScalarEvolution &SE) {
4961 bool IsPosBECond = false;
4962 Value *BECond = nullptr;
4963 if (BasicBlock *Latch = L->getLoopLatch()) {
4964 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
4965 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4966 "Both outgoing branches should not target same header!");
4967 BECond = BI->getCondition();
4968 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4969 } else {
4970 return S;
4971 }
4972 }
4973 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4974 return Rewriter.visit(S);
4975 }
4976
4977 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4978 const SCEV *Result = Expr;
4979 bool InvariantF = SE.isLoopInvariant(Expr, L);
4980
4981 if (!InvariantF) {
4983 switch (I->getOpcode()) {
4984 case Instruction::Select: {
4985 SelectInst *SI = cast<SelectInst>(I);
4986 std::optional<const SCEV *> Res =
4987 compareWithBackedgeCondition(SI->getCondition());
4988 if (Res) {
4989 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4990 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4991 }
4992 break;
4993 }
4994 default: {
4995 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4996 if (Res)
4997 Result = *Res;
4998 break;
4999 }
5000 }
5001 }
5002 return Result;
5003 }
5004
5005private:
5006 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
5007 bool IsPosBECond, ScalarEvolution &SE)
5008 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
5009 IsPositiveBECond(IsPosBECond) {}
5010
5011 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
5012
5013 const Loop *L;
5014 /// Loop back condition.
5015 Value *BackedgeCond = nullptr;
5016 /// Set to true if loop back is on positive branch condition.
5017 bool IsPositiveBECond;
5018};
5019
5020std::optional<const SCEV *>
5021SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
5022
5023 // If value matches the backedge condition for loop latch,
5024 // then return a constant evolution node based on loopback
5025 // branch taken.
5026 if (BackedgeCond == IC)
5027 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
5029 return std::nullopt;
5030}
5031
5032class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5033public:
5034 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5035 ScalarEvolution &SE) {
5036 SCEVShiftRewriter Rewriter(L, SE);
5037 const SCEV *Result = Rewriter.visit(S);
5038 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5039 }
5040
5041 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5042 // Only allow AddRecExprs for this loop.
5043 if (!SE.isLoopInvariant(Expr, L))
5044 Valid = false;
5045 return Expr;
5046 }
5047
5048 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5049 if (Expr->getLoop() == L && Expr->isAffine())
5050 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5051 Valid = false;
5052 return Expr;
5053 }
5054
5055 bool isValid() { return Valid; }
5056
5057private:
5058 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5059 : SCEVRewriteVisitor(SE), L(L) {}
5060
5061 const Loop *L;
5062 bool Valid = true;
5063};
5064
5065} // end anonymous namespace
5066
5067void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5068 if (!AR->isAffine())
5069 return;
5070
5071 // Force computation of ranges, which will also perform range-based flag
5072 // inference.
5073 if (!AR->hasNoSignedWrap())
5074 (void)getSignedRange(AR);
5075
5076 if (!AR->hasNoUnsignedWrap())
5077 (void)getUnsignedRange(AR);
5078
5079 if (!AR->hasNoSelfWrap()) {
5080 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5081 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5082 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5083 const APInt &BECountAP = BECountMax->getAPInt();
5084 unsigned NoOverflowBitWidth =
5085 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5086 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5087 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5088 }
5089 }
5090}
5091
5093ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5095
5096 if (AR->hasNoSignedWrap())
5097 return Result;
5098
5099 if (!AR->isAffine())
5100 return Result;
5101
5102 // This function can be expensive, only try to prove NSW once per AddRec.
5103 if (!SignedWrapViaInductionTried.insert(AR).second)
5104 return Result;
5105
5106 const SCEV *Step = AR->getStepRecurrence(*this);
5107 const Loop *L = AR->getLoop();
5108
5109 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5110 // Note that this serves two purposes: It filters out loops that are
5111 // simply not analyzable, and it covers the case where this code is
5112 // being called from within backedge-taken count analysis, such that
5113 // attempting to ask for the backedge-taken count would likely result
5114 // in infinite recursion. In the later case, the analysis code will
5115 // cope with a conservative value, and it will take care to purge
5116 // that value once it has finished.
5117 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5118
5119 // Normally, in the cases we can prove no-overflow via a
5120 // backedge guarding condition, we can also compute a backedge
5121 // taken count for the loop. The exceptions are assumptions and
5122 // guards present in the loop -- SCEV is not great at exploiting
5123 // these to compute max backedge taken counts, but can still use
5124 // these to prove lack of overflow. Use this fact to avoid
5125 // doing extra work that may not pay off.
5126
5127 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5128 AC.assumptions().empty())
5129 return Result;
5130
5131 // If the backedge is guarded by a comparison with the pre-inc value the
5132 // addrec is safe. Also, if the entry is guarded by a comparison with the
5133 // start value and the backedge is guarded by a comparison with the post-inc
5134 // value, the addrec is safe.
5136 const SCEV *OverflowLimit =
5137 getSignedOverflowLimitForStep(Step, &Pred, this);
5138 if (OverflowLimit &&
5139 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5140 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5141 Result = setFlags(Result, SCEV::FlagNSW);
5142 }
5143 return Result;
5144}
5146ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5148
5149 if (AR->hasNoUnsignedWrap())
5150 return Result;
5151
5152 if (!AR->isAffine())
5153 return Result;
5154
5155 // This function can be expensive, only try to prove NUW once per AddRec.
5156 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5157 return Result;
5158
5159 const SCEV *Step = AR->getStepRecurrence(*this);
5160 const Loop *L = AR->getLoop();
5161
5162 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5163 // Note that this serves two purposes: It filters out loops that are
5164 // simply not analyzable, and it covers the case where this code is
5165 // being called from within backedge-taken count analysis, such that
5166 // attempting to ask for the backedge-taken count would likely result
5167 // in infinite recursion. In the later case, the analysis code will
5168 // cope with a conservative value, and it will take care to purge
5169 // that value once it has finished.
5170 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5171
5172 // Normally, in the cases we can prove no-overflow via a
5173 // backedge guarding condition, we can also compute a backedge
5174 // taken count for the loop. The exceptions are assumptions and
5175 // guards present in the loop -- SCEV is not great at exploiting
5176 // these to compute max backedge taken counts, but can still use
5177 // these to prove lack of overflow. Use this fact to avoid
5178 // doing extra work that may not pay off.
5179
5180 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5181 AC.assumptions().empty())
5182 return Result;
5183
5184 // If the backedge is guarded by a comparison with the pre-inc value the
5185 // addrec is safe. Also, if the entry is guarded by a comparison with the
5186 // start value and the backedge is guarded by a comparison with the post-inc
5187 // value, the addrec is safe.
5188 if (isKnownPositive(Step)) {
5190 const SCEV *OverflowLimit =
5191 getUnsignedOverflowLimitForStep(Step, &Pred, this);
5192 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5193 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5194 Result = setFlags(Result, SCEV::FlagNUW);
5195 }
5196 return Result;
5197}
5198
5199namespace {
5200
5201/// Represents an abstract binary operation. This may exist as a
5202/// normal instruction or constant expression, or may have been
5203/// derived from an expression tree.
5204struct BinaryOp {
5205 unsigned Opcode;
5206 Value *LHS;
5207 Value *RHS;
5208 bool IsNSW = false;
5209 bool IsNUW = false;
5210
5211 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5212 /// constant expression.
5213 Operator *Op = nullptr;
5214
5215 explicit BinaryOp(Operator *Op)
5216 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5217 Op(Op) {
5218 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5219 IsNSW = OBO->hasNoSignedWrap();
5220 IsNUW = OBO->hasNoUnsignedWrap();
5221 }
5222 }
5223
5224 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5225 bool IsNUW = false)
5226 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5227};
5228
5229} // end anonymous namespace
5230
5231/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5232static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5233 AssumptionCache &AC,
5234 const DominatorTree &DT,
5235 const Instruction *CxtI) {
5236 auto *Op = dyn_cast<Operator>(V);
5237 if (!Op)
5238 return std::nullopt;
5239
5240 // Implementation detail: all the cleverness here should happen without
5241 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5242 // SCEV expressions when possible, and we should not break that.
5243
5244 switch (Op->getOpcode()) {
5245 case Instruction::Add:
5246 case Instruction::Sub:
5247 case Instruction::Mul:
5248 case Instruction::UDiv:
5249 case Instruction::URem:
5250 case Instruction::And:
5251 case Instruction::AShr:
5252 case Instruction::Shl:
5253 return BinaryOp(Op);
5254
5255 case Instruction::Or: {
5256 // Convert or disjoint into add nuw nsw.
5257 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5258 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5259 /*IsNSW=*/true, /*IsNUW=*/true);
5260 // Keep the reference to the original instruction so that we can later
5261 // check whether it can produce poison value or not.
5262 BinOp.Op = Op;
5263 return BinOp;
5264 }
5265 return BinaryOp(Op);
5266 }
5267
5268 case Instruction::Xor:
5269 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5270 // If the RHS of the xor is a signmask, then this is just an add.
5271 // Instcombine turns add of signmask into xor as a strength reduction step.
5272 if (RHSC->getValue().isSignMask())
5273 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5274 // Binary `xor` is a bit-wise `add`.
5275 if (V->getType()->isIntegerTy(1))
5276 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5277 return BinaryOp(Op);
5278
5279 case Instruction::LShr:
5280 // Turn logical shift right of a constant into a unsigned divide.
5281 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5282 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5283
5284 // If the shift count is not less than the bitwidth, the result of
5285 // the shift is undefined. Don't try to analyze it, because the
5286 // resolution chosen here may differ from the resolution chosen in
5287 // other parts of the compiler.
5288 if (SA->getValue().ult(BitWidth)) {
5289 Constant *X =
5290 ConstantInt::get(SA->getContext(),
5291 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5292 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5293 }
5294 }
5295 return BinaryOp(Op);
5296
5297 case Instruction::ExtractValue: {
5298 auto *EVI = cast<ExtractValueInst>(Op);
5299 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5300 break;
5301
5302 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5303 if (!WO)
5304 break;
5305
5306 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5307 bool Signed = WO->isSigned();
5308 // TODO: Should add nuw/nsw flags for mul as well.
5309 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5310 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5311
5312 // Now that we know that all uses of the arithmetic-result component of
5313 // CI are guarded by the overflow check, we can go ahead and pretend
5314 // that the arithmetic is non-overflowing.
5315 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5316 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5317 }
5318
5319 default:
5320 break;
5321 }
5322
5323 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5324 // semantics as a Sub, return a binary sub expression.
5325 if (auto *II = dyn_cast<IntrinsicInst>(V))
5326 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5327 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5328
5329 return std::nullopt;
5330}
5331
5332/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5333/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5334/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5335/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5336/// follows one of the following patterns:
5337/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5338/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5339/// If the SCEV expression of \p Op conforms with one of the expected patterns
5340/// we return the type of the truncation operation, and indicate whether the
5341/// truncated type should be treated as signed/unsigned by setting
5342/// \p Signed to true/false, respectively.
5343static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5344 bool &Signed, ScalarEvolution &SE) {
5345 // The case where Op == SymbolicPHI (that is, with no type conversions on
5346 // the way) is handled by the regular add recurrence creating logic and
5347 // would have already been triggered in createAddRecForPHI. Reaching it here
5348 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5349 // because one of the other operands of the SCEVAddExpr updating this PHI is
5350 // not invariant).
5351 //
5352 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5353 // this case predicates that allow us to prove that Op == SymbolicPHI will
5354 // be added.
5355 if (Op == SymbolicPHI)
5356 return nullptr;
5357
5358 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5359 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5360 if (SourceBits != NewBits)
5361 return nullptr;
5362
5363 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5364 Signed = true;
5365 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5366 }
5367 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5368 Signed = false;
5369 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5370 }
5371 return nullptr;
5372}
5373
5374static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5375 if (!PN->getType()->isIntegerTy())
5376 return nullptr;
5377 const Loop *L = LI.getLoopFor(PN->getParent());
5378 if (!L || L->getHeader() != PN->getParent())
5379 return nullptr;
5380 return L;
5381}
5382
5383// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5384// computation that updates the phi follows the following pattern:
5385// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5386// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5387// If so, try to see if it can be rewritten as an AddRecExpr under some
5388// Predicates. If successful, return them as a pair. Also cache the results
5389// of the analysis.
5390//
5391// Example usage scenario:
5392// Say the Rewriter is called for the following SCEV:
5393// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5394// where:
5395// %X = phi i64 (%Start, %BEValue)
5396// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5397// and call this function with %SymbolicPHI = %X.
5398//
5399// The analysis will find that the value coming around the backedge has
5400// the following SCEV:
5401// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5402// Upon concluding that this matches the desired pattern, the function
5403// will return the pair {NewAddRec, SmallPredsVec} where:
5404// NewAddRec = {%Start,+,%Step}
5405// SmallPredsVec = {P1, P2, P3} as follows:
5406// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5407// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5408// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5409// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5410// under the predicates {P1,P2,P3}.
5411// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5412// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5413//
5414// TODO's:
5415//
5416// 1) Extend the Induction descriptor to also support inductions that involve
5417// casts: When needed (namely, when we are called in the context of the
5418// vectorizer induction analysis), a Set of cast instructions will be
5419// populated by this method, and provided back to isInductionPHI. This is
5420// needed to allow the vectorizer to properly record them to be ignored by
5421// the cost model and to avoid vectorizing them (otherwise these casts,
5422// which are redundant under the runtime overflow checks, will be
5423// vectorized, which can be costly).
5424//
5425// 2) Support additional induction/PHISCEV patterns: We also want to support
5426// inductions where the sext-trunc / zext-trunc operations (partly) occur
5427// after the induction update operation (the induction increment):
5428//
5429// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5430// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5431//
5432// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5433// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5434//
5435// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5436std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5437ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5439
5440 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5441 // return an AddRec expression under some predicate.
5442
5443 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5444 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5445 assert(L && "Expecting an integer loop header phi");
5446
5447 // The loop may have multiple entrances or multiple exits; we can analyze
5448 // this phi as an addrec if it has a unique entry value and a unique
5449 // backedge value.
5450 Value *BEValueV = nullptr, *StartValueV = nullptr;
5451 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5452 Value *V = PN->getIncomingValue(i);
5453 if (L->contains(PN->getIncomingBlock(i))) {
5454 if (!BEValueV) {
5455 BEValueV = V;
5456 } else if (BEValueV != V) {
5457 BEValueV = nullptr;
5458 break;
5459 }
5460 } else if (!StartValueV) {
5461 StartValueV = V;
5462 } else if (StartValueV != V) {
5463 StartValueV = nullptr;
5464 break;
5465 }
5466 }
5467 if (!BEValueV || !StartValueV)
5468 return std::nullopt;
5469
5470 const SCEV *BEValue = getSCEV(BEValueV);
5471
5472 // If the value coming around the backedge is an add with the symbolic
5473 // value we just inserted, possibly with casts that we can ignore under
5474 // an appropriate runtime guard, then we found a simple induction variable!
5475 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5476 if (!Add)
5477 return std::nullopt;
5478
5479 // If there is a single occurrence of the symbolic value, possibly
5480 // casted, replace it with a recurrence.
5481 unsigned FoundIndex = Add->getNumOperands();
5482 Type *TruncTy = nullptr;
5483 bool Signed;
5484 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5485 if ((TruncTy =
5486 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5487 if (FoundIndex == e) {
5488 FoundIndex = i;
5489 break;
5490 }
5491
5492 if (FoundIndex == Add->getNumOperands())
5493 return std::nullopt;
5494
5495 // Create an add with everything but the specified operand.
5497 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5498 if (i != FoundIndex)
5499 Ops.push_back(Add->getOperand(i));
5500 const SCEV *Accum = getAddExpr(Ops);
5501
5502 // The runtime checks will not be valid if the step amount is
5503 // varying inside the loop.
5504 if (!isLoopInvariant(Accum, L))
5505 return std::nullopt;
5506
5507 // *** Part2: Create the predicates
5508
5509 // Analysis was successful: we have a phi-with-cast pattern for which we
5510 // can return an AddRec expression under the following predicates:
5511 //
5512 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5513 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5514 // P2: An Equal predicate that guarantees that
5515 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5516 // P3: An Equal predicate that guarantees that
5517 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5518 //
5519 // As we next prove, the above predicates guarantee that:
5520 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5521 //
5522 //
5523 // More formally, we want to prove that:
5524 // Expr(i+1) = Start + (i+1) * Accum
5525 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5526 //
5527 // Given that:
5528 // 1) Expr(0) = Start
5529 // 2) Expr(1) = Start + Accum
5530 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5531 // 3) Induction hypothesis (step i):
5532 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5533 //
5534 // Proof:
5535 // Expr(i+1) =
5536 // = Start + (i+1)*Accum
5537 // = (Start + i*Accum) + Accum
5538 // = Expr(i) + Accum
5539 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5540 // :: from step i
5541 //
5542 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5543 //
5544 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5545 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5546 // + Accum :: from P3
5547 //
5548 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5549 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5550 //
5551 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5552 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5553 //
5554 // By induction, the same applies to all iterations 1<=i<n:
5555 //
5556
5557 // Create a truncated addrec for which we will add a no overflow check (P1).
5558 const SCEV *StartVal = getSCEV(StartValueV);
5559 const SCEV *PHISCEV =
5560 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5561 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5562
5563 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5564 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5565 // will be constant.
5566 //
5567 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5568 // add P1.
5569 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5573 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5574 Predicates.push_back(AddRecPred);
5575 }
5576
5577 // Create the Equal Predicates P2,P3:
5578
5579 // It is possible that the predicates P2 and/or P3 are computable at
5580 // compile time due to StartVal and/or Accum being constants.
5581 // If either one is, then we can check that now and escape if either P2
5582 // or P3 is false.
5583
5584 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5585 // for each of StartVal and Accum
5586 auto getExtendedExpr = [&](const SCEV *Expr,
5587 bool CreateSignExtend) -> const SCEV * {
5588 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5589 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5590 const SCEV *ExtendedExpr =
5591 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5592 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5593 return ExtendedExpr;
5594 };
5595
5596 // Given:
5597 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5598 // = getExtendedExpr(Expr)
5599 // Determine whether the predicate P: Expr == ExtendedExpr
5600 // is known to be false at compile time
5601 auto PredIsKnownFalse = [&](const SCEV *Expr,
5602 const SCEV *ExtendedExpr) -> bool {
5603 return Expr != ExtendedExpr &&
5604 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5605 };
5606
5607 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5608 if (PredIsKnownFalse(StartVal, StartExtended)) {
5609 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5610 return std::nullopt;
5611 }
5612
5613 // The Step is always Signed (because the overflow checks are either
5614 // NSSW or NUSW)
5615 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5616 if (PredIsKnownFalse(Accum, AccumExtended)) {
5617 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5618 return std::nullopt;
5619 }
5620
5621 auto AppendPredicate = [&](const SCEV *Expr,
5622 const SCEV *ExtendedExpr) -> void {
5623 if (Expr != ExtendedExpr &&
5624 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5625 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5626 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5627 Predicates.push_back(Pred);
5628 }
5629 };
5630
5631 AppendPredicate(StartVal, StartExtended);
5632 AppendPredicate(Accum, AccumExtended);
5633
5634 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5635 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5636 // into NewAR if it will also add the runtime overflow checks specified in
5637 // Predicates.
5638 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5639
5640 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5641 std::make_pair(NewAR, Predicates);
5642 // Remember the result of the analysis for this SCEV at this locayyytion.
5643 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5644 return PredRewrite;
5645}
5646
5647std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5649 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5650 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5651 if (!L)
5652 return std::nullopt;
5653
5654 // Check to see if we already analyzed this PHI.
5655 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5656 if (I != PredicatedSCEVRewrites.end()) {
5657 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5658 I->second;
5659 // Analysis was done before and failed to create an AddRec:
5660 if (Rewrite.first == SymbolicPHI)
5661 return std::nullopt;
5662 // Analysis was done before and succeeded to create an AddRec under
5663 // a predicate:
5664 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5665 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5666 return Rewrite;
5667 }
5668
5669 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5670 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5671
5672 // Record in the cache that the analysis failed
5673 if (!Rewrite) {
5675 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5676 return std::nullopt;
5677 }
5678
5679 return Rewrite;
5680}
5681
5682// FIXME: This utility is currently required because the Rewriter currently
5683// does not rewrite this expression:
5684// {0, +, (sext ix (trunc iy to ix) to iy)}
5685// into {0, +, %step},
5686// even when the following Equal predicate exists:
5687// "%step == (sext ix (trunc iy to ix) to iy)".
5689 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5690 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5691 if (AR1 == AR2)
5692 return true;
5693
5694 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5695 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5696 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5697 if (Expr1 != Expr2 &&
5698 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5699 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5700 return false;
5701 return true;
5702 };
5703
5704 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5705 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5706 return false;
5707 return true;
5708}
5709
5710/// A helper function for createAddRecFromPHI to handle simple cases.
5711///
5712/// This function tries to find an AddRec expression for the simplest (yet most
5713/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5714/// If it fails, createAddRecFromPHI will use a more general, but slow,
5715/// technique for finding the AddRec expression.
5716const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5717 Value *BEValueV,
5718 Value *StartValueV) {
5719 const Loop *L = LI.getLoopFor(PN->getParent());
5720 assert(L && L->getHeader() == PN->getParent());
5721 assert(BEValueV && StartValueV);
5722
5723 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5724 if (!BO)
5725 return nullptr;
5726
5727 if (BO->Opcode != Instruction::Add)
5728 return nullptr;
5729
5730 const SCEV *Accum = nullptr;
5731 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5732 Accum = getSCEV(BO->RHS);
5733 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5734 Accum = getSCEV(BO->LHS);
5735
5736 if (!Accum)
5737 return nullptr;
5738
5740 if (BO->IsNUW)
5741 Flags = setFlags(Flags, SCEV::FlagNUW);
5742 if (BO->IsNSW)
5743 Flags = setFlags(Flags, SCEV::FlagNSW);
5744
5745 const SCEV *StartVal = getSCEV(StartValueV);
5746 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5747 insertValueToMap(PN, PHISCEV);
5748
5749 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5750 inferNoWrapViaConstantRanges(AR);
5751
5752 // We can add Flags to the post-inc expression only if we
5753 // know that it is *undefined behavior* for BEValueV to
5754 // overflow.
5755 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5756 assert(isLoopInvariant(Accum, L) &&
5757 "Accum is defined outside L, but is not invariant?");
5758 if (isAddRecNeverPoison(BEInst, L))
5759 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5760 }
5761
5762 return PHISCEV;
5763}
5764
5765const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5766 const Loop *L = LI.getLoopFor(PN->getParent());
5767 if (!L || L->getHeader() != PN->getParent())
5768 return nullptr;
5769
5770 // The loop may have multiple entrances or multiple exits; we can analyze
5771 // this phi as an addrec if it has a unique entry value and a unique
5772 // backedge value.
5773 Value *BEValueV = nullptr, *StartValueV = nullptr;
5774 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5775 Value *V = PN->getIncomingValue(i);
5776 if (L->contains(PN->getIncomingBlock(i))) {
5777 if (!BEValueV) {
5778 BEValueV = V;
5779 } else if (BEValueV != V) {
5780 BEValueV = nullptr;
5781 break;
5782 }
5783 } else if (!StartValueV) {
5784 StartValueV = V;
5785 } else if (StartValueV != V) {
5786 StartValueV = nullptr;
5787 break;
5788 }
5789 }
5790 if (!BEValueV || !StartValueV)
5791 return nullptr;
5792
5793 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5794 "PHI node already processed?");
5795
5796 // First, try to find AddRec expression without creating a fictituos symbolic
5797 // value for PN.
5798 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5799 return S;
5800
5801 // Handle PHI node value symbolically.
5802 const SCEV *SymbolicName = getUnknown(PN);
5803 insertValueToMap(PN, SymbolicName);
5804
5805 // Using this symbolic name for the PHI, analyze the value coming around
5806 // the back-edge.
5807 const SCEV *BEValue = getSCEV(BEValueV);
5808
5809 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5810 // has a special value for the first iteration of the loop.
5811
5812 // If the value coming around the backedge is an add with the symbolic
5813 // value we just inserted, then we found a simple induction variable!
5814 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5815 // If there is a single occurrence of the symbolic value, replace it
5816 // with a recurrence.
5817 unsigned FoundIndex = Add->getNumOperands();
5818 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5819 if (Add->getOperand(i) == SymbolicName)
5820 if (FoundIndex == e) {
5821 FoundIndex = i;
5822 break;
5823 }
5824
5825 if (FoundIndex != Add->getNumOperands()) {
5826 // Create an add with everything but the specified operand.
5828 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5829 if (i != FoundIndex)
5830 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5831 L, *this));
5832 const SCEV *Accum = getAddExpr(Ops);
5833
5834 // This is not a valid addrec if the step amount is varying each
5835 // loop iteration, but is not itself an addrec in this loop.
5836 if (isLoopInvariant(Accum, L) ||
5837 (isa<SCEVAddRecExpr>(Accum) &&
5838 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5840
5841 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5842 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5843 if (BO->IsNUW)
5844 Flags = setFlags(Flags, SCEV::FlagNUW);
5845 if (BO->IsNSW)
5846 Flags = setFlags(Flags, SCEV::FlagNSW);
5847 }
5848 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5849 if (GEP->getOperand(0) == PN) {
5850 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5851 // If the increment has any nowrap flags, then we know the address
5852 // space cannot be wrapped around.
5853 if (NW != GEPNoWrapFlags::none())
5854 Flags = setFlags(Flags, SCEV::FlagNW);
5855 // If the GEP is nuw or nusw with non-negative offset, we know that
5856 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5857 // offset is treated as signed, while the base is unsigned.
5858 if (NW.hasNoUnsignedWrap() ||
5860 Flags = setFlags(Flags, SCEV::FlagNUW);
5861 }
5862
5863 // We cannot transfer nuw and nsw flags from subtraction
5864 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5865 // for instance.
5866 }
5867
5868 const SCEV *StartVal = getSCEV(StartValueV);
5869 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5870
5871 // Okay, for the entire analysis of this edge we assumed the PHI
5872 // to be symbolic. We now need to go back and purge all of the
5873 // entries for the scalars that use the symbolic expression.
5874 forgetMemoizedResults({SymbolicName});
5875 insertValueToMap(PN, PHISCEV);
5876
5877 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5878 inferNoWrapViaConstantRanges(AR);
5879
5880 // We can add Flags to the post-inc expression only if we
5881 // know that it is *undefined behavior* for BEValueV to
5882 // overflow.
5883 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5884 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5885 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5886
5887 return PHISCEV;
5888 }
5889 }
5890 } else {
5891 // Otherwise, this could be a loop like this:
5892 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5893 // In this case, j = {1,+,1} and BEValue is j.
5894 // Because the other in-value of i (0) fits the evolution of BEValue
5895 // i really is an addrec evolution.
5896 //
5897 // We can generalize this saying that i is the shifted value of BEValue
5898 // by one iteration:
5899 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5900
5901 // Do not allow refinement in rewriting of BEValue.
5902 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5903 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5904 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5905 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5906 const SCEV *StartVal = getSCEV(StartValueV);
5907 if (Start == StartVal) {
5908 // Okay, for the entire analysis of this edge we assumed the PHI
5909 // to be symbolic. We now need to go back and purge all of the
5910 // entries for the scalars that use the symbolic expression.
5911 forgetMemoizedResults({SymbolicName});
5912 insertValueToMap(PN, Shifted);
5913 return Shifted;
5914 }
5915 }
5916 }
5917
5918 // Remove the temporary PHI node SCEV that has been inserted while intending
5919 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5920 // as it will prevent later (possibly simpler) SCEV expressions to be added
5921 // to the ValueExprMap.
5922 eraseValueFromMap(PN);
5923
5924 return nullptr;
5925}
5926
5927// Try to match a control flow sequence that branches out at BI and merges back
5928// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5929// match.
5931 Value *&C, Value *&LHS, Value *&RHS) {
5932 C = BI->getCondition();
5933
5934 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5935 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5936
5937 Use &LeftUse = Merge->getOperandUse(0);
5938 Use &RightUse = Merge->getOperandUse(1);
5939
5940 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5941 LHS = LeftUse;
5942 RHS = RightUse;
5943 return true;
5944 }
5945
5946 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5947 LHS = RightUse;
5948 RHS = LeftUse;
5949 return true;
5950 }
5951
5952 return false;
5953}
5954
5956 Value *&Cond, Value *&LHS,
5957 Value *&RHS) {
5958 auto IsReachable =
5959 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5960 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5961 // Try to match
5962 //
5963 // br %cond, label %left, label %right
5964 // left:
5965 // br label %merge
5966 // right:
5967 // br label %merge
5968 // merge:
5969 // V = phi [ %x, %left ], [ %y, %right ]
5970 //
5971 // as "select %cond, %x, %y"
5972
5973 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5974 assert(IDom && "At least the entry block should dominate PN");
5975
5976 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5977 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5978 }
5979 return false;
5980}
5981
5982const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5983 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5984 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5987 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5988
5989 return nullptr;
5990}
5991
5993 BinaryOperator *CommonInst = nullptr;
5994 // Check if instructions are identical.
5995 for (Value *Incoming : PN->incoming_values()) {
5996 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
5997 if (!IncomingInst)
5998 return nullptr;
5999 if (CommonInst) {
6000 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
6001 return nullptr; // Not identical, give up
6002 } else {
6003 // Remember binary operator
6004 CommonInst = IncomingInst;
6005 }
6006 }
6007 return CommonInst;
6008}
6009
6010/// Returns SCEV for the first operand of a phi if all phi operands have
6011/// identical opcodes and operands
6012/// eg.
6013/// a: %add = %a + %b
6014/// br %c
6015/// b: %add1 = %a + %b
6016/// br %c
6017/// c: %phi = phi [%add, a], [%add1, b]
6018/// scev(%phi) => scev(%add)
6019const SCEV *
6020ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6021 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6022 if (!CommonInst)
6023 return nullptr;
6024
6025 // Check if SCEV exprs for instructions are identical.
6026 const SCEV *CommonSCEV = getSCEV(CommonInst);
6027 bool SCEVExprsIdentical =
6029 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6030 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6031}
6032
6033const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6034 if (const SCEV *S = createAddRecFromPHI(PN))
6035 return S;
6036
6037 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6038 // phi node for X.
6039 if (Value *V = simplifyInstruction(
6040 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6041 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6042 return getSCEV(V);
6043
6044 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6045 return S;
6046
6047 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6048 return S;
6049
6050 // If it's not a loop phi, we can't handle it yet.
6051 return getUnknown(PN);
6052}
6053
6054bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6055 SCEVTypes RootKind) {
6056 struct FindClosure {
6057 const SCEV *OperandToFind;
6058 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6059 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6060
6061 bool Found = false;
6062
6063 bool canRecurseInto(SCEVTypes Kind) const {
6064 // We can only recurse into the SCEV expression of the same effective type
6065 // as the type of our root SCEV expression, and into zero-extensions.
6066 return RootKind == Kind || NonSequentialRootKind == Kind ||
6067 scZeroExtend == Kind;
6068 };
6069
6070 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6071 : OperandToFind(OperandToFind), RootKind(RootKind),
6072 NonSequentialRootKind(
6074 RootKind)) {}
6075
6076 bool follow(const SCEV *S) {
6077 Found = S == OperandToFind;
6078
6079 return !isDone() && canRecurseInto(S->getSCEVType());
6080 }
6081
6082 bool isDone() const { return Found; }
6083 };
6084
6085 FindClosure FC(OperandToFind, RootKind);
6086 visitAll(Root, FC);
6087 return FC.Found;
6088}
6089
6090std::optional<const SCEV *>
6091ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6092 ICmpInst *Cond,
6093 Value *TrueVal,
6094 Value *FalseVal) {
6095 // Try to match some simple smax or umax patterns.
6096 auto *ICI = Cond;
6097
6098 Value *LHS = ICI->getOperand(0);
6099 Value *RHS = ICI->getOperand(1);
6100
6101 switch (ICI->getPredicate()) {
6102 case ICmpInst::ICMP_SLT:
6103 case ICmpInst::ICMP_SLE:
6104 case ICmpInst::ICMP_ULT:
6105 case ICmpInst::ICMP_ULE:
6106 std::swap(LHS, RHS);
6107 [[fallthrough]];
6108 case ICmpInst::ICMP_SGT:
6109 case ICmpInst::ICMP_SGE:
6110 case ICmpInst::ICMP_UGT:
6111 case ICmpInst::ICMP_UGE:
6112 // a > b ? a+x : b+x -> max(a, b)+x
6113 // a > b ? b+x : a+x -> min(a, b)+x
6115 bool Signed = ICI->isSigned();
6116 const SCEV *LA = getSCEV(TrueVal);
6117 const SCEV *RA = getSCEV(FalseVal);
6118 const SCEV *LS = getSCEV(LHS);
6119 const SCEV *RS = getSCEV(RHS);
6120 if (LA->getType()->isPointerTy()) {
6121 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6122 // Need to make sure we can't produce weird expressions involving
6123 // negated pointers.
6124 if (LA == LS && RA == RS)
6125 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6126 if (LA == RS && RA == LS)
6127 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6128 }
6129 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6130 if (Op->getType()->isPointerTy()) {
6133 return Op;
6134 }
6135 if (Signed)
6136 Op = getNoopOrSignExtend(Op, Ty);
6137 else
6138 Op = getNoopOrZeroExtend(Op, Ty);
6139 return Op;
6140 };
6141 LS = CoerceOperand(LS);
6142 RS = CoerceOperand(RS);
6144 break;
6145 const SCEV *LDiff = getMinusSCEV(LA, LS);
6146 const SCEV *RDiff = getMinusSCEV(RA, RS);
6147 if (LDiff == RDiff)
6148 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6149 LDiff);
6150 LDiff = getMinusSCEV(LA, RS);
6151 RDiff = getMinusSCEV(RA, LS);
6152 if (LDiff == RDiff)
6153 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6154 LDiff);
6155 }
6156 break;
6157 case ICmpInst::ICMP_NE:
6158 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6159 std::swap(TrueVal, FalseVal);
6160 [[fallthrough]];
6161 case ICmpInst::ICMP_EQ:
6162 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6165 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6166 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6167 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6168 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6169 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6170 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6171 return getAddExpr(getUMaxExpr(X, C), Y);
6172 }
6173 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6174 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6175 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6176 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6178 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6179 const SCEV *X = getSCEV(LHS);
6180 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6181 X = ZExt->getOperand();
6182 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6183 const SCEV *FalseValExpr = getSCEV(FalseVal);
6184 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6185 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6186 /*Sequential=*/true);
6187 }
6188 }
6189 break;
6190 default:
6191 break;
6192 }
6193
6194 return std::nullopt;
6195}
6196
6197static std::optional<const SCEV *>
6199 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6200 assert(CondExpr->getType()->isIntegerTy(1) &&
6201 TrueExpr->getType() == FalseExpr->getType() &&
6202 TrueExpr->getType()->isIntegerTy(1) &&
6203 "Unexpected operands of a select.");
6204
6205 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6206 // --> C + (umin_seq cond, x - C)
6207 //
6208 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6209 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6210 // --> C + (umin_seq ~cond, x - C)
6211
6212 // FIXME: while we can't legally model the case where both of the hands
6213 // are fully variable, we only require that the *difference* is constant.
6214 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6215 return std::nullopt;
6216
6217 const SCEV *X, *C;
6218 if (isa<SCEVConstant>(TrueExpr)) {
6219 CondExpr = SE->getNotSCEV(CondExpr);
6220 X = FalseExpr;
6221 C = TrueExpr;
6222 } else {
6223 X = TrueExpr;
6224 C = FalseExpr;
6225 }
6226 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6227 /*Sequential=*/true));
6228}
6229
6230static std::optional<const SCEV *>
6232 Value *FalseVal) {
6233 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6234 return std::nullopt;
6235
6236 const auto *SECond = SE->getSCEV(Cond);
6237 const auto *SETrue = SE->getSCEV(TrueVal);
6238 const auto *SEFalse = SE->getSCEV(FalseVal);
6239 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6240}
6241
6242const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6243 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6244 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6245 assert(TrueVal->getType() == FalseVal->getType() &&
6246 V->getType() == TrueVal->getType() &&
6247 "Types of select hands and of the result must match.");
6248
6249 // For now, only deal with i1-typed `select`s.
6250 if (!V->getType()->isIntegerTy(1))
6251 return getUnknown(V);
6252
6253 if (std::optional<const SCEV *> S =
6254 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6255 return *S;
6256
6257 return getUnknown(V);
6258}
6259
6260const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6261 Value *TrueVal,
6262 Value *FalseVal) {
6263 // Handle "constant" branch or select. This can occur for instance when a
6264 // loop pass transforms an inner loop and moves on to process the outer loop.
6265 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6266 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6267
6268 if (auto *I = dyn_cast<Instruction>(V)) {
6269 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6270 if (std::optional<const SCEV *> S =
6271 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6272 TrueVal, FalseVal))
6273 return *S;
6274 }
6275 }
6276
6277 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6278}
6279
6280/// Expand GEP instructions into add and multiply operations. This allows them
6281/// to be analyzed by regular SCEV code.
6282const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6283 assert(GEP->getSourceElementType()->isSized() &&
6284 "GEP source element type must be sized");
6285
6286 SmallVector<SCEVUse, 4> IndexExprs;
6287 for (Value *Index : GEP->indices())
6288 IndexExprs.push_back(getSCEV(Index));
6289 return getGEPExpr(GEP, IndexExprs);
6290}
6291
6292APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6293 const Instruction *CtxI) {
6295 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6296 return TrailingZeros >= BitWidth
6298 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6299 };
6300 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6301 // The result is GCD of all operands results.
6302 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6303 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6305 Res, getConstantMultiple(N->getOperand(I), CtxI));
6306 return Res;
6307 };
6308
6309 switch (S->getSCEVType()) {
6310 case scConstant:
6311 return cast<SCEVConstant>(S)->getAPInt();
6312 case scPtrToAddr:
6313 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6314 case scUDivExpr:
6315 case scVScale:
6316 return APInt(BitWidth, 1);
6317 case scTruncate: {
6318 // Only multiples that are a power of 2 will hold after truncation.
6319 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6320 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6321 return GetShiftedByZeros(TZ);
6322 }
6323 case scZeroExtend: {
6324 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6325 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6326 }
6327 case scSignExtend: {
6328 // Only multiples that are a power of 2 will hold after sext.
6329 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6330 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6331 return GetShiftedByZeros(TZ);
6332 }
6333 case scMulExpr: {
6334 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6335 if (M->hasNoUnsignedWrap()) {
6336 // The result is the product of all operand results.
6337 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6338 for (const SCEV *Operand : M->operands().drop_front())
6339 Res = Res * getConstantMultiple(Operand, CtxI);
6340 return Res;
6341 }
6342
6343 // If there are no wrap guarentees, find the trailing zeros, which is the
6344 // sum of trailing zeros for all its operands.
6345 uint32_t TZ = 0;
6346 for (const SCEV *Operand : M->operands())
6347 TZ += getMinTrailingZeros(Operand, CtxI);
6348 return GetShiftedByZeros(TZ);
6349 }
6350 case scAddExpr:
6351 case scAddRecExpr: {
6352 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6353 if (N->hasNoUnsignedWrap())
6354 return GetGCDMultiple(N);
6355 // Find the trailing bits, which is the minimum of its operands.
6356 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6357 for (const SCEV *Operand : N->operands().drop_front())
6358 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6359 return GetShiftedByZeros(TZ);
6360 }
6361 case scUMaxExpr:
6362 case scSMaxExpr:
6363 case scUMinExpr:
6364 case scSMinExpr:
6366 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6367 case scUnknown: {
6368 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6369 // the point their underlying IR instruction has been defined. If CtxI was
6370 // not provided, use:
6371 // * the first instruction in the entry block if it is an argument
6372 // * the instruction itself otherwise.
6373 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6374 if (!CtxI) {
6375 if (isa<Argument>(U->getValue()))
6376 CtxI = &*F.getEntryBlock().begin();
6377 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6378 CtxI = I;
6379 }
6380 unsigned Known =
6381 computeKnownBits(U->getValue(),
6382 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6383 .allowEphemerals(true))
6384 .countMinTrailingZeros();
6385 return GetShiftedByZeros(Known);
6386 }
6387 case scCouldNotCompute:
6388 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6389 }
6390 llvm_unreachable("Unknown SCEV kind!");
6391}
6392
6394 const Instruction *CtxI) {
6395 // Skip looking up and updating the cache if there is a context instruction,
6396 // as the result will only be valid in the specified context.
6397 if (CtxI)
6398 return getConstantMultipleImpl(S, CtxI);
6399
6400 auto I = ConstantMultipleCache.find(S);
6401 if (I != ConstantMultipleCache.end())
6402 return I->second;
6403
6404 APInt Result = getConstantMultipleImpl(S, CtxI);
6405 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6406 assert(InsertPair.second && "Should insert a new key");
6407 return InsertPair.first->second;
6408}
6409
6411 APInt Multiple = getConstantMultiple(S);
6412 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6413}
6414
6416 const Instruction *CtxI) {
6417 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6418 (unsigned)getTypeSizeInBits(S->getType()));
6419}
6420
6421/// Helper method to assign a range to V from metadata present in the IR.
6422static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6424 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6425 return getConstantRangeFromMetadata(*MD);
6426 if (const auto *CB = dyn_cast<CallBase>(V))
6427 if (std::optional<ConstantRange> Range = CB->getRange())
6428 return Range;
6429 }
6430 if (auto *A = dyn_cast<Argument>(V))
6431 if (std::optional<ConstantRange> Range = A->getRange())
6432 return Range;
6433
6434 return std::nullopt;
6435}
6436
6438 SCEV::NoWrapFlags Flags) {
6439 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6440 AddRec->setNoWrapFlags(Flags);
6441 UnsignedRanges.erase(AddRec);
6442 SignedRanges.erase(AddRec);
6443 ConstantMultipleCache.erase(AddRec);
6444 }
6445}
6446
6447ConstantRange ScalarEvolution::
6448getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6449 const DataLayout &DL = getDataLayout();
6450
6451 unsigned BitWidth = getTypeSizeInBits(U->getType());
6452 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6453
6454 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6455 // use information about the trip count to improve our available range. Note
6456 // that the trip count independent cases are already handled by known bits.
6457 // WARNING: The definition of recurrence used here is subtly different than
6458 // the one used by AddRec (and thus most of this file). Step is allowed to
6459 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6460 // and other addrecs in the same loop (for non-affine addrecs). The code
6461 // below intentionally handles the case where step is not loop invariant.
6462 auto *P = dyn_cast<PHINode>(U->getValue());
6463 if (!P)
6464 return FullSet;
6465
6466 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6467 // even the values that are not available in these blocks may come from them,
6468 // and this leads to false-positive recurrence test.
6469 for (auto *Pred : predecessors(P->getParent()))
6470 if (!DT.isReachableFromEntry(Pred))
6471 return FullSet;
6472
6473 BinaryOperator *BO;
6474 Value *Start, *Step;
6475 if (!matchSimpleRecurrence(P, BO, Start, Step))
6476 return FullSet;
6477
6478 // If we found a recurrence in reachable code, we must be in a loop. Note
6479 // that BO might be in some subloop of L, and that's completely okay.
6480 auto *L = LI.getLoopFor(P->getParent());
6481 assert(L && L->getHeader() == P->getParent());
6482 if (!L->contains(BO->getParent()))
6483 // NOTE: This bailout should be an assert instead. However, asserting
6484 // the condition here exposes a case where LoopFusion is querying SCEV
6485 // with malformed loop information during the midst of the transform.
6486 // There doesn't appear to be an obvious fix, so for the moment bailout
6487 // until the caller issue can be fixed. PR49566 tracks the bug.
6488 return FullSet;
6489
6490 // TODO: Extend to other opcodes such as mul, and div
6491 switch (BO->getOpcode()) {
6492 default:
6493 return FullSet;
6494 case Instruction::AShr:
6495 case Instruction::LShr:
6496 case Instruction::Shl:
6497 break;
6498 };
6499
6500 if (BO->getOperand(0) != P)
6501 // TODO: Handle the power function forms some day.
6502 return FullSet;
6503
6504 unsigned TC = getSmallConstantMaxTripCount(L);
6505 if (!TC || TC >= BitWidth)
6506 return FullSet;
6507
6508 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6509 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6510 assert(KnownStart.getBitWidth() == BitWidth &&
6511 KnownStep.getBitWidth() == BitWidth);
6512
6513 // Compute total shift amount, being careful of overflow and bitwidths.
6514 auto MaxShiftAmt = KnownStep.getMaxValue();
6515 APInt TCAP(BitWidth, TC-1);
6516 bool Overflow = false;
6517 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6518 if (Overflow)
6519 return FullSet;
6520
6521 switch (BO->getOpcode()) {
6522 default:
6523 llvm_unreachable("filtered out above");
6524 case Instruction::AShr: {
6525 // For each ashr, three cases:
6526 // shift = 0 => unchanged value
6527 // saturation => 0 or -1
6528 // other => a value closer to zero (of the same sign)
6529 // Thus, the end value is closer to zero than the start.
6530 auto KnownEnd = KnownBits::ashr(KnownStart,
6531 KnownBits::makeConstant(TotalShift));
6532 if (KnownStart.isNonNegative())
6533 // Analogous to lshr (simply not yet canonicalized)
6534 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6535 KnownStart.getMaxValue() + 1);
6536 if (KnownStart.isNegative())
6537 // End >=u Start && End <=s Start
6538 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6539 KnownEnd.getMaxValue() + 1);
6540 break;
6541 }
6542 case Instruction::LShr: {
6543 // For each lshr, three cases:
6544 // shift = 0 => unchanged value
6545 // saturation => 0
6546 // other => a smaller positive number
6547 // Thus, the low end of the unsigned range is the last value produced.
6548 auto KnownEnd = KnownBits::lshr(KnownStart,
6549 KnownBits::makeConstant(TotalShift));
6550 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6551 KnownStart.getMaxValue() + 1);
6552 }
6553 case Instruction::Shl: {
6554 // Iff no bits are shifted out, value increases on every shift.
6555 auto KnownEnd = KnownBits::shl(KnownStart,
6556 KnownBits::makeConstant(TotalShift));
6557 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6558 return ConstantRange(KnownStart.getMinValue(),
6559 KnownEnd.getMaxValue() + 1);
6560 break;
6561 }
6562 };
6563 return FullSet;
6564}
6565
6566// The goal of this function is to check if recursively visiting the operands
6567// of this PHI might lead to an infinite loop. If we do see such a loop,
6568// there's no good way to break it, so we avoid analyzing such cases.
6569//
6570// getRangeRef previously used a visited set to avoid infinite loops, but this
6571// caused other issues: the result was dependent on the order of getRangeRef
6572// calls, and the interaction with createSCEVIter could cause a stack overflow
6573// in some cases (see issue #148253).
6574//
6575// FIXME: The way this is implemented is overly conservative; this checks
6576// for a few obviously safe patterns, but anything that doesn't lead to
6577// recursion is fine.
6579 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6581 return true;
6582
6583 if (all_of(PHI->operands(),
6584 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6585 return true;
6586
6587 return false;
6588}
6589
6590const ConstantRange &
6591ScalarEvolution::getRangeRefIter(const SCEV *S,
6592 ScalarEvolution::RangeSignHint SignHint) {
6593 DenseMap<const SCEV *, ConstantRange> &Cache =
6594 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6595 : SignedRanges;
6596 SmallVector<SCEVUse> WorkList;
6597 SmallPtrSet<const SCEV *, 8> Seen;
6598
6599 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6600 // SCEVUnknown PHI node.
6601 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6602 if (!Seen.insert(Expr).second)
6603 return;
6604 if (Cache.contains(Expr))
6605 return;
6606 switch (Expr->getSCEVType()) {
6607 case scUnknown:
6609 break;
6610 [[fallthrough]];
6611 case scConstant:
6612 case scVScale:
6613 case scTruncate:
6614 case scZeroExtend:
6615 case scSignExtend:
6616 case scPtrToAddr:
6617 case scAddExpr:
6618 case scMulExpr:
6619 case scUDivExpr:
6620 case scAddRecExpr:
6621 case scUMaxExpr:
6622 case scSMaxExpr:
6623 case scUMinExpr:
6624 case scSMinExpr:
6626 WorkList.push_back(Expr);
6627 break;
6628 case scCouldNotCompute:
6629 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6630 }
6631 };
6632 AddToWorklist(S);
6633
6634 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6635 for (unsigned I = 0; I != WorkList.size(); ++I) {
6636 const SCEV *P = WorkList[I];
6637 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6638 // If it is not a `SCEVUnknown`, just recurse into operands.
6639 if (!UnknownS) {
6640 for (const SCEV *Op : P->operands())
6641 AddToWorklist(Op);
6642 continue;
6643 }
6644 // `SCEVUnknown`'s require special treatment.
6645 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6646 if (!RangeRefPHIAllowedOperands(DT, P))
6647 continue;
6648 for (auto &Op : reverse(P->operands()))
6649 AddToWorklist(getSCEV(Op));
6650 }
6651 }
6652
6653 if (!WorkList.empty()) {
6654 // Use getRangeRef to compute ranges for items in the worklist in reverse
6655 // order. This will force ranges for earlier operands to be computed before
6656 // their users in most cases.
6657 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6658 getRangeRef(P, SignHint);
6659 }
6660 }
6661
6662 return getRangeRef(S, SignHint, 0);
6663}
6664
6665const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6666 if (const auto *C = dyn_cast<SCEVConstant>(S))
6667 return &C->getAPInt();
6668 return nullptr;
6669}
6670
6671/// Determine the range for a particular SCEV. If SignHint is
6672/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6673/// with a "cleaner" unsigned (resp. signed) representation.
6674const ConstantRange &ScalarEvolution::getRangeRef(
6675 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6676 DenseMap<const SCEV *, ConstantRange> &Cache =
6677 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6678 : SignedRanges;
6680 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6682
6683 // See if we've computed this range already.
6684 auto I = Cache.find(S);
6685 if (I != Cache.end())
6686 return I->second;
6687
6688 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6689 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6690
6691 // Switch to iteratively computing the range for S, if it is part of a deeply
6692 // nested expression.
6694 return getRangeRefIter(S, SignHint);
6695
6696 unsigned BitWidth = getTypeSizeInBits(S->getType());
6697 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6698 using OBO = OverflowingBinaryOperator;
6699
6700 // If the value has known zeros, the maximum value will have those known zeros
6701 // as well.
6702 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6703 APInt Multiple = getNonZeroConstantMultiple(S);
6704 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6705 if (!Remainder.isZero())
6706 ConservativeResult =
6707 ConstantRange(APInt::getMinValue(BitWidth),
6708 APInt::getMaxValue(BitWidth) - Remainder + 1);
6709 }
6710 else {
6711 uint32_t TZ = getMinTrailingZeros(S);
6712 if (TZ != 0) {
6713 ConservativeResult = ConstantRange(
6715 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6716 }
6717 }
6718
6719 switch (S->getSCEVType()) {
6720 case scConstant:
6721 llvm_unreachable("Already handled above.");
6722 case scVScale:
6723 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6724 case scTruncate: {
6725 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6726 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6727 return setRange(
6728 Trunc, SignHint,
6729 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6730 }
6731 case scZeroExtend: {
6732 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6733 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6734 return setRange(
6735 ZExt, SignHint,
6736 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6737 }
6738 case scSignExtend: {
6739 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6740 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6741 return setRange(
6742 SExt, SignHint,
6743 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6744 }
6745 case scPtrToAddr: {
6746 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6747 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6748 return setRange(Cast, SignHint, X);
6749 }
6750 case scAddExpr: {
6751 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6752 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6753 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6754 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6755 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6756 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6757 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6758 ConservativeResult =
6759 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6760 }
6761 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6762 unsigned WrapType = OBO::AnyWrap;
6763 if (Add->hasNoSignedWrap())
6764 WrapType |= OBO::NoSignedWrap;
6765 if (Add->hasNoUnsignedWrap())
6766 WrapType |= OBO::NoUnsignedWrap;
6767 for (const SCEV *Op : drop_begin(Add->operands()))
6768 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6769 RangeType);
6770 return setRange(Add, SignHint,
6771 ConservativeResult.intersectWith(X, RangeType));
6772 }
6773 case scMulExpr: {
6774 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6775 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6776 for (const SCEV *Op : drop_begin(Mul->operands()))
6777 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6778 return setRange(Mul, SignHint,
6779 ConservativeResult.intersectWith(X, RangeType));
6780 }
6781 case scUDivExpr: {
6782 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6783 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6784 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6785 return setRange(UDiv, SignHint,
6786 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6787 }
6788 case scAddRecExpr: {
6789 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6790 // If there's no unsigned wrap, the value will never be less than its
6791 // initial value.
6792 if (AddRec->hasNoUnsignedWrap()) {
6793 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6794 if (!UnsignedMinValue.isZero())
6795 ConservativeResult = ConservativeResult.intersectWith(
6796 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6797 }
6798
6799 // If there's no signed wrap, and all the operands except initial value have
6800 // the same sign or zero, the value won't ever be:
6801 // 1: smaller than initial value if operands are non negative,
6802 // 2: bigger than initial value if operands are non positive.
6803 // For both cases, value can not cross signed min/max boundary.
6804 if (AddRec->hasNoSignedWrap()) {
6805 bool AllNonNeg = true;
6806 bool AllNonPos = true;
6807 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6808 if (!isKnownNonNegative(AddRec->getOperand(i)))
6809 AllNonNeg = false;
6810 if (!isKnownNonPositive(AddRec->getOperand(i)))
6811 AllNonPos = false;
6812 }
6813 if (AllNonNeg)
6814 ConservativeResult = ConservativeResult.intersectWith(
6817 RangeType);
6818 else if (AllNonPos)
6819 ConservativeResult = ConservativeResult.intersectWith(
6821 getSignedRangeMax(AddRec->getStart()) +
6822 1),
6823 RangeType);
6824 }
6825
6826 // TODO: non-affine addrec
6827 if (AddRec->isAffine()) {
6828 const SCEV *MaxBEScev =
6830 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6831 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6832
6833 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6834 // MaxBECount's active bits are all <= AddRec's bit width.
6835 if (MaxBECount.getBitWidth() > BitWidth &&
6836 MaxBECount.getActiveBits() <= BitWidth)
6837 MaxBECount = MaxBECount.trunc(BitWidth);
6838 else if (MaxBECount.getBitWidth() < BitWidth)
6839 MaxBECount = MaxBECount.zext(BitWidth);
6840
6841 if (MaxBECount.getBitWidth() == BitWidth) {
6842 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6843 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6844 ConservativeResult =
6845 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6846 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6847
6848 auto RangeFromFactoring = getRangeViaFactoring(
6849 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6850 ConservativeResult =
6851 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6852 }
6853 }
6854
6855 // Now try symbolic BE count and more powerful methods.
6857 const SCEV *SymbolicMaxBECount =
6859 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6860 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6861 AddRec->hasNoSelfWrap()) {
6862 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6863 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6864 ConservativeResult =
6865 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6866 }
6867 }
6868 }
6869
6870 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6871 }
6872 case scUMaxExpr:
6873 case scSMaxExpr:
6874 case scUMinExpr:
6875 case scSMinExpr:
6876 case scSequentialUMinExpr: {
6878 switch (S->getSCEVType()) {
6879 case scUMaxExpr:
6880 ID = Intrinsic::umax;
6881 break;
6882 case scSMaxExpr:
6883 ID = Intrinsic::smax;
6884 break;
6885 case scUMinExpr:
6887 ID = Intrinsic::umin;
6888 break;
6889 case scSMinExpr:
6890 ID = Intrinsic::smin;
6891 break;
6892 default:
6893 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6894 }
6895
6896 const auto *NAry = cast<SCEVNAryExpr>(S);
6897 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6898 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6899 X = X.intrinsic(
6900 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6901 return setRange(S, SignHint,
6902 ConservativeResult.intersectWith(X, RangeType));
6903 }
6904 case scUnknown: {
6905 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6906 Value *V = U->getValue();
6907
6908 // Check if the IR explicitly contains !range metadata.
6909 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6910 if (MDRange)
6911 ConservativeResult =
6912 ConservativeResult.intersectWith(*MDRange, RangeType);
6913
6914 // Use facts about recurrences in the underlying IR. Note that add
6915 // recurrences are AddRecExprs and thus don't hit this path. This
6916 // primarily handles shift recurrences.
6917 auto CR = getRangeForUnknownRecurrence(U);
6918 ConservativeResult = ConservativeResult.intersectWith(CR);
6919
6920 // See if ValueTracking can give us a useful range.
6921 const DataLayout &DL = getDataLayout();
6922 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6923 if (Known.getBitWidth() != BitWidth)
6924 Known = Known.zextOrTrunc(BitWidth);
6925
6926 // ValueTracking may be able to compute a tighter result for the number of
6927 // sign bits than for the value of those sign bits.
6928 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6929 if (U->getType()->isPointerTy()) {
6930 // If the pointer size is larger than the index size type, this can cause
6931 // NS to be larger than BitWidth. So compensate for this.
6932 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6933 int ptrIdxDiff = ptrSize - BitWidth;
6934 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6935 NS -= ptrIdxDiff;
6936 }
6937
6938 if (NS > 1) {
6939 // If we know any of the sign bits, we know all of the sign bits.
6940 if (!Known.Zero.getHiBits(NS).isZero())
6941 Known.Zero.setHighBits(NS);
6942 if (!Known.One.getHiBits(NS).isZero())
6943 Known.One.setHighBits(NS);
6944 }
6945
6946 if (Known.getMinValue() != Known.getMaxValue() + 1)
6947 ConservativeResult = ConservativeResult.intersectWith(
6948 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6949 RangeType);
6950 if (NS > 1)
6951 ConservativeResult = ConservativeResult.intersectWith(
6952 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6953 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6954 RangeType);
6955
6956 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6957 // Strengthen the range if the underlying IR value is a
6958 // global/alloca/heap allocation using the size of the object.
6959 bool CanBeNull;
6960 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6961 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6962 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6963 // The highest address the object can start is DerefBytes bytes before
6964 // the end (unsigned max value). If this value is not a multiple of the
6965 // alignment, the last possible start value is the next lowest multiple
6966 // of the alignment. Note: The computations below cannot overflow,
6967 // because if they would there's no possible start address for the
6968 // object.
6969 APInt MaxVal =
6970 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6971 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6972 uint64_t Rem = MaxVal.urem(Align);
6973 MaxVal -= APInt(BitWidth, Rem);
6974 APInt MinVal = APInt::getZero(BitWidth);
6975 if (llvm::isKnownNonZero(V, DL))
6976 MinVal = Align;
6977 ConservativeResult = ConservativeResult.intersectWith(
6978 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6979 }
6980 }
6981
6982 // A range of Phi is a subset of union of all ranges of its input.
6983 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6984 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6985 // AddRecs; return the range for the corresponding AddRec.
6986 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
6987 return getRangeRef(AR, SignHint, Depth + 1);
6988
6989 // Make sure that we do not run over cycled Phis.
6990 if (RangeRefPHIAllowedOperands(DT, Phi)) {
6991 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6992
6993 for (const auto &Op : Phi->operands()) {
6994 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6995 RangeFromOps = RangeFromOps.unionWith(OpRange);
6996 // No point to continue if we already have a full set.
6997 if (RangeFromOps.isFullSet())
6998 break;
6999 }
7000 ConservativeResult =
7001 ConservativeResult.intersectWith(RangeFromOps, RangeType);
7002 }
7003 }
7004
7005 // vscale can't be equal to zero
7006 if (const auto *II = dyn_cast<IntrinsicInst>(V))
7007 if (II->getIntrinsicID() == Intrinsic::vscale) {
7008 ConstantRange Disallowed = APInt::getZero(BitWidth);
7009 ConservativeResult = ConservativeResult.difference(Disallowed);
7010 }
7011
7012 return setRange(U, SignHint, std::move(ConservativeResult));
7013 }
7014 case scCouldNotCompute:
7015 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7016 }
7017
7018 return setRange(S, SignHint, std::move(ConservativeResult));
7019}
7020
7021// Given a StartRange, Step and MaxBECount for an expression compute a range of
7022// values that the expression can take. Initially, the expression has a value
7023// from StartRange and then is changed by Step up to MaxBECount times. Signed
7024// argument defines if we treat Step as signed or unsigned. The second return
7025// value indicates that no wrapping occurred.
7026static std::pair<ConstantRange, bool>
7028 const APInt &MaxBECount, bool Signed) {
7029 unsigned BitWidth = Step.getBitWidth();
7030 assert(BitWidth == StartRange.getBitWidth() &&
7031 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7032 // If either Step or MaxBECount is 0, then the expression won't change, and we
7033 // just need to return the initial range.
7034 if (Step == 0 || MaxBECount == 0)
7035 return {StartRange, true};
7036
7037 // If we don't know anything about the initial value (i.e. StartRange is
7038 // FullRange), then we don't know anything about the final range either.
7039 // Return FullRange.
7040 if (StartRange.isFullSet())
7041 return {ConstantRange::getFull(BitWidth), false};
7042
7043 // If Step is signed and negative, then we use its absolute value, but we also
7044 // note that we're moving in the opposite direction.
7045 bool Descending = Signed && Step.isNegative();
7046
7047 if (Signed)
7048 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7049 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7050 // This equations hold true due to the well-defined wrap-around behavior of
7051 // APInt.
7052 Step = Step.abs();
7053
7054 // Check if Offset is more than full span of BitWidth. If it is, the
7055 // expression is guaranteed to overflow.
7056 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7057 return {ConstantRange::getFull(BitWidth), false};
7058
7059 // Offset is by how much the expression can change. Checks above guarantee no
7060 // overflow here.
7061 APInt Offset = Step * MaxBECount;
7062
7063 // Minimum value of the final range will match the minimal value of StartRange
7064 // if the expression is increasing and will be decreased by Offset otherwise.
7065 // Maximum value of the final range will match the maximal value of StartRange
7066 // if the expression is decreasing and will be increased by Offset otherwise.
7067 APInt StartLower = StartRange.getLower();
7068 APInt StartUpper = StartRange.getUpper() - 1;
7069 bool Overflow;
7070 APInt MovedBoundary;
7071 if (Signed) {
7072 // This does not use sadd_ov, as we want to check overflow for a signed
7073 // start with an unsigned offset.
7074 if (Descending) {
7075 MovedBoundary = StartLower - std::move(Offset);
7076 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7077 } else {
7078 MovedBoundary = StartUpper + std::move(Offset);
7079 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7080 }
7081 } else {
7082 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7083 Overflow |= StartRange.isWrappedSet();
7084 }
7085
7086 // It's possible that the new minimum/maximum value will fall into the initial
7087 // range (due to wrap around). This means that the expression can take any
7088 // value in this bitwidth, and we have to return full range.
7089 if (StartRange.contains(MovedBoundary))
7090 return {ConstantRange::getFull(BitWidth), false};
7091
7092 APInt NewLower =
7093 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7094 APInt NewUpper =
7095 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7096 NewUpper += 1;
7097
7098 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7099 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7100 !Overflow};
7101}
7102
7103std::pair<ConstantRange, SCEV::NoWrapFlags>
7104ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7105 const APInt &MaxBECount) {
7106 assert(getTypeSizeInBits(Start->getType()) ==
7107 getTypeSizeInBits(Step->getType()) &&
7108 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7109 "mismatched bit widths");
7110
7111 // First, consider step signed.
7112 ConstantRange StartSRange = getSignedRange(Start);
7113 ConstantRange StepSRange = getSignedRange(Step);
7114
7115 // If Step can be both positive and negative, we need to find ranges for the
7116 // maximum absolute step values in both directions and union them.
7117 auto [SR1, NSW1] = getRangeForAffineARHelper(
7118 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7119 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7120 StartSRange, MaxBECount,
7121 /*Signed=*/true);
7122 ConstantRange SR = SR1.unionWith(SR2);
7123
7124 // Next, consider step unsigned.
7125 auto [UR, NUW] = getRangeForAffineARHelper(
7126 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7127 /*Signed=*/false);
7128
7130 if (NUW)
7132 if (NSW1 && NSW2)
7134
7135 // Finally, intersect signed and unsigned ranges.
7137}
7138
7139ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7140 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7141 ScalarEvolution::RangeSignHint SignHint) {
7142 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7143 assert(AddRec->hasNoSelfWrap() &&
7144 "This only works for non-self-wrapping AddRecs!");
7145 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7146 const SCEV *Step = AddRec->getStepRecurrence(*this);
7147 // Only deal with constant step to save compile time.
7148 if (!isa<SCEVConstant>(Step))
7149 return ConstantRange::getFull(BitWidth);
7150 // Let's make sure that we can prove that we do not self-wrap during
7151 // MaxBECount iterations. We need this because MaxBECount is a maximum
7152 // iteration count estimate, and we might infer nw from some exit for which we
7153 // do not know max exit count (or any other side reasoning).
7154 // TODO: Turn into assert at some point.
7155 if (getTypeSizeInBits(MaxBECount->getType()) >
7156 getTypeSizeInBits(AddRec->getType()))
7157 return ConstantRange::getFull(BitWidth);
7158 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7159 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7160 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7161 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7162 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7163 MaxItersWithoutWrap))
7164 return ConstantRange::getFull(BitWidth);
7165
7166 ICmpInst::Predicate LEPred =
7168 ICmpInst::Predicate GEPred =
7170 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7171
7172 // We know that there is no self-wrap. Let's take Start and End values and
7173 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7174 // the iteration. They either lie inside the range [Min(Start, End),
7175 // Max(Start, End)] or outside it:
7176 //
7177 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7178 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7179 //
7180 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7181 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7182 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7183 // Start <= End and step is positive, or Start >= End and step is negative.
7184 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7185 ConstantRange StartRange = getRangeRef(Start, SignHint);
7186 ConstantRange EndRange = getRangeRef(End, SignHint);
7187 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7188 // If they already cover full iteration space, we will know nothing useful
7189 // even if we prove what we want to prove.
7190 if (RangeBetween.isFullSet())
7191 return RangeBetween;
7192 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7193 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7194 : RangeBetween.isWrappedSet();
7195 if (IsWrappedSet)
7196 return ConstantRange::getFull(BitWidth);
7197
7198 if (isKnownPositive(Step) &&
7199 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7200 return RangeBetween;
7201 if (isKnownNegative(Step) &&
7202 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7203 return RangeBetween;
7204 return ConstantRange::getFull(BitWidth);
7205}
7206
7207ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7208 const SCEV *Step,
7209 const APInt &MaxBECount) {
7210 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7211 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7212
7213 unsigned BitWidth = MaxBECount.getBitWidth();
7214 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7215 getTypeSizeInBits(Step->getType()) == BitWidth &&
7216 "mismatched bit widths");
7217
7218 struct SelectPattern {
7219 Value *Condition = nullptr;
7220 APInt TrueValue;
7221 APInt FalseValue;
7222
7223 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7224 const SCEV *S) {
7225 std::optional<unsigned> CastOp;
7226 APInt Offset(BitWidth, 0);
7227
7229 "Should be!");
7230
7231 // Peel off a constant offset. In the future we could consider being
7232 // smarter here and handle {Start+Step,+,Step} too.
7233 const APInt *Off;
7234 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7235 Offset = *Off;
7236
7237 // Peel off a cast operation
7238 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7239 CastOp = SCast->getSCEVType();
7240 S = SCast->getOperand();
7241 }
7242
7243 using namespace llvm::PatternMatch;
7244
7245 auto *SU = dyn_cast<SCEVUnknown>(S);
7246 const APInt *TrueVal, *FalseVal;
7247 if (!SU ||
7248 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7249 m_APInt(FalseVal)))) {
7250 Condition = nullptr;
7251 return;
7252 }
7253
7254 TrueValue = *TrueVal;
7255 FalseValue = *FalseVal;
7256
7257 // Re-apply the cast we peeled off earlier
7258 if (CastOp)
7259 switch (*CastOp) {
7260 default:
7261 llvm_unreachable("Unknown SCEV cast type!");
7262
7263 case scTruncate:
7264 TrueValue = TrueValue.trunc(BitWidth);
7265 FalseValue = FalseValue.trunc(BitWidth);
7266 break;
7267 case scZeroExtend:
7268 TrueValue = TrueValue.zext(BitWidth);
7269 FalseValue = FalseValue.zext(BitWidth);
7270 break;
7271 case scSignExtend:
7272 TrueValue = TrueValue.sext(BitWidth);
7273 FalseValue = FalseValue.sext(BitWidth);
7274 break;
7275 }
7276
7277 // Re-apply the constant offset we peeled off earlier
7278 TrueValue += Offset;
7279 FalseValue += Offset;
7280 }
7281
7282 bool isRecognized() { return Condition != nullptr; }
7283 };
7284
7285 SelectPattern StartPattern(*this, BitWidth, Start);
7286 if (!StartPattern.isRecognized())
7287 return ConstantRange::getFull(BitWidth);
7288
7289 SelectPattern StepPattern(*this, BitWidth, Step);
7290 if (!StepPattern.isRecognized())
7291 return ConstantRange::getFull(BitWidth);
7292
7293 if (StartPattern.Condition != StepPattern.Condition) {
7294 // We don't handle this case today; but we could, by considering four
7295 // possibilities below instead of two. I'm not sure if there are cases where
7296 // that will help over what getRange already does, though.
7297 return ConstantRange::getFull(BitWidth);
7298 }
7299
7300 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7301 // construct arbitrary general SCEV expressions here. This function is called
7302 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7303 // say) can end up caching a suboptimal value.
7304
7305 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7306 // C2352 and C2512 (otherwise it isn't needed).
7307
7308 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7309 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7310 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7311 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7312
7313 ConstantRange TrueRange =
7314 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7315 ConstantRange FalseRange =
7316 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7317
7318 return TrueRange.unionWith(FalseRange);
7319}
7320
7321SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7322 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7323 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7324
7325 // Return early if there are no flags to propagate to the SCEV.
7327 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7328 PDI && PDI->isDisjoint()) {
7330 } else {
7331 if (BinOp->hasNoUnsignedWrap())
7333 if (BinOp->hasNoSignedWrap())
7335 }
7336 if (Flags == SCEV::FlagAnyWrap)
7337 return SCEV::FlagAnyWrap;
7338
7339 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7340}
7341
7342const Instruction *
7343ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7344 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7345 return &*AddRec->getLoop()->getHeader()->begin();
7346 if (auto *U = dyn_cast<SCEVUnknown>(S))
7347 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7348 return I;
7349 return nullptr;
7350}
7351
7352const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7353 bool &Precise) {
7354 Precise = true;
7355 // Do a bounded search of the def relation of the requested SCEVs.
7356 SmallPtrSet<const SCEV *, 16> Visited;
7357 SmallVector<SCEVUse> Worklist;
7358 auto pushOp = [&](const SCEV *S) {
7359 if (!Visited.insert(S).second)
7360 return;
7361 // Threshold of 30 here is arbitrary.
7362 if (Visited.size() > 30) {
7363 Precise = false;
7364 return;
7365 }
7366 Worklist.push_back(S);
7367 };
7368
7369 for (SCEVUse S : Ops)
7370 pushOp(S);
7371
7372 const Instruction *Bound = nullptr;
7373 while (!Worklist.empty()) {
7374 SCEVUse S = Worklist.pop_back_val();
7375 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7376 if (!Bound || DT.dominates(Bound, DefI))
7377 Bound = DefI;
7378 } else {
7379 for (SCEVUse Op : S->operands())
7380 pushOp(Op);
7381 }
7382 }
7383 return Bound ? Bound : &*F.getEntryBlock().begin();
7384}
7385
7386const Instruction *
7387ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7388 bool Discard;
7389 return getDefiningScopeBound(Ops, Discard);
7390}
7391
7392bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7393 const Instruction *B) {
7394 if (A->getParent() == B->getParent() &&
7396 B->getIterator()))
7397 return true;
7398
7399 auto *BLoop = LI.getLoopFor(B->getParent());
7400 if (BLoop && BLoop->getHeader() == B->getParent() &&
7401 BLoop->getLoopPreheader() == A->getParent() &&
7403 A->getParent()->end()) &&
7404 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7405 B->getIterator()))
7406 return true;
7407 return false;
7408}
7409
7411 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7412 visitAll(Op, PC);
7413 return PC.MaybePoison.empty();
7414}
7415
7416bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7417 return !SCEVExprContains(Op, [this](const SCEV *S) {
7418 const SCEV *Op1;
7419 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7420 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7421 // is a non-zero constant, we have to assume the UDiv may be UB.
7422 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7423 });
7424}
7425
7426bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7427 // Only proceed if we can prove that I does not yield poison.
7429 return false;
7430
7431 // At this point we know that if I is executed, then it does not wrap
7432 // according to at least one of NSW or NUW. If I is not executed, then we do
7433 // not know if the calculation that I represents would wrap. Multiple
7434 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7435 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7436 // derived from other instructions that map to the same SCEV. We cannot make
7437 // that guarantee for cases where I is not executed. So we need to find a
7438 // upper bound on the defining scope for the SCEV, and prove that I is
7439 // executed every time we enter that scope. When the bounding scope is a
7440 // loop (the common case), this is equivalent to proving I executes on every
7441 // iteration of that loop.
7442 SmallVector<SCEVUse> SCEVOps;
7443 for (const Use &Op : I->operands()) {
7444 // I could be an extractvalue from a call to an overflow intrinsic.
7445 // TODO: We can do better here in some cases.
7446 if (isSCEVable(Op->getType()))
7447 SCEVOps.push_back(getSCEV(Op));
7448 }
7449 auto *DefI = getDefiningScopeBound(SCEVOps);
7450 return isGuaranteedToTransferExecutionTo(DefI, I);
7451}
7452
7453bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7454 // If we know that \c I can never be poison period, then that's enough.
7455 if (isSCEVExprNeverPoison(I))
7456 return true;
7457
7458 // If the loop only has one exit, then we know that, if the loop is entered,
7459 // any instruction dominating that exit will be executed. If any such
7460 // instruction would result in UB, the addrec cannot be poison.
7461 //
7462 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7463 // also handles uses outside the loop header (they just need to dominate the
7464 // single exit).
7465
7466 auto *ExitingBB = L->getExitingBlock();
7467 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7468 return false;
7469
7470 SmallPtrSet<const Value *, 16> KnownPoison;
7472
7473 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7474 // things that are known to be poison under that assumption go on the
7475 // Worklist.
7476 KnownPoison.insert(I);
7477 Worklist.push_back(I);
7478
7479 while (!Worklist.empty()) {
7480 const Instruction *Poison = Worklist.pop_back_val();
7481
7482 for (const Use &U : Poison->uses()) {
7483 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7484 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7485 DT.dominates(PoisonUser->getParent(), ExitingBB))
7486 return true;
7487
7488 if (propagatesPoison(U) && L->contains(PoisonUser))
7489 if (KnownPoison.insert(PoisonUser).second)
7490 Worklist.push_back(PoisonUser);
7491 }
7492 }
7493
7494 return false;
7495}
7496
7497ScalarEvolution::LoopProperties
7498ScalarEvolution::getLoopProperties(const Loop *L) {
7499 using LoopProperties = ScalarEvolution::LoopProperties;
7500
7501 auto Itr = LoopPropertiesCache.find(L);
7502 if (Itr == LoopPropertiesCache.end()) {
7503 auto HasSideEffects = [](Instruction *I) {
7504 if (auto *SI = dyn_cast<StoreInst>(I))
7505 return !SI->isSimple();
7506
7507 if (I->mayThrow())
7508 return true;
7509
7510 // Non-volatile memset / memcpy do not count as side-effect for forward
7511 // progress.
7512 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7513 return false;
7514
7515 return I->mayWriteToMemory();
7516 };
7517
7518 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7519 /*HasNoSideEffects*/ true};
7520
7521 for (auto *BB : L->getBlocks())
7522 for (auto &I : *BB) {
7524 LP.HasNoAbnormalExits = false;
7525 if (HasSideEffects(&I))
7526 LP.HasNoSideEffects = false;
7527 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7528 break; // We're already as pessimistic as we can get.
7529 }
7530
7531 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7532 assert(InsertPair.second && "We just checked!");
7533 Itr = InsertPair.first;
7534 }
7535
7536 return Itr->second;
7537}
7538
7540 // A mustprogress loop without side effects must be finite.
7541 // TODO: The check used here is very conservative. It's only *specific*
7542 // side effects which are well defined in infinite loops.
7543 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7544}
7545
7546const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7547 // Worklist item with a Value and a bool indicating whether all operands have
7548 // been visited already.
7551
7552 Stack.emplace_back(V, false);
7553 while (!Stack.empty()) {
7554 auto E = Stack.back();
7555 Value *CurV = E.getPointer();
7556
7557 if (getExistingSCEV(CurV)) {
7558 Stack.pop_back();
7559 continue;
7560 }
7561
7563 const SCEV *CreatedSCEV = nullptr;
7564 // If all operands have been visited already, create the SCEV.
7565 if (E.getInt()) {
7566 CreatedSCEV = createSCEV(CurV);
7567 } else {
7568 // Otherwise get the operands we need to create SCEV's for before creating
7569 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7570 // just use it.
7571 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7572 }
7573
7574 if (CreatedSCEV) {
7575 insertValueToMap(CurV, CreatedSCEV);
7576 Stack.pop_back();
7577 } else {
7578 Stack.back().setInt(true);
7579 // Queue its operands which need to be constructed.
7580 for (Value *Op : Ops)
7581 Stack.emplace_back(Op, false);
7582 }
7583 }
7584
7585 return getExistingSCEV(V);
7586}
7587
7588const SCEV *
7589ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7590 if (!isSCEVable(V->getType()))
7591 return getUnknown(V);
7592
7593 if (Instruction *I = dyn_cast<Instruction>(V)) {
7594 // Don't attempt to analyze instructions in blocks that aren't
7595 // reachable. Such instructions don't matter, and they aren't required
7596 // to obey basic rules for definitions dominating uses which this
7597 // analysis depends on.
7598 if (!DT.isReachableFromEntry(I->getParent()))
7599 return getUnknown(PoisonValue::get(V->getType()));
7600 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7601 return getConstant(CI);
7602 else if (isa<GlobalAlias>(V))
7603 return getUnknown(V);
7604 else if (!isa<ConstantExpr>(V))
7605 return getUnknown(V);
7606
7608 if (auto BO =
7610 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7611 switch (BO->Opcode) {
7612 case Instruction::Add:
7613 case Instruction::Mul: {
7614 // For additions and multiplications, traverse add/mul chains for which we
7615 // can potentially create a single SCEV, to reduce the number of
7616 // get{Add,Mul}Expr calls.
7617 do {
7618 if (BO->Op) {
7619 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7620 Ops.push_back(BO->Op);
7621 break;
7622 }
7623 }
7624 Ops.push_back(BO->RHS);
7625 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7627 if (!NewBO ||
7628 (BO->Opcode == Instruction::Add &&
7629 (NewBO->Opcode != Instruction::Add &&
7630 NewBO->Opcode != Instruction::Sub)) ||
7631 (BO->Opcode == Instruction::Mul &&
7632 NewBO->Opcode != Instruction::Mul)) {
7633 Ops.push_back(BO->LHS);
7634 break;
7635 }
7636 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7637 // requires a SCEV for the LHS.
7638 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7639 auto *I = dyn_cast<Instruction>(BO->Op);
7640 if (I && programUndefinedIfPoison(I)) {
7641 Ops.push_back(BO->LHS);
7642 break;
7643 }
7644 }
7645 BO = NewBO;
7646 } while (true);
7647 return nullptr;
7648 }
7649 case Instruction::Sub:
7650 case Instruction::UDiv:
7651 case Instruction::URem:
7652 break;
7653 case Instruction::AShr:
7654 case Instruction::Shl:
7655 case Instruction::Xor:
7656 if (!IsConstArg)
7657 return nullptr;
7658 break;
7659 case Instruction::And:
7660 case Instruction::Or:
7661 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7662 return nullptr;
7663 break;
7664 case Instruction::LShr:
7665 return getUnknown(V);
7666 default:
7667 llvm_unreachable("Unhandled binop");
7668 break;
7669 }
7670
7671 Ops.push_back(BO->LHS);
7672 Ops.push_back(BO->RHS);
7673 return nullptr;
7674 }
7675
7676 switch (U->getOpcode()) {
7677 case Instruction::Trunc:
7678 case Instruction::ZExt:
7679 case Instruction::SExt:
7680 case Instruction::PtrToAddr:
7681 case Instruction::PtrToInt:
7682 Ops.push_back(U->getOperand(0));
7683 return nullptr;
7684
7685 case Instruction::BitCast:
7686 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7687 Ops.push_back(U->getOperand(0));
7688 return nullptr;
7689 }
7690 return getUnknown(V);
7691
7692 case Instruction::SDiv:
7693 case Instruction::SRem:
7694 Ops.push_back(U->getOperand(0));
7695 Ops.push_back(U->getOperand(1));
7696 return nullptr;
7697
7698 case Instruction::GetElementPtr:
7699 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7700 "GEP source element type must be sized");
7701 llvm::append_range(Ops, U->operands());
7702 return nullptr;
7703
7704 case Instruction::IntToPtr:
7705 return getUnknown(V);
7706
7707 case Instruction::PHI:
7708 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7709 // relevant nodes for each of them.
7710 //
7711 // The first is just to call simplifyInstruction, and get something back
7712 // that isn't a PHI.
7713 if (Value *V = simplifyInstruction(
7714 cast<PHINode>(U),
7715 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7716 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7717 assert(V);
7718 Ops.push_back(V);
7719 return nullptr;
7720 }
7721 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7722 // operands which all perform the same operation, but haven't been
7723 // CSE'ed for whatever reason.
7724 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7725 assert(BO);
7726 Ops.push_back(BO);
7727 return nullptr;
7728 }
7729 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7730 // is equivalent to a select, and analyzes it like a select.
7731 {
7732 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7734 assert(Cond);
7735 assert(LHS);
7736 assert(RHS);
7737 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7738 Ops.push_back(CondICmp->getOperand(0));
7739 Ops.push_back(CondICmp->getOperand(1));
7740 }
7741 Ops.push_back(Cond);
7742 Ops.push_back(LHS);
7743 Ops.push_back(RHS);
7744 return nullptr;
7745 }
7746 }
7747 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7748 // so just construct it recursively.
7749 //
7750 // In addition to getNodeForPHI, also construct nodes which might be needed
7751 // by getRangeRef.
7753 for (Value *V : cast<PHINode>(U)->operands())
7754 Ops.push_back(V);
7755 return nullptr;
7756 }
7757 return nullptr;
7758
7759 case Instruction::Select: {
7760 // Check if U is a select that can be simplified to a SCEVUnknown.
7761 auto CanSimplifyToUnknown = [this, U]() {
7762 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7763 return false;
7764
7765 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7766 if (!ICI)
7767 return false;
7768 Value *LHS = ICI->getOperand(0);
7769 Value *RHS = ICI->getOperand(1);
7770 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7771 ICI->getPredicate() == CmpInst::ICMP_NE) {
7773 return true;
7774 } else if (getTypeSizeInBits(LHS->getType()) >
7775 getTypeSizeInBits(U->getType()))
7776 return true;
7777 return false;
7778 };
7779 if (CanSimplifyToUnknown())
7780 return getUnknown(U);
7781
7782 llvm::append_range(Ops, U->operands());
7783 return nullptr;
7784 break;
7785 }
7786 case Instruction::Call:
7787 case Instruction::Invoke:
7788 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7789 Ops.push_back(RV);
7790 return nullptr;
7791 }
7792
7793 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7794 switch (II->getIntrinsicID()) {
7795 case Intrinsic::abs:
7796 Ops.push_back(II->getArgOperand(0));
7797 return nullptr;
7798 case Intrinsic::umax:
7799 case Intrinsic::umin:
7800 case Intrinsic::smax:
7801 case Intrinsic::smin:
7802 case Intrinsic::usub_sat:
7803 case Intrinsic::uadd_sat:
7804 Ops.push_back(II->getArgOperand(0));
7805 Ops.push_back(II->getArgOperand(1));
7806 return nullptr;
7807 case Intrinsic::start_loop_iterations:
7808 case Intrinsic::annotation:
7809 case Intrinsic::ptr_annotation:
7810 Ops.push_back(II->getArgOperand(0));
7811 return nullptr;
7812 default:
7813 break;
7814 }
7815 }
7816 break;
7817 }
7818
7819 return nullptr;
7820}
7821
7822const SCEV *ScalarEvolution::createSCEV(Value *V) {
7823 if (!isSCEVable(V->getType()))
7824 return getUnknown(V);
7825
7826 if (Instruction *I = dyn_cast<Instruction>(V)) {
7827 // Don't attempt to analyze instructions in blocks that aren't
7828 // reachable. Such instructions don't matter, and they aren't required
7829 // to obey basic rules for definitions dominating uses which this
7830 // analysis depends on.
7831 if (!DT.isReachableFromEntry(I->getParent()))
7832 return getUnknown(PoisonValue::get(V->getType()));
7833 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7834 return getConstant(CI);
7835 else if (isa<GlobalAlias>(V))
7836 return getUnknown(V);
7837 else if (!isa<ConstantExpr>(V))
7838 return getUnknown(V);
7839
7840 const SCEV *LHS;
7841 const SCEV *RHS;
7842
7844 if (auto BO =
7846 switch (BO->Opcode) {
7847 case Instruction::Add: {
7848 // The simple thing to do would be to just call getSCEV on both operands
7849 // and call getAddExpr with the result. However if we're looking at a
7850 // bunch of things all added together, this can be quite inefficient,
7851 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7852 // Instead, gather up all the operands and make a single getAddExpr call.
7853 // LLVM IR canonical form means we need only traverse the left operands.
7855 do {
7856 if (BO->Op) {
7857 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7858 AddOps.push_back(OpSCEV);
7859 break;
7860 }
7861
7862 // If a NUW or NSW flag can be applied to the SCEV for this
7863 // addition, then compute the SCEV for this addition by itself
7864 // with a separate call to getAddExpr. We need to do that
7865 // instead of pushing the operands of the addition onto AddOps,
7866 // since the flags are only known to apply to this particular
7867 // addition - they may not apply to other additions that can be
7868 // formed with operands from AddOps.
7869 const SCEV *RHS = getSCEV(BO->RHS);
7870 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7871 if (Flags != SCEV::FlagAnyWrap) {
7872 const SCEV *LHS = getSCEV(BO->LHS);
7873 if (BO->Opcode == Instruction::Sub)
7874 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7875 else
7876 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7877 break;
7878 }
7879 }
7880
7881 if (BO->Opcode == Instruction::Sub)
7882 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7883 else
7884 AddOps.push_back(getSCEV(BO->RHS));
7885
7886 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7888 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7889 NewBO->Opcode != Instruction::Sub)) {
7890 AddOps.push_back(getSCEV(BO->LHS));
7891 break;
7892 }
7893 BO = NewBO;
7894 } while (true);
7895
7896 return getAddExpr(AddOps);
7897 }
7898
7899 case Instruction::Mul: {
7901 do {
7902 if (BO->Op) {
7903 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7904 MulOps.push_back(OpSCEV);
7905 break;
7906 }
7907
7908 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7909 if (Flags != SCEV::FlagAnyWrap) {
7910 LHS = getSCEV(BO->LHS);
7911 RHS = getSCEV(BO->RHS);
7912 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7913 break;
7914 }
7915 }
7916
7917 MulOps.push_back(getSCEV(BO->RHS));
7918 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7920 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7921 MulOps.push_back(getSCEV(BO->LHS));
7922 break;
7923 }
7924 BO = NewBO;
7925 } while (true);
7926
7927 return getMulExpr(MulOps);
7928 }
7929 case Instruction::UDiv:
7930 LHS = getSCEV(BO->LHS);
7931 RHS = getSCEV(BO->RHS);
7932 return getUDivExpr(LHS, RHS);
7933 case Instruction::URem:
7934 LHS = getSCEV(BO->LHS);
7935 RHS = getSCEV(BO->RHS);
7936 return getURemExpr(LHS, RHS);
7937 case Instruction::Sub: {
7939 if (BO->Op)
7940 Flags = getNoWrapFlagsFromUB(BO->Op);
7941
7942 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7943 // operand. While we don't model ptrtoint directly in SCEV, the
7944 // difference between two pointer addresses is well-defined.
7945 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7946 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7947 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7948 if (HasPtrLHS || HasPtrRHS) {
7949 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7950 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7951 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7952 // useful structure.
7953 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7954 bool BothPtr) -> const SCEV * {
7955 if (!HasPtr)
7956 return getSCEV(OrigOp);
7957 const SCEV *PtrSCEV = getSCEV(PtrOp);
7958 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
7959 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
7960 if (!isa<SCEVCouldNotCompute>(Addr) &&
7961 getTypeSizeInBits(OrigOp->getType()) <=
7962 getTypeSizeInBits(Addr->getType()))
7963 return getTruncateOrNoop(Addr, OrigOp->getType());
7964 }
7965 return getSCEV(OrigOp);
7966 };
7967 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7968 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7969 return getMinusSCEV(L, R, Flags);
7970 }
7971
7972 LHS = getSCEV(BO->LHS);
7973 RHS = getSCEV(BO->RHS);
7974 return getMinusSCEV(LHS, RHS, Flags);
7975 }
7976 case Instruction::And:
7977 // For an expression like x&255 that merely masks off the high bits,
7978 // use zext(trunc(x)) as the SCEV expression.
7979 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7980 if (CI->isZero())
7981 return getSCEV(BO->RHS);
7982 if (CI->isMinusOne())
7983 return getSCEV(BO->LHS);
7984 const APInt &A = CI->getValue();
7985
7986 // Instcombine's ShrinkDemandedConstant may strip bits out of
7987 // constants, obscuring what would otherwise be a low-bits mask.
7988 // Use computeKnownBits to compute what ShrinkDemandedConstant
7989 // knew about to reconstruct a low-bits mask value.
7990 unsigned LZ = A.countl_zero();
7991 unsigned TZ = A.countr_zero();
7992 unsigned BitWidth = A.getBitWidth();
7993 KnownBits Known(BitWidth);
7994 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
7995
7996 APInt EffectiveMask =
7997 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7998 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7999 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
8000 const SCEV *LHS = getSCEV(BO->LHS);
8001 const SCEV *ShiftedLHS = nullptr;
8002 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
8003 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
8004 // For an expression like (x * 8) & 8, simplify the multiply.
8005 unsigned MulZeros = OpC->getAPInt().countr_zero();
8006 unsigned GCD = std::min(MulZeros, TZ);
8007 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
8009 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
8010 append_range(MulOps, LHSMul->operands().drop_front());
8011 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
8012 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
8013 }
8014 }
8015 if (!ShiftedLHS)
8016 ShiftedLHS = getUDivExpr(LHS, MulCount);
8017 return getMulExpr(
8019 getTruncateExpr(ShiftedLHS,
8020 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
8021 BO->LHS->getType()),
8022 MulCount);
8023 }
8024 }
8025 // Binary `and` is a bit-wise `umin`.
8026 if (BO->LHS->getType()->isIntegerTy(1)) {
8027 LHS = getSCEV(BO->LHS);
8028 RHS = getSCEV(BO->RHS);
8029 return getUMinExpr(LHS, RHS);
8030 }
8031 break;
8032
8033 case Instruction::Or:
8034 // Binary `or` is a bit-wise `umax`.
8035 if (BO->LHS->getType()->isIntegerTy(1)) {
8036 LHS = getSCEV(BO->LHS);
8037 RHS = getSCEV(BO->RHS);
8038 return getUMaxExpr(LHS, RHS);
8039 }
8040 break;
8041
8042 case Instruction::Xor:
8043 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8044 // If the RHS of xor is -1, then this is a not operation.
8045 if (CI->isMinusOne())
8046 return getNotSCEV(getSCEV(BO->LHS));
8047
8048 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8049 // This is a variant of the check for xor with -1, and it handles
8050 // the case where instcombine has trimmed non-demanded bits out
8051 // of an xor with -1.
8052 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8053 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8054 if (LBO->getOpcode() == Instruction::And &&
8055 LCI->getValue() == CI->getValue())
8056 if (const SCEVZeroExtendExpr *Z =
8058 Type *UTy = BO->LHS->getType();
8059 const SCEV *Z0 = Z->getOperand();
8060 Type *Z0Ty = Z0->getType();
8061 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8062
8063 // If C is a low-bits mask, the zero extend is serving to
8064 // mask off the high bits. Complement the operand and
8065 // re-apply the zext.
8066 if (CI->getValue().isMask(Z0TySize))
8067 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8068
8069 // If C is a single bit, it may be in the sign-bit position
8070 // before the zero-extend. In this case, represent the xor
8071 // using an add, which is equivalent, and re-apply the zext.
8072 APInt Trunc = CI->getValue().trunc(Z0TySize);
8073 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8074 Trunc.isSignMask())
8075 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8076 UTy);
8077 }
8078 }
8079 break;
8080
8081 case Instruction::Shl:
8082 // Turn shift left of a constant amount into a multiply.
8083 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8084 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8085
8086 // If the shift count is not less than the bitwidth, the result of
8087 // the shift is undefined. Don't try to analyze it, because the
8088 // resolution chosen here may differ from the resolution chosen in
8089 // other parts of the compiler.
8090 if (SA->getValue().uge(BitWidth))
8091 break;
8092
8093 // We can safely preserve the nuw flag in all cases. It's also safe to
8094 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8095 // requires special handling. It can be preserved as long as we're not
8096 // left shifting by bitwidth - 1.
8097 auto Flags = SCEV::FlagAnyWrap;
8098 if (BO->Op) {
8099 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8100 if (any(MulFlags & SCEV::FlagNSW) &&
8101 (any(MulFlags & SCEV::FlagNUW) ||
8102 SA->getValue().ult(BitWidth - 1)))
8104 if (any(MulFlags & SCEV::FlagNUW))
8106 }
8107
8108 ConstantInt *X = ConstantInt::get(
8109 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8110 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8111 }
8112 break;
8113
8114 case Instruction::AShr:
8115 // AShr X, C, where C is a constant.
8116 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8117 if (!CI)
8118 break;
8119
8120 Type *OuterTy = BO->LHS->getType();
8122 // If the shift count is not less than the bitwidth, the result of
8123 // the shift is undefined. Don't try to analyze it, because the
8124 // resolution chosen here may differ from the resolution chosen in
8125 // other parts of the compiler.
8126 if (CI->getValue().uge(BitWidth))
8127 break;
8128
8129 if (CI->isZero())
8130 return getSCEV(BO->LHS); // shift by zero --> noop
8131
8132 uint64_t AShrAmt = CI->getZExtValue();
8133 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8134
8135 Operator *L = dyn_cast<Operator>(BO->LHS);
8136 const SCEV *AddTruncateExpr = nullptr;
8137 ConstantInt *ShlAmtCI = nullptr;
8138 const SCEV *AddConstant = nullptr;
8139
8140 if (L && L->getOpcode() == Instruction::Add) {
8141 // X = Shl A, n
8142 // Y = Add X, c
8143 // Z = AShr Y, m
8144 // n, c and m are constants.
8145
8146 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8147 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8148 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8149 if (AddOperandCI) {
8150 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8151 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8152 // since we truncate to TruncTy, the AddConstant should be of the
8153 // same type, so create a new Constant with type same as TruncTy.
8154 // Also, the Add constant should be shifted right by AShr amount.
8155 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8156 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8157 // we model the expression as sext(add(trunc(A), c << n)), since the
8158 // sext(trunc) part is already handled below, we create a
8159 // AddExpr(TruncExp) which will be used later.
8160 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8161 }
8162 }
8163 } else if (L && L->getOpcode() == Instruction::Shl) {
8164 // X = Shl A, n
8165 // Y = AShr X, m
8166 // Both n and m are constant.
8167
8168 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8169 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8170 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8171 }
8172
8173 if (AddTruncateExpr && ShlAmtCI) {
8174 // We can merge the two given cases into a single SCEV statement,
8175 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8176 // a simpler case. The following code handles the two cases:
8177 //
8178 // 1) For a two-shift sext-inreg, i.e. n = m,
8179 // use sext(trunc(x)) as the SCEV expression.
8180 //
8181 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8182 // expression. We already checked that ShlAmt < BitWidth, so
8183 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8184 // ShlAmt - AShrAmt < Amt.
8185 const APInt &ShlAmt = ShlAmtCI->getValue();
8186 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8187 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8188 ShlAmtCI->getZExtValue() - AShrAmt);
8189 const SCEV *CompositeExpr =
8190 getMulExpr(AddTruncateExpr, getConstant(Mul));
8191 if (L->getOpcode() != Instruction::Shl)
8192 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8193
8194 return getSignExtendExpr(CompositeExpr, OuterTy);
8195 }
8196 }
8197 break;
8198 }
8199 }
8200
8201 switch (U->getOpcode()) {
8202 case Instruction::Trunc:
8203 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8204
8205 case Instruction::ZExt:
8206 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8207
8208 case Instruction::SExt:
8209 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8211 // The NSW flag of a subtract does not always survive the conversion to
8212 // A + (-1)*B. By pushing sign extension onto its operands we are much
8213 // more likely to preserve NSW and allow later AddRec optimisations.
8214 //
8215 // NOTE: This is effectively duplicating this logic from getSignExtend:
8216 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8217 // but by that point the NSW information has potentially been lost.
8218 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8219 Type *Ty = U->getType();
8220 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8221 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8222 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8223 }
8224 }
8225 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8226
8227 case Instruction::BitCast:
8228 // BitCasts are no-op casts so we just eliminate the cast.
8229 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8230 return getSCEV(U->getOperand(0));
8231 break;
8232
8233 case Instruction::PtrToAddr: {
8234 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8235 if (isa<SCEVCouldNotCompute>(IntOp))
8236 return getUnknown(V);
8237 return IntOp;
8238 }
8239
8240 case Instruction::PtrToInt:
8241 // SCEV only models ptrtoaddr.
8242 return getUnknown(V);
8243
8244 case Instruction::IntToPtr:
8245 // Just don't deal with inttoptr casts.
8246 return getUnknown(V);
8247
8248 case Instruction::SDiv:
8249 // If both operands are non-negative, this is just an udiv.
8250 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8251 isKnownNonNegative(getSCEV(U->getOperand(1))))
8252 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8253 break;
8254
8255 case Instruction::SRem:
8256 // If both operands are non-negative, this is just an urem.
8257 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8258 isKnownNonNegative(getSCEV(U->getOperand(1))))
8259 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8260 break;
8261
8262 case Instruction::GetElementPtr:
8263 return createNodeForGEP(cast<GEPOperator>(U));
8264
8265 case Instruction::PHI:
8266 return createNodeForPHI(cast<PHINode>(U));
8267
8268 case Instruction::Select:
8269 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8270 U->getOperand(2));
8271
8272 case Instruction::Call:
8273 case Instruction::Invoke:
8274 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8275 return getSCEV(RV);
8276
8277 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8278 switch (II->getIntrinsicID()) {
8279 case Intrinsic::abs:
8280 return getAbsExpr(
8281 getSCEV(II->getArgOperand(0)),
8282 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8283 case Intrinsic::umax:
8284 LHS = getSCEV(II->getArgOperand(0));
8285 RHS = getSCEV(II->getArgOperand(1));
8286 return getUMaxExpr(LHS, RHS);
8287 case Intrinsic::umin:
8288 LHS = getSCEV(II->getArgOperand(0));
8289 RHS = getSCEV(II->getArgOperand(1));
8290 return getUMinExpr(LHS, RHS);
8291 case Intrinsic::smax:
8292 LHS = getSCEV(II->getArgOperand(0));
8293 RHS = getSCEV(II->getArgOperand(1));
8294 return getSMaxExpr(LHS, RHS);
8295 case Intrinsic::smin:
8296 LHS = getSCEV(II->getArgOperand(0));
8297 RHS = getSCEV(II->getArgOperand(1));
8298 return getSMinExpr(LHS, RHS);
8299 case Intrinsic::usub_sat: {
8300 const SCEV *X = getSCEV(II->getArgOperand(0));
8301 const SCEV *Y = getSCEV(II->getArgOperand(1));
8302 const SCEV *ClampedY = getUMinExpr(X, Y);
8303 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8304 }
8305 case Intrinsic::uadd_sat: {
8306 const SCEV *X = getSCEV(II->getArgOperand(0));
8307 const SCEV *Y = getSCEV(II->getArgOperand(1));
8308 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8309 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8310 }
8311 case Intrinsic::start_loop_iterations:
8312 case Intrinsic::annotation:
8313 case Intrinsic::ptr_annotation:
8314 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8315 // just eqivalent to the first operand for SCEV purposes.
8316 return getSCEV(II->getArgOperand(0));
8317 case Intrinsic::vscale:
8318 return getVScale(II->getType());
8319 default:
8320 break;
8321 }
8322 }
8323 break;
8324 }
8325
8326 return getUnknown(V);
8327}
8328
8329//===----------------------------------------------------------------------===//
8330// Iteration Count Computation Code
8331//
8332
8334 if (isa<SCEVCouldNotCompute>(ExitCount))
8335 return getCouldNotCompute();
8336
8337 auto *ExitCountType = ExitCount->getType();
8338 assert(ExitCountType->isIntegerTy());
8339 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8340 1 + ExitCountType->getScalarSizeInBits());
8341 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8342}
8343
8345 Type *EvalTy,
8346 const Loop *L) {
8347 if (isa<SCEVCouldNotCompute>(ExitCount))
8348 return getCouldNotCompute();
8349
8350 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8351 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8352
8353 auto CanAddOneWithoutOverflow = [&]() {
8354 ConstantRange ExitCountRange =
8355 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8356 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8357 return true;
8358
8359 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8360 getMinusOne(ExitCount->getType()));
8361 };
8362
8363 // If we need to zero extend the backedge count, check if we can add one to
8364 // it prior to zero extending without overflow. Provided this is safe, it
8365 // allows better simplification of the +1.
8366 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8367 return getZeroExtendExpr(
8368 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8369
8370 // Get the total trip count from the count by adding 1. This may wrap.
8371 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8372}
8373
8374static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8375 if (!ExitCount)
8376 return 0;
8377
8378 ConstantInt *ExitConst = ExitCount->getValue();
8379
8380 // Guard against huge trip counts.
8381 if (ExitConst->getValue().getActiveBits() > 32)
8382 return 0;
8383
8384 // In case of integer overflow, this returns 0, which is correct.
8385 return ((unsigned)ExitConst->getZExtValue()) + 1;
8386}
8387
8389 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8390 return getConstantTripCount(ExitCount);
8391}
8392
8393unsigned
8395 const BasicBlock *ExitingBlock) {
8396 assert(ExitingBlock && "Must pass a non-null exiting block!");
8397 assert(L->isLoopExiting(ExitingBlock) &&
8398 "Exiting block must actually branch out of the loop!");
8399 const SCEVConstant *ExitCount =
8400 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8401 return getConstantTripCount(ExitCount);
8402}
8403
8405 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8406
8407 const auto *MaxExitCount =
8408 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8410 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8411}
8412
8414 SmallVector<BasicBlock *, 8> ExitingBlocks;
8415 L->getExitingBlocks(ExitingBlocks);
8416
8417 std::optional<unsigned> Res;
8418 for (auto *ExitingBB : ExitingBlocks) {
8419 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
8420 if (!Res)
8421 Res = Multiple;
8422 Res = std::gcd(*Res, Multiple);
8423 }
8424 return Res.value_or(1);
8425}
8426
8428 const SCEV *ExitCount) {
8429 if (isa<SCEVCouldNotCompute>(ExitCount))
8430 return 1;
8431
8432 // Get the trip count
8433 const SCEV *TCExpr = getTripCountFromExitCount(applyLoopGuards(ExitCount, L));
8434
8435 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8436 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8437 // the greatest power of 2 divisor less than 2^32.
8438 return Multiple.getActiveBits() > 32
8439 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8440 : (unsigned)Multiple.getZExtValue();
8441}
8442
8443/// Returns the largest constant divisor of the trip count of this loop as a
8444/// normal unsigned value, if possible. This means that the actual trip count is
8445/// always a multiple of the returned value (don't forget the trip count could
8446/// very well be zero as well!).
8447///
8448/// Returns 1 if the trip count is unknown or not guaranteed to be the
8449/// multiple of a constant (which is also the case if the trip count is simply
8450/// constant, use getSmallConstantTripCount for that case), Will also return 1
8451/// if the trip count is very large (>= 2^32).
8452///
8453/// As explained in the comments for getSmallConstantTripCount, this assumes
8454/// that control exits the loop via ExitingBlock.
8455unsigned
8457 const BasicBlock *ExitingBlock) {
8458 assert(ExitingBlock && "Must pass a non-null exiting block!");
8459 assert(L->isLoopExiting(ExitingBlock) &&
8460 "Exiting block must actually branch out of the loop!");
8461 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8462 return getSmallConstantTripMultiple(L, ExitCount);
8463}
8464
8466 const BasicBlock *ExitingBlock,
8467 ExitCountKind Kind) {
8468 switch (Kind) {
8469 case Exact:
8470 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8471 case SymbolicMaximum:
8472 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8473 case ConstantMaximum:
8474 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8475 };
8476 llvm_unreachable("Invalid ExitCountKind!");
8477}
8478
8480 const Loop *L, const BasicBlock *ExitingBlock,
8482 switch (Kind) {
8483 case Exact:
8484 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8485 Predicates);
8486 case SymbolicMaximum:
8487 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8488 Predicates);
8489 case ConstantMaximum:
8490 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8491 Predicates);
8492 };
8493 llvm_unreachable("Invalid ExitCountKind!");
8494}
8495
8498 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8499}
8500
8502 ExitCountKind Kind) {
8503 switch (Kind) {
8504 case Exact:
8505 return getBackedgeTakenInfo(L).getExact(L, this);
8506 case ConstantMaximum:
8507 return getBackedgeTakenInfo(L).getConstantMax(this);
8508 case SymbolicMaximum:
8509 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8510 };
8511 llvm_unreachable("Invalid ExitCountKind!");
8512}
8513
8516 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8517}
8518
8521 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8522}
8523
8525 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8526}
8527
8528/// Push PHI nodes in the header of the given loop onto the given Worklist.
8529static void PushLoopPHIs(const Loop *L,
8532 BasicBlock *Header = L->getHeader();
8533
8534 // Push all Loop-header PHIs onto the Worklist stack.
8535 for (PHINode &PN : Header->phis())
8536 if (Visited.insert(&PN).second)
8537 Worklist.push_back(&PN);
8538}
8539
8540ScalarEvolution::BackedgeTakenInfo &
8541ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8542 auto &BTI = getBackedgeTakenInfo(L);
8543 if (BTI.hasFullInfo())
8544 return BTI;
8545
8546 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8547
8548 if (!Pair.second)
8549 return Pair.first->second;
8550
8551 BackedgeTakenInfo Result =
8552 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8553
8554 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8555}
8556
8557ScalarEvolution::BackedgeTakenInfo &
8558ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8559 // Initially insert an invalid entry for this loop. If the insertion
8560 // succeeds, proceed to actually compute a backedge-taken count and
8561 // update the value. The temporary CouldNotCompute value tells SCEV
8562 // code elsewhere that it shouldn't attempt to request a new
8563 // backedge-taken count, which could result in infinite recursion.
8564 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8565 BackedgeTakenCounts.try_emplace(L);
8566 if (!Pair.second)
8567 return Pair.first->second;
8568
8569 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8570 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8571 // must be cleared in this scope.
8572 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8573
8574 // Now that we know more about the trip count for this loop, forget any
8575 // existing SCEV values for PHI nodes in this loop since they are only
8576 // conservative estimates made without the benefit of trip count
8577 // information. This invalidation is not necessary for correctness, and is
8578 // only done to produce more precise results.
8579 if (Result.hasAnyInfo()) {
8580 // Invalidate any expression using an addrec in this loop.
8581 SmallVector<SCEVUse, 8> ToForget;
8582 auto LoopUsersIt = LoopUsers.find(L);
8583 if (LoopUsersIt != LoopUsers.end())
8584 append_range(ToForget, LoopUsersIt->second);
8585 forgetMemoizedResults(ToForget);
8586
8587 // Invalidate constant-evolved loop header phis.
8588 for (PHINode &PN : L->getHeader()->phis())
8589 ConstantEvolutionLoopExitValue.erase(&PN);
8590 }
8591
8592 // Re-lookup the insert position, since the call to
8593 // computeBackedgeTakenCount above could result in a
8594 // recusive call to getBackedgeTakenInfo (on a different
8595 // loop), which would invalidate the iterator computed
8596 // earlier.
8597 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8598}
8599
8601 // This method is intended to forget all info about loops. It should
8602 // invalidate caches as if the following happened:
8603 // - The trip counts of all loops have changed arbitrarily
8604 // - Every llvm::Value has been updated in place to produce a different
8605 // result.
8606 BackedgeTakenCounts.clear();
8607 PredicatedBackedgeTakenCounts.clear();
8608 BECountUsers.clear();
8609 LoopPropertiesCache.clear();
8610 ConstantEvolutionLoopExitValue.clear();
8611 ValueExprMap.clear();
8612 ValuesAtScopes.clear();
8613 ValuesAtScopesUsers.clear();
8614 LoopDispositions.clear();
8615 BlockDispositions.clear();
8616 UnsignedRanges.clear();
8617 SignedRanges.clear();
8618 ExprValueMap.clear();
8619 HasRecMap.clear();
8620 ConstantMultipleCache.clear();
8621 PredicatedSCEVRewrites.clear();
8622 FoldCache.clear();
8623 FoldCacheUser.clear();
8624}
8625void ScalarEvolution::visitAndClearUsers(
8628 SmallVectorImpl<SCEVUse> &ToForget) {
8629 while (!Worklist.empty()) {
8630 Instruction *I = Worklist.pop_back_val();
8631 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8632 continue;
8633
8635 ValueExprMap.find_as(static_cast<Value *>(I));
8636 if (It != ValueExprMap.end()) {
8637 ToForget.push_back(It->second);
8638 eraseValueFromMap(It->first);
8639 if (PHINode *PN = dyn_cast<PHINode>(I))
8640 ConstantEvolutionLoopExitValue.erase(PN);
8641 }
8642
8643 PushDefUseChildren(I, Worklist, Visited);
8644 }
8645}
8646
8648 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8651 SmallVector<SCEVUse, 16> ToForget;
8652
8653 // Iterate over all the loops and sub-loops to drop SCEV information.
8654 while (!LoopWorklist.empty()) {
8655 auto *CurrL = LoopWorklist.pop_back_val();
8656
8657 // Drop any stored trip count value.
8658 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8659 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8660
8661 // Drop information about predicated SCEV rewrites for this loop.
8662 PredicatedSCEVRewrites.remove_if(
8663 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8664
8665 auto LoopUsersItr = LoopUsers.find(CurrL);
8666 if (LoopUsersItr != LoopUsers.end())
8667 llvm::append_range(ToForget, LoopUsersItr->second);
8668
8669 // Drop information about expressions based on loop-header PHIs.
8670 PushLoopPHIs(CurrL, Worklist, Visited);
8671 visitAndClearUsers(Worklist, Visited, ToForget);
8672
8673 LoopPropertiesCache.erase(CurrL);
8674 // Forget all contained loops too, to avoid dangling entries in the
8675 // ValuesAtScopes map.
8676 LoopWorklist.append(CurrL->begin(), CurrL->end());
8677 }
8678 forgetMemoizedResults(ToForget);
8679}
8680
8682 forgetLoop(L->getOutermostLoop());
8683}
8684
8687 if (!I) return;
8688
8689 // Drop information about expressions based on loop-header PHIs.
8692 SmallVector<SCEVUse, 8> ToForget;
8693 Worklist.push_back(I);
8694 Visited.insert(I);
8695 visitAndClearUsers(Worklist, Visited, ToForget);
8696
8697 forgetMemoizedResults(ToForget);
8698}
8699
8701 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8702 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8703 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8704 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8705 auto InvalidateValue = [&](Value *Val) {
8706 if (!isSCEVable(Val->getType()))
8707 return;
8708 if (const SCEV *S = getExistingSCEV(Val)) {
8709 struct InvalidationRootCollector {
8710 Loop *L;
8712
8713 InvalidationRootCollector(Loop *L) : L(L) {}
8714
8715 bool follow(const SCEV *S) {
8716 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8717 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8718 if (L->contains(I))
8719 Roots.push_back(S);
8720 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8721 if (L->contains(AddRec->getLoop()))
8722 Roots.push_back(S);
8723 }
8724 return true;
8725 }
8726 bool isDone() const { return false; }
8727 };
8728
8729 InvalidationRootCollector C(L);
8730 visitAll(S, C);
8731 forgetMemoizedResults(C.Roots);
8732 }
8733 };
8734
8735 InvalidateValue(V);
8736
8737 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8738 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8739 // expressions referencing loop-internal values.
8740 if (!isSCEVable(V->getType()) && any_of(V->incoming_values(), [](Value *Inc) {
8741 return isa<WithOverflowInst>(Inc);
8742 }))
8743 for (User *U : V->users())
8744 InvalidateValue(U);
8745 // Also perform the normal invalidation.
8746 forgetValue(V);
8747}
8748
8749void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8750
8752 // Unless a specific value is passed to invalidation, completely clear both
8753 // caches.
8754 if (!V) {
8755 BlockDispositions.clear();
8756 LoopDispositions.clear();
8757 return;
8758 }
8759
8760 if (!isSCEVable(V->getType()))
8761 return;
8762
8763 const SCEV *S = getExistingSCEV(V);
8764 if (!S)
8765 return;
8766
8767 // Invalidate the block and loop dispositions cached for S. Dispositions of
8768 // S's users may change if S's disposition changes (i.e. a user may change to
8769 // loop-invariant, if S changes to loop invariant), so also invalidate
8770 // dispositions of S's users recursively.
8771 SmallVector<SCEVUse, 8> Worklist = {S};
8773 while (!Worklist.empty()) {
8774 const SCEV *Curr = Worklist.pop_back_val();
8775 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8776 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8777 if (!LoopDispoRemoved && !BlockDispoRemoved)
8778 continue;
8779 auto Users = SCEVUsers.find(Curr);
8780 if (Users != SCEVUsers.end())
8781 for (const auto *User : Users->second)
8782 if (Seen.insert(User).second)
8783 Worklist.push_back(User);
8784 }
8785}
8786
8787/// Get the exact loop backedge taken count considering all loop exits. A
8788/// computable result can only be returned for loops with all exiting blocks
8789/// dominating the latch. howFarToZero assumes that the limit of each loop test
8790/// is never skipped. This is a valid assumption as long as the loop exits via
8791/// that test. For precise results, it is the caller's responsibility to specify
8792/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8793const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8794 const Loop *L, ScalarEvolution *SE,
8796 // If any exits were not computable, the loop is not computable.
8797 if (!isComplete() || ExitNotTaken.empty())
8798 return SE->getCouldNotCompute();
8799
8800 const BasicBlock *Latch = L->getLoopLatch();
8801 // All exiting blocks we have collected must dominate the only backedge.
8802 if (!Latch)
8803 return SE->getCouldNotCompute();
8804
8805 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8806 // count is simply a minimum out of all these calculated exit counts.
8808 for (const auto &ENT : ExitNotTaken) {
8809 const SCEV *BECount = ENT.ExactNotTaken;
8810 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8811 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8812 "We should only have known counts for exiting blocks that dominate "
8813 "latch!");
8814
8815 Ops.push_back(BECount);
8816
8817 if (Preds)
8818 append_range(*Preds, ENT.Predicates);
8819
8820 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8821 "Predicate should be always true!");
8822 }
8823
8824 // If an earlier exit exits on the first iteration (exit count zero), then
8825 // a later poison exit count should not propagate into the result. This are
8826 // exactly the semantics provided by umin_seq.
8827 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8828}
8829
8830const ScalarEvolution::ExitNotTakenInfo *
8831ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8832 const BasicBlock *ExitingBlock,
8833 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8834 for (const auto &ENT : ExitNotTaken)
8835 if (ENT.ExitingBlock == ExitingBlock) {
8836 if (ENT.hasAlwaysTruePredicate())
8837 return &ENT;
8838 else if (Predicates) {
8839 append_range(*Predicates, ENT.Predicates);
8840 return &ENT;
8841 }
8842 }
8843
8844 return nullptr;
8845}
8846
8847/// getConstantMax - Get the constant max backedge taken count for the loop.
8848const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8849 ScalarEvolution *SE,
8850 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8851 if (!getConstantMax())
8852 return SE->getCouldNotCompute();
8853
8854 for (const auto &ENT : ExitNotTaken)
8855 if (!ENT.hasAlwaysTruePredicate()) {
8856 if (!Predicates)
8857 return SE->getCouldNotCompute();
8858 append_range(*Predicates, ENT.Predicates);
8859 }
8860
8861 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8862 isa<SCEVConstant>(getConstantMax())) &&
8863 "No point in having a non-constant max backedge taken count!");
8864 return getConstantMax();
8865}
8866
8867const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8868 const Loop *L, ScalarEvolution *SE,
8869 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8870 if (!SymbolicMax) {
8871 // Form an expression for the maximum exit count possible for this loop. We
8872 // merge the max and exact information to approximate a version of
8873 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8874 // constants.
8875 SmallVector<SCEVUse, 4> ExitCounts;
8876
8877 for (const auto &ENT : ExitNotTaken) {
8878 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8879 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8880 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8881 "We should only have known counts for exiting blocks that "
8882 "dominate latch!");
8883 ExitCounts.push_back(ExitCount);
8884 if (Predicates)
8885 append_range(*Predicates, ENT.Predicates);
8886
8887 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8888 "Predicate should be always true!");
8889 }
8890 }
8891 if (ExitCounts.empty())
8892 SymbolicMax = SE->getCouldNotCompute();
8893 else
8894 SymbolicMax =
8895 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8896 }
8897 return SymbolicMax;
8898}
8899
8900bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8901 ScalarEvolution *SE) const {
8902 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8903 return !ENT.hasAlwaysTruePredicate();
8904 };
8905 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8906}
8907
8910
8912 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8913 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8917 // If we prove the max count is zero, so is the symbolic bound. This happens
8918 // in practice due to differences in a) how context sensitive we've chosen
8919 // to be and b) how we reason about bounds implied by UB.
8920 if (ConstantMaxNotTaken->isZero()) {
8921 this->ExactNotTaken = E = ConstantMaxNotTaken;
8922 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8923 }
8924
8927 "Exact is not allowed to be less precise than Constant Max");
8930 "Exact is not allowed to be less precise than Symbolic Max");
8933 "Symbolic Max is not allowed to be less precise than Constant Max");
8936 "No point in having a non-constant max backedge taken count!");
8938 for (const auto PredList : PredLists)
8939 for (const auto *P : PredList) {
8940 if (SeenPreds.contains(P))
8941 continue;
8942 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8943 SeenPreds.insert(P);
8944 Predicates.push_back(P);
8945 }
8946 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8947 "Backedge count should be int");
8949 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8950 "Max backedge count should be int");
8951}
8952
8960
8961/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8962/// computable exit into a persistent ExitNotTakenInfo array.
8963ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8965 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8966 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8967 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8968
8969 ExitNotTaken.reserve(ExitCounts.size());
8970 std::transform(ExitCounts.begin(), ExitCounts.end(),
8971 std::back_inserter(ExitNotTaken),
8972 [&](const EdgeExitInfo &EEI) {
8973 BasicBlock *ExitBB = EEI.first;
8974 const ExitLimit &EL = EEI.second;
8975 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8976 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8977 EL.Predicates);
8978 });
8979 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8980 isa<SCEVConstant>(ConstantMax)) &&
8981 "No point in having a non-constant max backedge taken count!");
8982}
8983
8984/// Compute the number of times the backedge of the specified loop will execute.
8985ScalarEvolution::BackedgeTakenInfo
8986ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8987 bool AllowPredicates) {
8988 SmallVector<BasicBlock *, 8> ExitingBlocks;
8989 L->getExitingBlocks(ExitingBlocks);
8990
8991 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8992
8994 bool CouldComputeBECount = true;
8995 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8996 const SCEV *MustExitMaxBECount = nullptr;
8997 const SCEV *MayExitMaxBECount = nullptr;
8998 bool MustExitMaxOrZero = false;
8999 bool IsOnlyExit = ExitingBlocks.size() == 1;
9000
9001 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9002 // and compute maxBECount.
9003 // Do a union of all the predicates here.
9004 for (BasicBlock *ExitBB : ExitingBlocks) {
9005 // We canonicalize untaken exits to br (constant), ignore them so that
9006 // proving an exit untaken doesn't negatively impact our ability to reason
9007 // about the loop as whole.
9008 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9009 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9010 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9011 if (ExitIfTrue == CI->isZero())
9012 continue;
9013 }
9014
9015 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9016
9017 assert((AllowPredicates || EL.Predicates.empty()) &&
9018 "Predicated exit limit when predicates are not allowed!");
9019
9020 // 1. For each exit that can be computed, add an entry to ExitCounts.
9021 // CouldComputeBECount is true only if all exits can be computed.
9022 if (EL.ExactNotTaken != getCouldNotCompute())
9023 ++NumExitCountsComputed;
9024 else
9025 // We couldn't compute an exact value for this exit, so
9026 // we won't be able to compute an exact value for the loop.
9027 CouldComputeBECount = false;
9028 // Remember exit count if either exact or symbolic is known. Because
9029 // Exact always implies symbolic, only check symbolic.
9030 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9031 ExitCounts.emplace_back(ExitBB, EL);
9032 else {
9033 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9034 "Exact is known but symbolic isn't?");
9035 ++NumExitCountsNotComputed;
9036 }
9037
9038 // 2. Derive the loop's MaxBECount from each exit's max number of
9039 // non-exiting iterations. Partition the loop exits into two kinds:
9040 // LoopMustExits and LoopMayExits.
9041 //
9042 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9043 // is a LoopMayExit. If any computable LoopMustExit is found, then
9044 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9045 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9046 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9047 // any
9048 // computable EL.ConstantMaxNotTaken.
9049 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9050 DT.dominates(ExitBB, Latch)) {
9051 if (!MustExitMaxBECount) {
9052 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9053 MustExitMaxOrZero = EL.MaxOrZero;
9054 } else {
9055 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9056 EL.ConstantMaxNotTaken);
9057 }
9058 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9059 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9060 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9061 else {
9062 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9063 EL.ConstantMaxNotTaken);
9064 }
9065 }
9066 }
9067 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9068 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9069 // The loop backedge will be taken the maximum or zero times if there's
9070 // a single exit that must be taken the maximum or zero times.
9071 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9072
9073 // Remember which SCEVs are used in exit limits for invalidation purposes.
9074 // We only care about non-constant SCEVs here, so we can ignore
9075 // EL.ConstantMaxNotTaken
9076 // and MaxBECount, which must be SCEVConstant.
9077 for (const auto &Pair : ExitCounts) {
9078 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9079 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9080 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9081 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9082 {L, AllowPredicates});
9083 }
9084 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9085 MaxBECount, MaxOrZero);
9086}
9087
9088ScalarEvolution::ExitLimit
9089ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9090 bool IsOnlyExit, bool AllowPredicates) {
9091 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9092 // If our exiting block does not dominate the latch, then its connection with
9093 // loop's exit limit may be far from trivial.
9094 const BasicBlock *Latch = L->getLoopLatch();
9095 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9096 return getCouldNotCompute();
9097
9098 Instruction *Term = ExitingBlock->getTerminator();
9099 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9100 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9101 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9102 "It should have one successor in loop and one exit block!");
9103 // Proceed to the next level to examine the exit condition expression.
9104 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9105 /*ControlsOnlyExit=*/IsOnlyExit,
9106 AllowPredicates);
9107 }
9108
9109 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9110 // For switch, make sure that there is a single exit from the loop.
9111 BasicBlock *Exit = nullptr;
9112 for (auto *SBB : successors(ExitingBlock))
9113 if (!L->contains(SBB)) {
9114 if (Exit) // Multiple exit successors.
9115 return getCouldNotCompute();
9116 Exit = SBB;
9117 }
9118 assert(Exit && "Exiting block must have at least one exit");
9119 return computeExitLimitFromSingleExitSwitch(
9120 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9121 }
9122
9123 return getCouldNotCompute();
9124}