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