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