LLVM 19.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"
66#include "llvm/ADT/FoldingSet.h"
67#include "llvm/ADT/STLExtras.h"
68#include "llvm/ADT/ScopeExit.h"
69#include "llvm/ADT/Sequence.h"
71#include "llvm/ADT/SmallSet.h"
73#include "llvm/ADT/Statistic.h"
75#include "llvm/ADT/StringRef.h"
84#include "llvm/Config/llvm-config.h"
85#include "llvm/IR/Argument.h"
86#include "llvm/IR/BasicBlock.h"
87#include "llvm/IR/CFG.h"
88#include "llvm/IR/Constant.h"
90#include "llvm/IR/Constants.h"
91#include "llvm/IR/DataLayout.h"
93#include "llvm/IR/Dominators.h"
94#include "llvm/IR/Function.h"
95#include "llvm/IR/GlobalAlias.h"
96#include "llvm/IR/GlobalValue.h"
98#include "llvm/IR/InstrTypes.h"
99#include "llvm/IR/Instruction.h"
100#include "llvm/IR/Instructions.h"
102#include "llvm/IR/Intrinsics.h"
103#include "llvm/IR/LLVMContext.h"
104#include "llvm/IR/Operator.h"
105#include "llvm/IR/PatternMatch.h"
106#include "llvm/IR/Type.h"
107#include "llvm/IR/Use.h"
108#include "llvm/IR/User.h"
109#include "llvm/IR/Value.h"
110#include "llvm/IR/Verifier.h"
112#include "llvm/Pass.h"
113#include "llvm/Support/Casting.h"
116#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;
136
137#define DEBUG_TYPE "scalar-evolution"
138
139STATISTIC(NumExitCountsComputed,
140 "Number of loop exits with predictable exit counts");
141STATISTIC(NumExitCountsNotComputed,
142 "Number of loop exits without predictable exit counts");
143STATISTIC(NumBruteForceTripCountsComputed,
144 "Number of loops with trip counts computed by force");
145
146#ifdef EXPENSIVE_CHECKS
147bool llvm::VerifySCEV = true;
148#else
149bool llvm::VerifySCEV = false;
150#endif
151
153 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
154 cl::desc("Maximum number of iterations SCEV will "
155 "symbolically execute a constant "
156 "derived loop"),
157 cl::init(100));
158
160 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
163 "verify-scev-strict", cl::Hidden,
164 cl::desc("Enable stricter verification with -verify-scev is passed"));
165
167 "scev-verify-ir", cl::Hidden,
168 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
169 cl::init(false));
170
172 "scev-mulops-inline-threshold", cl::Hidden,
173 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
174 cl::init(32));
175
177 "scev-addops-inline-threshold", cl::Hidden,
178 cl::desc("Threshold for inlining addition operands into a SCEV"),
179 cl::init(500));
180
182 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
183 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
184 cl::init(32));
185
187 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
188 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
189 cl::init(2));
190
192 "scalar-evolution-max-value-compare-depth", cl::Hidden,
193 cl::desc("Maximum depth of recursive value complexity comparisons"),
194 cl::init(2));
195
197 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
198 cl::desc("Maximum depth of recursive arithmetics"),
199 cl::init(32));
200
202 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
203 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
204
206 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
207 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
208 cl::init(8));
209
211 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
212 cl::desc("Max coefficients in AddRec during evolving"),
213 cl::init(8));
214
216 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
217 cl::desc("Size of the expression which is considered huge"),
218 cl::init(4096));
219
221 "scev-range-iter-threshold", cl::Hidden,
222 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
223 cl::init(32));
224
225static cl::opt<bool>
226ClassifyExpressions("scalar-evolution-classify-expressions",
227 cl::Hidden, cl::init(true),
228 cl::desc("When printing analysis, include information on every instruction"));
229
231 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
232 cl::init(false),
233 cl::desc("Use more powerful methods of sharpening expression ranges. May "
234 "be costly in terms of compile time"));
235
237 "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
238 cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
239 "Phi strongly connected components"),
240 cl::init(8));
241
242static cl::opt<bool>
243 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
244 cl::desc("Handle <= and >= in finite loops"),
245 cl::init(true));
246
248 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
249 cl::desc("Infer nuw/nsw flags using context where suitable"),
250 cl::init(true));
251
252//===----------------------------------------------------------------------===//
253// SCEV class definitions
254//===----------------------------------------------------------------------===//
255
256//===----------------------------------------------------------------------===//
257// Implementation of the SCEV class.
258//
259
260#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
262 print(dbgs());
263 dbgs() << '\n';
264}
265#endif
266
268 switch (getSCEVType()) {
269 case scConstant:
270 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
271 return;
272 case scVScale:
273 OS << "vscale";
274 return;
275 case scPtrToInt: {
276 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
277 const SCEV *Op = PtrToInt->getOperand();
278 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
279 << *PtrToInt->getType() << ")";
280 return;
281 }
282 case scTruncate: {
283 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
284 const SCEV *Op = Trunc->getOperand();
285 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
286 << *Trunc->getType() << ")";
287 return;
288 }
289 case scZeroExtend: {
290 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
291 const SCEV *Op = ZExt->getOperand();
292 OS << "(zext " << *Op->getType() << " " << *Op << " to "
293 << *ZExt->getType() << ")";
294 return;
295 }
296 case scSignExtend: {
297 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
298 const SCEV *Op = SExt->getOperand();
299 OS << "(sext " << *Op->getType() << " " << *Op << " to "
300 << *SExt->getType() << ")";
301 return;
302 }
303 case scAddRecExpr: {
304 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
305 OS << "{" << *AR->getOperand(0);
306 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
307 OS << ",+," << *AR->getOperand(i);
308 OS << "}<";
309 if (AR->hasNoUnsignedWrap())
310 OS << "nuw><";
311 if (AR->hasNoSignedWrap())
312 OS << "nsw><";
313 if (AR->hasNoSelfWrap() &&
315 OS << "nw><";
316 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
317 OS << ">";
318 return;
319 }
320 case scAddExpr:
321 case scMulExpr:
322 case scUMaxExpr:
323 case scSMaxExpr:
324 case scUMinExpr:
325 case scSMinExpr:
327 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
328 const char *OpStr = nullptr;
329 switch (NAry->getSCEVType()) {
330 case scAddExpr: OpStr = " + "; break;
331 case scMulExpr: OpStr = " * "; break;
332 case scUMaxExpr: OpStr = " umax "; break;
333 case scSMaxExpr: OpStr = " smax "; break;
334 case scUMinExpr:
335 OpStr = " umin ";
336 break;
337 case scSMinExpr:
338 OpStr = " smin ";
339 break;
341 OpStr = " umin_seq ";
342 break;
343 default:
344 llvm_unreachable("There are no other nary expression types.");
345 }
346 OS << "(";
347 ListSeparator LS(OpStr);
348 for (const SCEV *Op : NAry->operands())
349 OS << LS << *Op;
350 OS << ")";
351 switch (NAry->getSCEVType()) {
352 case scAddExpr:
353 case scMulExpr:
354 if (NAry->hasNoUnsignedWrap())
355 OS << "<nuw>";
356 if (NAry->hasNoSignedWrap())
357 OS << "<nsw>";
358 break;
359 default:
360 // Nothing to print for other nary expressions.
361 break;
362 }
363 return;
364 }
365 case scUDivExpr: {
366 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
367 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
368 return;
369 }
370 case scUnknown:
371 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
372 return;
374 OS << "***COULDNOTCOMPUTE***";
375 return;
376 }
377 llvm_unreachable("Unknown SCEV kind!");
378}
379
381 switch (getSCEVType()) {
382 case scConstant:
383 return cast<SCEVConstant>(this)->getType();
384 case scVScale:
385 return cast<SCEVVScale>(this)->getType();
386 case scPtrToInt:
387 case scTruncate:
388 case scZeroExtend:
389 case scSignExtend:
390 return cast<SCEVCastExpr>(this)->getType();
391 case scAddRecExpr:
392 return cast<SCEVAddRecExpr>(this)->getType();
393 case scMulExpr:
394 return cast<SCEVMulExpr>(this)->getType();
395 case scUMaxExpr:
396 case scSMaxExpr:
397 case scUMinExpr:
398 case scSMinExpr:
399 return cast<SCEVMinMaxExpr>(this)->getType();
401 return cast<SCEVSequentialMinMaxExpr>(this)->getType();
402 case scAddExpr:
403 return cast<SCEVAddExpr>(this)->getType();
404 case scUDivExpr:
405 return cast<SCEVUDivExpr>(this)->getType();
406 case scUnknown:
407 return cast<SCEVUnknown>(this)->getType();
409 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
410 }
411 llvm_unreachable("Unknown SCEV kind!");
412}
413
415 switch (getSCEVType()) {
416 case scConstant:
417 case scVScale:
418 case scUnknown:
419 return {};
420 case scPtrToInt:
421 case scTruncate:
422 case scZeroExtend:
423 case scSignExtend:
424 return cast<SCEVCastExpr>(this)->operands();
425 case scAddRecExpr:
426 case scAddExpr:
427 case scMulExpr:
428 case scUMaxExpr:
429 case scSMaxExpr:
430 case scUMinExpr:
431 case scSMinExpr:
433 return cast<SCEVNAryExpr>(this)->operands();
434 case scUDivExpr:
435 return cast<SCEVUDivExpr>(this)->operands();
437 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
438 }
439 llvm_unreachable("Unknown SCEV kind!");
440}
441
442bool SCEV::isZero() const {
443 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
444 return SC->getValue()->isZero();
445 return false;
446}
447
448bool SCEV::isOne() const {
449 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
450 return SC->getValue()->isOne();
451 return false;
452}
453
455 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
456 return SC->getValue()->isMinusOne();
457 return false;
458}
459
461 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
462 if (!Mul) return false;
463
464 // If there is a constant factor, it will be first.
465 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
466 if (!SC) return false;
467
468 // Return true if the value is negative, this matches things like (-42 * V).
469 return SC->getAPInt().isNegative();
470}
471
474
476 return S->getSCEVType() == scCouldNotCompute;
477}
478
481 ID.AddInteger(scConstant);
482 ID.AddPointer(V);
483 void *IP = nullptr;
484 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
485 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
486 UniqueSCEVs.InsertNode(S, IP);
487 return S;
488}
489
491 return getConstant(ConstantInt::get(getContext(), Val));
492}
493
494const SCEV *
496 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
497 return getConstant(ConstantInt::get(ITy, V, isSigned));
498}
499
502 ID.AddInteger(scVScale);
503 ID.AddPointer(Ty);
504 void *IP = nullptr;
505 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
506 return S;
507 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
508 UniqueSCEVs.InsertNode(S, IP);
509 return S;
510}
511
513 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
514 if (EC.isScalable())
515 Res = getMulExpr(Res, getVScale(Ty));
516 return Res;
517}
518
520 const SCEV *op, Type *ty)
521 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
522
523SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
524 Type *ITy)
525 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
527 "Must be a non-bit-width-changing pointer-to-integer cast!");
528}
529
531 SCEVTypes SCEVTy, const SCEV *op,
532 Type *ty)
533 : SCEVCastExpr(ID, SCEVTy, op, ty) {}
534
535SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
536 Type *ty)
538 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
539 "Cannot truncate non-integer value!");
540}
541
542SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
543 const SCEV *op, Type *ty)
545 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
546 "Cannot zero extend non-integer value!");
547}
548
549SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
550 const SCEV *op, Type *ty)
552 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
553 "Cannot sign extend non-integer value!");
554}
555
556void SCEVUnknown::deleted() {
557 // Clear this SCEVUnknown from various maps.
558 SE->forgetMemoizedResults(this);
559
560 // Remove this SCEVUnknown from the uniquing map.
561 SE->UniqueSCEVs.RemoveNode(this);
562
563 // Release the value.
564 setValPtr(nullptr);
565}
566
567void SCEVUnknown::allUsesReplacedWith(Value *New) {
568 // Clear this SCEVUnknown from various maps.
569 SE->forgetMemoizedResults(this);
570
571 // Remove this SCEVUnknown from the uniquing map.
572 SE->UniqueSCEVs.RemoveNode(this);
573
574 // Replace the value pointer in case someone is still using this SCEVUnknown.
575 setValPtr(New);
576}
577
578//===----------------------------------------------------------------------===//
579// SCEV Utilities
580//===----------------------------------------------------------------------===//
581
582/// Compare the two values \p LV and \p RV in terms of their "complexity" where
583/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
584/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
585/// have been previously deemed to be "equally complex" by this routine. It is
586/// intended to avoid exponential time complexity in cases like:
587///
588/// %a = f(%x, %y)
589/// %b = f(%a, %a)
590/// %c = f(%b, %b)
591///
592/// %d = f(%x, %y)
593/// %e = f(%d, %d)
594/// %f = f(%e, %e)
595///
596/// CompareValueComplexity(%f, %c)
597///
598/// Since we do not continue running this routine on expression trees once we
599/// have seen unequal values, there is no need to track them in the cache.
600static int
602 const LoopInfo *const LI, Value *LV, Value *RV,
603 unsigned Depth) {
604 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
605 return 0;
606
607 // Order pointer values after integer values. This helps SCEVExpander form
608 // GEPs.
609 bool LIsPointer = LV->getType()->isPointerTy(),
610 RIsPointer = RV->getType()->isPointerTy();
611 if (LIsPointer != RIsPointer)
612 return (int)LIsPointer - (int)RIsPointer;
613
614 // Compare getValueID values.
615 unsigned LID = LV->getValueID(), RID = RV->getValueID();
616 if (LID != RID)
617 return (int)LID - (int)RID;
618
619 // Sort arguments by their position.
620 if (const auto *LA = dyn_cast<Argument>(LV)) {
621 const auto *RA = cast<Argument>(RV);
622 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
623 return (int)LArgNo - (int)RArgNo;
624 }
625
626 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
627 const auto *RGV = cast<GlobalValue>(RV);
628
629 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
630 auto LT = GV->getLinkage();
631 return !(GlobalValue::isPrivateLinkage(LT) ||
633 };
634
635 // Use the names to distinguish the two values, but only if the
636 // names are semantically important.
637 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
638 return LGV->getName().compare(RGV->getName());
639 }
640
641 // For instructions, compare their loop depth, and their operand count. This
642 // is pretty loose.
643 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
644 const auto *RInst = cast<Instruction>(RV);
645
646 // Compare loop depths.
647 const BasicBlock *LParent = LInst->getParent(),
648 *RParent = RInst->getParent();
649 if (LParent != RParent) {
650 unsigned LDepth = LI->getLoopDepth(LParent),
651 RDepth = LI->getLoopDepth(RParent);
652 if (LDepth != RDepth)
653 return (int)LDepth - (int)RDepth;
654 }
655
656 // Compare the number of operands.
657 unsigned LNumOps = LInst->getNumOperands(),
658 RNumOps = RInst->getNumOperands();
659 if (LNumOps != RNumOps)
660 return (int)LNumOps - (int)RNumOps;
661
662 for (unsigned Idx : seq(LNumOps)) {
663 int Result =
664 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
665 RInst->getOperand(Idx), Depth + 1);
666 if (Result != 0)
667 return Result;
668 }
669 }
670
671 EqCacheValue.unionSets(LV, RV);
672 return 0;
673}
674
675// Return negative, zero, or positive, if LHS is less than, equal to, or greater
676// than RHS, respectively. A three-way result allows recursive comparisons to be
677// more efficient.
678// If the max analysis depth was reached, return std::nullopt, assuming we do
679// not know if they are equivalent for sure.
680static std::optional<int>
683 const LoopInfo *const LI, const SCEV *LHS,
684 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
685 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
686 if (LHS == RHS)
687 return 0;
688
689 // Primarily, sort the SCEVs by their getSCEVType().
690 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
691 if (LType != RType)
692 return (int)LType - (int)RType;
693
694 if (EqCacheSCEV.isEquivalent(LHS, RHS))
695 return 0;
696
698 return std::nullopt;
699
700 // Aside from the getSCEVType() ordering, the particular ordering
701 // isn't very important except that it's beneficial to be consistent,
702 // so that (a + b) and (b + a) don't end up as different expressions.
703 switch (LType) {
704 case scUnknown: {
705 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
706 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
707
708 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
709 RU->getValue(), Depth + 1);
710 if (X == 0)
711 EqCacheSCEV.unionSets(LHS, RHS);
712 return X;
713 }
714
715 case scConstant: {
716 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
717 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
718
719 // Compare constant values.
720 const APInt &LA = LC->getAPInt();
721 const APInt &RA = RC->getAPInt();
722 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
723 if (LBitWidth != RBitWidth)
724 return (int)LBitWidth - (int)RBitWidth;
725 return LA.ult(RA) ? -1 : 1;
726 }
727
728 case scVScale: {
729 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
730 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
731 return LTy->getBitWidth() - RTy->getBitWidth();
732 }
733
734 case scAddRecExpr: {
735 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
736 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
737
738 // There is always a dominance between two recs that are used by one SCEV,
739 // so we can safely sort recs by loop header dominance. We require such
740 // order in getAddExpr.
741 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
742 if (LLoop != RLoop) {
743 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
744 assert(LHead != RHead && "Two loops share the same header?");
745 if (DT.dominates(LHead, RHead))
746 return 1;
747 assert(DT.dominates(RHead, LHead) &&
748 "No dominance between recurrences used by one SCEV?");
749 return -1;
750 }
751
752 [[fallthrough]];
753 }
754
755 case scTruncate:
756 case scZeroExtend:
757 case scSignExtend:
758 case scPtrToInt:
759 case scAddExpr:
760 case scMulExpr:
761 case scUDivExpr:
762 case scSMaxExpr:
763 case scUMaxExpr:
764 case scSMinExpr:
765 case scUMinExpr:
767 ArrayRef<const SCEV *> LOps = LHS->operands();
768 ArrayRef<const SCEV *> ROps = RHS->operands();
769
770 // Lexicographically compare n-ary-like expressions.
771 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
772 if (LNumOps != RNumOps)
773 return (int)LNumOps - (int)RNumOps;
774
775 for (unsigned i = 0; i != LNumOps; ++i) {
776 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LOps[i],
777 ROps[i], DT, Depth + 1);
778 if (X != 0)
779 return X;
780 }
781 EqCacheSCEV.unionSets(LHS, RHS);
782 return 0;
783 }
784
786 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
787 }
788 llvm_unreachable("Unknown SCEV kind!");
789}
790
791/// Given a list of SCEV objects, order them by their complexity, and group
792/// objects of the same complexity together by value. When this routine is
793/// finished, we know that any duplicates in the vector are consecutive and that
794/// complexity is monotonically increasing.
795///
796/// Note that we go take special precautions to ensure that we get deterministic
797/// results from this routine. In other words, we don't want the results of
798/// this to depend on where the addresses of various SCEV objects happened to
799/// land in memory.
801 LoopInfo *LI, DominatorTree &DT) {
802 if (Ops.size() < 2) return; // Noop
803
806
807 // Whether LHS has provably less complexity than RHS.
808 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
809 auto Complexity =
810 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
811 return Complexity && *Complexity < 0;
812 };
813 if (Ops.size() == 2) {
814 // This is the common case, which also happens to be trivially simple.
815 // Special case it.
816 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
817 if (IsLessComplex(RHS, LHS))
818 std::swap(LHS, RHS);
819 return;
820 }
821
822 // Do the rough sort by complexity.
823 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
824 return IsLessComplex(LHS, RHS);
825 });
826
827 // Now that we are sorted by complexity, group elements of the same
828 // complexity. Note that this is, at worst, N^2, but the vector is likely to
829 // be extremely short in practice. Note that we take this approach because we
830 // do not want to depend on the addresses of the objects we are grouping.
831 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
832 const SCEV *S = Ops[i];
833 unsigned Complexity = S->getSCEVType();
834
835 // If there are any objects of the same complexity and same value as this
836 // one, group them.
837 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
838 if (Ops[j] == S) { // Found a duplicate.
839 // Move it to immediately after i'th element.
840 std::swap(Ops[i+1], Ops[j]);
841 ++i; // no need to rescan it.
842 if (i == e-2) return; // Done!
843 }
844 }
845 }
846}
847
848/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
849/// least HugeExprThreshold nodes).
851 return any_of(Ops, [](const SCEV *S) {
853 });
854}
855
856//===----------------------------------------------------------------------===//
857// Simple SCEV method implementations
858//===----------------------------------------------------------------------===//
859
860/// Compute BC(It, K). The result has width W. Assume, K > 0.
861static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
862 ScalarEvolution &SE,
863 Type *ResultTy) {
864 // Handle the simplest case efficiently.
865 if (K == 1)
866 return SE.getTruncateOrZeroExtend(It, ResultTy);
867
868 // We are using the following formula for BC(It, K):
869 //
870 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
871 //
872 // Suppose, W is the bitwidth of the return value. We must be prepared for
873 // overflow. Hence, we must assure that the result of our computation is
874 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
875 // safe in modular arithmetic.
876 //
877 // However, this code doesn't use exactly that formula; the formula it uses
878 // is something like the following, where T is the number of factors of 2 in
879 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
880 // exponentiation:
881 //
882 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
883 //
884 // This formula is trivially equivalent to the previous formula. However,
885 // this formula can be implemented much more efficiently. The trick is that
886 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
887 // arithmetic. To do exact division in modular arithmetic, all we have
888 // to do is multiply by the inverse. Therefore, this step can be done at
889 // width W.
890 //
891 // The next issue is how to safely do the division by 2^T. The way this
892 // is done is by doing the multiplication step at a width of at least W + T
893 // bits. This way, the bottom W+T bits of the product are accurate. Then,
894 // when we perform the division by 2^T (which is equivalent to a right shift
895 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
896 // truncated out after the division by 2^T.
897 //
898 // In comparison to just directly using the first formula, this technique
899 // is much more efficient; using the first formula requires W * K bits,
900 // but this formula less than W + K bits. Also, the first formula requires
901 // a division step, whereas this formula only requires multiplies and shifts.
902 //
903 // It doesn't matter whether the subtraction step is done in the calculation
904 // width or the input iteration count's width; if the subtraction overflows,
905 // the result must be zero anyway. We prefer here to do it in the width of
906 // the induction variable because it helps a lot for certain cases; CodeGen
907 // isn't smart enough to ignore the overflow, which leads to much less
908 // efficient code if the width of the subtraction is wider than the native
909 // register width.
910 //
911 // (It's possible to not widen at all by pulling out factors of 2 before
912 // the multiplication; for example, K=2 can be calculated as
913 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
914 // extra arithmetic, so it's not an obvious win, and it gets
915 // much more complicated for K > 3.)
916
917 // Protection from insane SCEVs; this bound is conservative,
918 // but it probably doesn't matter.
919 if (K > 1000)
920 return SE.getCouldNotCompute();
921
922 unsigned W = SE.getTypeSizeInBits(ResultTy);
923
924 // Calculate K! / 2^T and T; we divide out the factors of two before
925 // multiplying for calculating K! / 2^T to avoid overflow.
926 // Other overflow doesn't matter because we only care about the bottom
927 // W bits of the result.
928 APInt OddFactorial(W, 1);
929 unsigned T = 1;
930 for (unsigned i = 3; i <= K; ++i) {
931 unsigned TwoFactors = countr_zero(i);
932 T += TwoFactors;
933 OddFactorial *= (i >> TwoFactors);
934 }
935
936 // We need at least W + T bits for the multiplication step
937 unsigned CalculationBits = W + T;
938
939 // Calculate 2^T, at width T+W.
940 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
941
942 // Calculate the multiplicative inverse of K! / 2^T;
943 // this multiplication factor will perform the exact division by
944 // K! / 2^T.
945 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
946
947 // Calculate the product, at width T+W
948 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
949 CalculationBits);
950 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
951 for (unsigned i = 1; i != K; ++i) {
952 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
953 Dividend = SE.getMulExpr(Dividend,
954 SE.getTruncateOrZeroExtend(S, CalculationTy));
955 }
956
957 // Divide by 2^T
958 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
959
960 // Truncate the result, and divide by K! / 2^T.
961
962 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
963 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
964}
965
966/// Return the value of this chain of recurrences at the specified iteration
967/// number. We can evaluate this recurrence by multiplying each element in the
968/// chain by the binomial coefficient corresponding to it. In other words, we
969/// can evaluate {A,+,B,+,C,+,D} as:
970///
971/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
972///
973/// where BC(It, k) stands for binomial coefficient.
975 ScalarEvolution &SE) const {
976 return evaluateAtIteration(operands(), It, SE);
977}
978
979const SCEV *
981 const SCEV *It, ScalarEvolution &SE) {
982 assert(Operands.size() > 0);
983 const SCEV *Result = Operands[0];
984 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
985 // The computation is correct in the face of overflow provided that the
986 // multiplication is performed _after_ the evaluation of the binomial
987 // coefficient.
988 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
989 if (isa<SCEVCouldNotCompute>(Coeff))
990 return Coeff;
991
992 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
993 }
994 return Result;
995}
996
997//===----------------------------------------------------------------------===//
998// SCEV Expression folder implementations
999//===----------------------------------------------------------------------===//
1000
1002 unsigned Depth) {
1003 assert(Depth <= 1 &&
1004 "getLosslessPtrToIntExpr() should self-recurse at most once.");
1005
1006 // We could be called with an integer-typed operands during SCEV rewrites.
1007 // Since the operand is an integer already, just perform zext/trunc/self cast.
1008 if (!Op->getType()->isPointerTy())
1009 return Op;
1010
1011 // What would be an ID for such a SCEV cast expression?
1013 ID.AddInteger(scPtrToInt);
1014 ID.AddPointer(Op);
1015
1016 void *IP = nullptr;
1017
1018 // Is there already an expression for such a cast?
1019 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1020 return S;
1021
1022 // It isn't legal for optimizations to construct new ptrtoint expressions
1023 // for non-integral pointers.
1024 if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1025 return getCouldNotCompute();
1026
1027 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1028
1029 // We can only trivially model ptrtoint if SCEV's effective (integer) type
1030 // is sufficiently wide to represent all possible pointer values.
1031 // We could theoretically teach SCEV to truncate wider pointers, but
1032 // that isn't implemented for now.
1034 getDataLayout().getTypeSizeInBits(IntPtrTy))
1035 return getCouldNotCompute();
1036
1037 // If not, is this expression something we can't reduce any further?
1038 if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1039 // Perform some basic constant folding. If the operand of the ptr2int cast
1040 // is a null pointer, don't create a ptr2int SCEV expression (that will be
1041 // left as-is), but produce a zero constant.
1042 // NOTE: We could handle a more general case, but lack motivational cases.
1043 if (isa<ConstantPointerNull>(U->getValue()))
1044 return getZero(IntPtrTy);
1045
1046 // Create an explicit cast node.
1047 // We can reuse the existing insert position since if we get here,
1048 // we won't have made any changes which would invalidate it.
1049 SCEV *S = new (SCEVAllocator)
1050 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1051 UniqueSCEVs.InsertNode(S, IP);
1052 registerUser(S, Op);
1053 return S;
1054 }
1055
1056 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1057 "non-SCEVUnknown's.");
1058
1059 // Otherwise, we've got some expression that is more complex than just a
1060 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1061 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1062 // only, and the expressions must otherwise be integer-typed.
1063 // So sink the cast down to the SCEVUnknown's.
1064
1065 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1066 /// which computes a pointer-typed value, and rewrites the whole expression
1067 /// tree so that *all* the computations are done on integers, and the only
1068 /// pointer-typed operands in the expression are SCEVUnknown.
1069 class SCEVPtrToIntSinkingRewriter
1070 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1072
1073 public:
1074 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1075
1076 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1077 SCEVPtrToIntSinkingRewriter Rewriter(SE);
1078 return Rewriter.visit(Scev);
1079 }
1080
1081 const SCEV *visit(const SCEV *S) {
1082 Type *STy = S->getType();
1083 // If the expression is not pointer-typed, just keep it as-is.
1084 if (!STy->isPointerTy())
1085 return S;
1086 // Else, recursively sink the cast down into it.
1087 return Base::visit(S);
1088 }
1089
1090 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1092 bool Changed = false;
1093 for (const auto *Op : Expr->operands()) {
1094 Operands.push_back(visit(Op));
1095 Changed |= Op != Operands.back();
1096 }
1097 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1098 }
1099
1100 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1102 bool Changed = false;
1103 for (const auto *Op : Expr->operands()) {
1104 Operands.push_back(visit(Op));
1105 Changed |= Op != Operands.back();
1106 }
1107 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1108 }
1109
1110 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1111 assert(Expr->getType()->isPointerTy() &&
1112 "Should only reach pointer-typed SCEVUnknown's.");
1113 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1114 }
1115 };
1116
1117 // And actually perform the cast sinking.
1118 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1119 assert(IntOp->getType()->isIntegerTy() &&
1120 "We must have succeeded in sinking the cast, "
1121 "and ending up with an integer-typed expression!");
1122 return IntOp;
1123}
1124
1126 assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1127
1128 const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1129 if (isa<SCEVCouldNotCompute>(IntOp))
1130 return IntOp;
1131
1132 return getTruncateOrZeroExtend(IntOp, Ty);
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
1145 ID.AddInteger(scTruncate);
1146 ID.AddPointer(Op);
1147 ID.AddPointer(Ty);
1148 void *IP = nullptr;
1149 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1150
1151 // Fold if the operand is constant.
1152 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1153 return getConstant(
1154 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1155
1156 // trunc(trunc(x)) --> trunc(x)
1157 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1158 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1159
1160 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1161 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1162 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1163
1164 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1165 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1166 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1167
1168 if (Depth > MaxCastDepth) {
1169 SCEV *S =
1170 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1171 UniqueSCEVs.InsertNode(S, IP);
1172 registerUser(S, Op);
1173 return S;
1174 }
1175
1176 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1177 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1178 // if after transforming we have at most one truncate, not counting truncates
1179 // that replace other casts.
1180 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1181 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1183 unsigned numTruncs = 0;
1184 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1185 ++i) {
1186 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1187 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1188 isa<SCEVTruncateExpr>(S))
1189 numTruncs++;
1190 Operands.push_back(S);
1191 }
1192 if (numTruncs < 2) {
1193 if (isa<SCEVAddExpr>(Op))
1194 return getAddExpr(Operands);
1195 if (isa<SCEVMulExpr>(Op))
1196 return getMulExpr(Operands);
1197 llvm_unreachable("Unexpected SCEV type for Op.");
1198 }
1199 // Although we checked in the beginning that ID is not in the cache, it is
1200 // possible that during recursion and different modification ID was inserted
1201 // into the cache. So if we find it, just return it.
1202 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1203 return S;
1204 }
1205
1206 // If the input value is a chrec scev, truncate the chrec's operands.
1207 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1209 for (const SCEV *Op : AddRec->operands())
1210 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1211 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1212 }
1213
1214 // Return zero if truncating to known zeros.
1215 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1216 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1217 return getZero(Ty);
1218
1219 // The cast wasn't folded; create an explicit cast node. We can reuse
1220 // the existing insert position since if we get here, we won't have
1221 // made any changes which would invalidate it.
1222 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1223 Op, Ty);
1224 UniqueSCEVs.InsertNode(S, IP);
1225 registerUser(S, Op);
1226 return S;
1227}
1228
1229// Get the limit of a recurrence such that incrementing by Step cannot cause
1230// signed overflow as long as the value of the recurrence within the
1231// loop does not exceed this limit before incrementing.
1232static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1233 ICmpInst::Predicate *Pred,
1234 ScalarEvolution *SE) {
1235 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1236 if (SE->isKnownPositive(Step)) {
1237 *Pred = ICmpInst::ICMP_SLT;
1239 SE->getSignedRangeMax(Step));
1240 }
1241 if (SE->isKnownNegative(Step)) {
1242 *Pred = ICmpInst::ICMP_SGT;
1244 SE->getSignedRangeMin(Step));
1245 }
1246 return nullptr;
1247}
1248
1249// Get the limit of a recurrence such that incrementing by Step cannot cause
1250// unsigned overflow as long as the value of the recurrence within the loop does
1251// not exceed this limit before incrementing.
1253 ICmpInst::Predicate *Pred,
1254 ScalarEvolution *SE) {
1255 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1256 *Pred = ICmpInst::ICMP_ULT;
1257
1259 SE->getUnsignedRangeMax(Step));
1260}
1261
1262namespace {
1263
1264struct ExtendOpTraitsBase {
1265 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1266 unsigned);
1267};
1268
1269// Used to make code generic over signed and unsigned overflow.
1270template <typename ExtendOp> struct ExtendOpTraits {
1271 // Members present:
1272 //
1273 // static const SCEV::NoWrapFlags WrapType;
1274 //
1275 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1276 //
1277 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1278 // ICmpInst::Predicate *Pred,
1279 // ScalarEvolution *SE);
1280};
1281
1282template <>
1283struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1284 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1285
1286 static const GetExtendExprTy GetExtendExpr;
1287
1288 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1289 ICmpInst::Predicate *Pred,
1290 ScalarEvolution *SE) {
1291 return getSignedOverflowLimitForStep(Step, Pred, SE);
1292 }
1293};
1294
1295const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1297
1298template <>
1299struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1300 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1301
1302 static const GetExtendExprTy GetExtendExpr;
1303
1304 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1305 ICmpInst::Predicate *Pred,
1306 ScalarEvolution *SE) {
1307 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1308 }
1309};
1310
1311const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1313
1314} // end anonymous namespace
1315
1316// The recurrence AR has been shown to have no signed/unsigned wrap or something
1317// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1318// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1319// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1320// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1321// expression "Step + sext/zext(PreIncAR)" is congruent with
1322// "sext/zext(PostIncAR)"
1323template <typename ExtendOpTy>
1324static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1325 ScalarEvolution *SE, unsigned Depth) {
1326 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1327 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1328
1329 const Loop *L = AR->getLoop();
1330 const SCEV *Start = AR->getStart();
1331 const SCEV *Step = AR->getStepRecurrence(*SE);
1332
1333 // Check for a simple looking step prior to loop entry.
1334 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1335 if (!SA)
1336 return nullptr;
1337
1338 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1339 // subtraction is expensive. For this purpose, perform a quick and dirty
1340 // difference, by checking for Step in the operand list. Note, that
1341 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1343 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1344 if (*It == Step) {
1345 DiffOps.erase(It);
1346 break;
1347 }
1348
1349 if (DiffOps.size() == SA->getNumOperands())
1350 return nullptr;
1351
1352 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1353 // `Step`:
1354
1355 // 1. NSW/NUW flags on the step increment.
1356 auto PreStartFlags =
1358 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1359 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1360 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1361
1362 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1363 // "S+X does not sign/unsign-overflow".
1364 //
1365
1366 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1367 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1368 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1369 return PreStart;
1370
1371 // 2. Direct overflow check on the step operation's expression.
1372 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1373 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1374 const SCEV *OperandExtendedStart =
1375 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1376 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1377 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1378 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1379 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1380 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1381 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1382 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1383 }
1384 return PreStart;
1385 }
1386
1387 // 3. Loop precondition.
1389 const SCEV *OverflowLimit =
1390 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1391
1392 if (OverflowLimit &&
1393 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1394 return PreStart;
1395
1396 return nullptr;
1397}
1398
1399// Get the normalized zero or sign extended expression for this AddRec's Start.
1400template <typename ExtendOpTy>
1401static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1402 ScalarEvolution *SE,
1403 unsigned Depth) {
1404 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1405
1406 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1407 if (!PreStart)
1408 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1409
1410 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1411 Depth),
1412 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1413}
1414
1415// Try to prove away overflow by looking at "nearby" add recurrences. A
1416// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1417// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1418//
1419// Formally:
1420//
1421// {S,+,X} == {S-T,+,X} + T
1422// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1423//
1424// If ({S-T,+,X} + T) does not overflow ... (1)
1425//
1426// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1427//
1428// If {S-T,+,X} does not overflow ... (2)
1429//
1430// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1431// == {Ext(S-T)+Ext(T),+,Ext(X)}
1432//
1433// If (S-T)+T does not overflow ... (3)
1434//
1435// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1436// == {Ext(S),+,Ext(X)} == LHS
1437//
1438// Thus, if (1), (2) and (3) are true for some T, then
1439// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1440//
1441// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1442// does not overflow" restricted to the 0th iteration. Therefore we only need
1443// to check for (1) and (2).
1444//
1445// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1446// is `Delta` (defined below).
1447template <typename ExtendOpTy>
1448bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1449 const SCEV *Step,
1450 const Loop *L) {
1451 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1452
1453 // We restrict `Start` to a constant to prevent SCEV from spending too much
1454 // time here. It is correct (but more expensive) to continue with a
1455 // non-constant `Start` and do a general SCEV subtraction to compute
1456 // `PreStart` below.
1457 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1458 if (!StartC)
1459 return false;
1460
1461 APInt StartAI = StartC->getAPInt();
1462
1463 for (unsigned Delta : {-2, -1, 1, 2}) {
1464 const SCEV *PreStart = getConstant(StartAI - Delta);
1465
1467 ID.AddInteger(scAddRecExpr);
1468 ID.AddPointer(PreStart);
1469 ID.AddPointer(Step);
1470 ID.AddPointer(L);
1471 void *IP = nullptr;
1472 const auto *PreAR =
1473 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1474
1475 // Give up if we don't already have the add recurrence we need because
1476 // actually constructing an add recurrence is relatively expensive.
1477 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1478 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1480 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1481 DeltaS, &Pred, this);
1482 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1483 return true;
1484 }
1485 }
1486
1487 return false;
1488}
1489
1490// Finds an integer D for an expression (C + x + y + ...) such that the top
1491// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1492// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1493// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1494// the (C + x + y + ...) expression is \p WholeAddExpr.
1496 const SCEVConstant *ConstantTerm,
1497 const SCEVAddExpr *WholeAddExpr) {
1498 const APInt &C = ConstantTerm->getAPInt();
1499 const unsigned BitWidth = C.getBitWidth();
1500 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1501 uint32_t TZ = BitWidth;
1502 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1503 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1504 if (TZ) {
1505 // Set D to be as many least significant bits of C as possible while still
1506 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1507 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1508 }
1509 return APInt(BitWidth, 0);
1510}
1511
1512// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1513// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1514// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1515// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1517 const APInt &ConstantStart,
1518 const SCEV *Step) {
1519 const unsigned BitWidth = ConstantStart.getBitWidth();
1520 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1521 if (TZ)
1522 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1523 : ConstantStart;
1524 return APInt(BitWidth, 0);
1525}
1526
1528 const ScalarEvolution::FoldID &ID, const SCEV *S,
1531 &FoldCacheUser) {
1532 auto I = FoldCache.insert({ID, S});
1533 if (!I.second) {
1534 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1535 // entry.
1536 auto &UserIDs = FoldCacheUser[I.first->second];
1537 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1538 for (unsigned I = 0; I != UserIDs.size(); ++I)
1539 if (UserIDs[I] == ID) {
1540 std::swap(UserIDs[I], UserIDs.back());
1541 break;
1542 }
1543 UserIDs.pop_back();
1544 I.first->second = S;
1545 }
1546 auto R = FoldCacheUser.insert({S, {}});
1547 R.first->second.push_back(ID);
1548}
1549
1550const SCEV *
1552 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1553 "This is not an extending conversion!");
1554 assert(isSCEVable(Ty) &&
1555 "This is not a conversion to a SCEVable type!");
1556 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1557 Ty = getEffectiveSCEVType(Ty);
1558
1559 FoldID ID(scZeroExtend, Op, Ty);
1560 auto Iter = FoldCache.find(ID);
1561 if (Iter != FoldCache.end())
1562 return Iter->second;
1563
1564 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1565 if (!isa<SCEVZeroExtendExpr>(S))
1566 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1567 return S;
1568}
1569
1571 unsigned Depth) {
1572 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1573 "This is not an extending conversion!");
1574 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1575 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1576
1577 // Fold if the operand is constant.
1578 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1579 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1580
1581 // zext(zext(x)) --> zext(x)
1582 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1583 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1584
1585 // Before doing any expensive analysis, check to see if we've already
1586 // computed a SCEV for this Op and Ty.
1588 ID.AddInteger(scZeroExtend);
1589 ID.AddPointer(Op);
1590 ID.AddPointer(Ty);
1591 void *IP = nullptr;
1592 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1593 if (Depth > MaxCastDepth) {
1594 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1595 Op, Ty);
1596 UniqueSCEVs.InsertNode(S, IP);
1597 registerUser(S, Op);
1598 return S;
1599 }
1600
1601 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1602 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1603 // It's possible the bits taken off by the truncate were all zero bits. If
1604 // so, we should be able to simplify this further.
1605 const SCEV *X = ST->getOperand();
1607 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1608 unsigned NewBits = getTypeSizeInBits(Ty);
1609 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1610 CR.zextOrTrunc(NewBits)))
1611 return getTruncateOrZeroExtend(X, Ty, Depth);
1612 }
1613
1614 // If the input value is a chrec scev, and we can prove that the value
1615 // did not overflow the old, smaller, value, we can zero extend all of the
1616 // operands (often constants). This allows analysis of something like
1617 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1618 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1619 if (AR->isAffine()) {
1620 const SCEV *Start = AR->getStart();
1621 const SCEV *Step = AR->getStepRecurrence(*this);
1622 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1623 const Loop *L = AR->getLoop();
1624
1625 // If we have special knowledge that this addrec won't overflow,
1626 // we don't need to do any further analysis.
1627 if (AR->hasNoUnsignedWrap()) {
1628 Start =
1629 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1630 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1631 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1632 }
1633
1634 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1635 // Note that this serves two purposes: It filters out loops that are
1636 // simply not analyzable, and it covers the case where this code is
1637 // being called from within backedge-taken count analysis, such that
1638 // attempting to ask for the backedge-taken count would likely result
1639 // in infinite recursion. In the later case, the analysis code will
1640 // cope with a conservative value, and it will take care to purge
1641 // that value once it has finished.
1642 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1643 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1644 // Manually compute the final value for AR, checking for overflow.
1645
1646 // Check whether the backedge-taken count can be losslessly casted to
1647 // the addrec's type. The count is always unsigned.
1648 const SCEV *CastedMaxBECount =
1649 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1650 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1651 CastedMaxBECount, MaxBECount->getType(), Depth);
1652 if (MaxBECount == RecastedMaxBECount) {
1653 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1654 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1655 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1657 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1659 Depth + 1),
1660 WideTy, Depth + 1);
1661 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1662 const SCEV *WideMaxBECount =
1663 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1664 const SCEV *OperandExtendedAdd =
1665 getAddExpr(WideStart,
1666 getMulExpr(WideMaxBECount,
1667 getZeroExtendExpr(Step, WideTy, Depth + 1),
1670 if (ZAdd == OperandExtendedAdd) {
1671 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1672 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1673 // Return the expression with the addrec on the outside.
1674 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1675 Depth + 1);
1676 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1677 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1678 }
1679 // Similar to above, only this time treat the step value as signed.
1680 // This covers loops that count down.
1681 OperandExtendedAdd =
1682 getAddExpr(WideStart,
1683 getMulExpr(WideMaxBECount,
1684 getSignExtendExpr(Step, WideTy, Depth + 1),
1687 if (ZAdd == OperandExtendedAdd) {
1688 // Cache knowledge of AR NW, which is propagated to this AddRec.
1689 // Negative step causes unsigned wrap, but it still can't self-wrap.
1690 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1691 // Return the expression with the addrec on the outside.
1692 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1693 Depth + 1);
1694 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1695 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1696 }
1697 }
1698 }
1699
1700 // Normally, in the cases we can prove no-overflow via a
1701 // backedge guarding condition, we can also compute a backedge
1702 // taken count for the loop. The exceptions are assumptions and
1703 // guards present in the loop -- SCEV is not great at exploiting
1704 // these to compute max backedge taken counts, but can still use
1705 // these to prove lack of overflow. Use this fact to avoid
1706 // doing extra work that may not pay off.
1707 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1708 !AC.assumptions().empty()) {
1709
1710 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1711 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1712 if (AR->hasNoUnsignedWrap()) {
1713 // Same as nuw case above - duplicated here to avoid a compile time
1714 // issue. It's not clear that the order of checks does matter, but
1715 // it's one of two issue possible causes for a change which was
1716 // reverted. Be conservative for the moment.
1717 Start =
1718 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1719 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1720 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1721 }
1722
1723 // For a negative step, we can extend the operands iff doing so only
1724 // traverses values in the range zext([0,UINT_MAX]).
1725 if (isKnownNegative(Step)) {
1727 getSignedRangeMin(Step));
1730 // Cache knowledge of AR NW, which is propagated to this
1731 // AddRec. Negative step causes unsigned wrap, but it
1732 // still can't self-wrap.
1733 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1734 // Return the expression with the addrec on the outside.
1735 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1736 Depth + 1);
1737 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1738 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1739 }
1740 }
1741 }
1742
1743 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1744 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1745 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1746 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1747 const APInt &C = SC->getAPInt();
1748 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1749 if (D != 0) {
1750 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1751 const SCEV *SResidual =
1752 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1753 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1754 return getAddExpr(SZExtD, SZExtR,
1756 Depth + 1);
1757 }
1758 }
1759
1760 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1761 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1762 Start =
1763 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1764 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1765 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1766 }
1767 }
1768
1769 // zext(A % B) --> zext(A) % zext(B)
1770 {
1771 const SCEV *LHS;
1772 const SCEV *RHS;
1773 if (matchURem(Op, LHS, RHS))
1774 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1775 getZeroExtendExpr(RHS, Ty, Depth + 1));
1776 }
1777
1778 // zext(A / B) --> zext(A) / zext(B).
1779 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1780 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1781 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1782
1783 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1784 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1785 if (SA->hasNoUnsignedWrap()) {
1786 // If the addition does not unsign overflow then we can, by definition,
1787 // commute the zero extension with the addition operation.
1789 for (const auto *Op : SA->operands())
1790 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1791 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1792 }
1793
1794 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1795 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1796 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1797 //
1798 // Often address arithmetics contain expressions like
1799 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1800 // This transformation is useful while proving that such expressions are
1801 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1802 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1803 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1804 if (D != 0) {
1805 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1806 const SCEV *SResidual =
1808 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1809 return getAddExpr(SZExtD, SZExtR,
1811 Depth + 1);
1812 }
1813 }
1814 }
1815
1816 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1817 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1818 if (SM->hasNoUnsignedWrap()) {
1819 // If the multiply does not unsign overflow then we can, by definition,
1820 // commute the zero extension with the multiply operation.
1822 for (const auto *Op : SM->operands())
1823 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1824 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1825 }
1826
1827 // zext(2^K * (trunc X to iN)) to iM ->
1828 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1829 //
1830 // Proof:
1831 //
1832 // zext(2^K * (trunc X to iN)) to iM
1833 // = zext((trunc X to iN) << K) to iM
1834 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1835 // (because shl removes the top K bits)
1836 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1837 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1838 //
1839 if (SM->getNumOperands() == 2)
1840 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1841 if (MulLHS->getAPInt().isPowerOf2())
1842 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1843 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1844 MulLHS->getAPInt().logBase2();
1845 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1846 return getMulExpr(
1847 getZeroExtendExpr(MulLHS, Ty),
1849 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1850 SCEV::FlagNUW, Depth + 1);
1851 }
1852 }
1853
1854 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1855 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1856 if (isa<SCEVUMinExpr>(Op) || isa<SCEVUMaxExpr>(Op)) {
1857 auto *MinMax = cast<SCEVMinMaxExpr>(Op);
1859 for (auto *Operand : MinMax->operands())
1860 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1861 if (isa<SCEVUMinExpr>(MinMax))
1862 return getUMinExpr(Operands);
1863 return getUMaxExpr(Operands);
1864 }
1865
1866 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1867 if (auto *MinMax = dyn_cast<SCEVSequentialMinMaxExpr>(Op)) {
1868 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1870 for (auto *Operand : MinMax->operands())
1871 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1872 return getUMinExpr(Operands, /*Sequential*/ true);
1873 }
1874
1875 // The cast wasn't folded; create an explicit cast node.
1876 // Recompute the insert position, as it may have been invalidated.
1877 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1878 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1879 Op, Ty);
1880 UniqueSCEVs.InsertNode(S, IP);
1881 registerUser(S, Op);
1882 return S;
1883}
1884
1885const SCEV *
1887 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1888 "This is not an extending conversion!");
1889 assert(isSCEVable(Ty) &&
1890 "This is not a conversion to a SCEVable type!");
1891 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1892 Ty = getEffectiveSCEVType(Ty);
1893
1894 FoldID ID(scSignExtend, Op, Ty);
1895 auto Iter = FoldCache.find(ID);
1896 if (Iter != FoldCache.end())
1897 return Iter->second;
1898
1899 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1900 if (!isa<SCEVSignExtendExpr>(S))
1901 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1902 return S;
1903}
1904
1906 unsigned Depth) {
1907 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1908 "This is not an extending conversion!");
1909 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1910 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1911 Ty = getEffectiveSCEVType(Ty);
1912
1913 // Fold if the operand is constant.
1914 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1915 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1916
1917 // sext(sext(x)) --> sext(x)
1918 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1919 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1920
1921 // sext(zext(x)) --> zext(x)
1922 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1923 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1924
1925 // Before doing any expensive analysis, check to see if we've already
1926 // computed a SCEV for this Op and Ty.
1928 ID.AddInteger(scSignExtend);
1929 ID.AddPointer(Op);
1930 ID.AddPointer(Ty);
1931 void *IP = nullptr;
1932 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1933 // Limit recursion depth.
1934 if (Depth > MaxCastDepth) {
1935 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1936 Op, Ty);
1937 UniqueSCEVs.InsertNode(S, IP);
1938 registerUser(S, Op);
1939 return S;
1940 }
1941
1942 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1943 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1944 // It's possible the bits taken off by the truncate were all sign bits. If
1945 // so, we should be able to simplify this further.
1946 const SCEV *X = ST->getOperand();
1948 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1949 unsigned NewBits = getTypeSizeInBits(Ty);
1950 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1951 CR.sextOrTrunc(NewBits)))
1952 return getTruncateOrSignExtend(X, Ty, Depth);
1953 }
1954
1955 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1956 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1957 if (SA->hasNoSignedWrap()) {
1958 // If the addition does not sign overflow then we can, by definition,
1959 // commute the sign extension with the addition operation.
1961 for (const auto *Op : SA->operands())
1962 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1963 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1964 }
1965
1966 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1967 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1968 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1969 //
1970 // For instance, this will bring two seemingly different expressions:
1971 // 1 + sext(5 + 20 * %x + 24 * %y) and
1972 // sext(6 + 20 * %x + 24 * %y)
1973 // to the same form:
1974 // 2 + sext(4 + 20 * %x + 24 * %y)
1975 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1976 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1977 if (D != 0) {
1978 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1979 const SCEV *SResidual =
1981 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1982 return getAddExpr(SSExtD, SSExtR,
1984 Depth + 1);
1985 }
1986 }
1987 }
1988 // If the input value is a chrec scev, and we can prove that the value
1989 // did not overflow the old, smaller, value, we can sign extend all of the
1990 // operands (often constants). This allows analysis of something like
1991 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1992 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1993 if (AR->isAffine()) {
1994 const SCEV *Start = AR->getStart();
1995 const SCEV *Step = AR->getStepRecurrence(*this);
1996 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1997 const Loop *L = AR->getLoop();
1998
1999 // If we have special knowledge that this addrec won't overflow,
2000 // we don't need to do any further analysis.
2001 if (AR->hasNoSignedWrap()) {
2002 Start =
2003 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2004 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2005 return getAddRecExpr(Start, Step, L, SCEV::FlagNSW);
2006 }
2007
2008 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2009 // Note that this serves two purposes: It filters out loops that are
2010 // simply not analyzable, and it covers the case where this code is
2011 // being called from within backedge-taken count analysis, such that
2012 // attempting to ask for the backedge-taken count would likely result
2013 // in infinite recursion. In the later case, the analysis code will
2014 // cope with a conservative value, and it will take care to purge
2015 // that value once it has finished.
2016 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2017 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2018 // Manually compute the final value for AR, checking for
2019 // overflow.
2020
2021 // Check whether the backedge-taken count can be losslessly casted to
2022 // the addrec's type. The count is always unsigned.
2023 const SCEV *CastedMaxBECount =
2024 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2025 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2026 CastedMaxBECount, MaxBECount->getType(), Depth);
2027 if (MaxBECount == RecastedMaxBECount) {
2028 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2029 // Check whether Start+Step*MaxBECount has no signed overflow.
2030 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2032 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2034 Depth + 1),
2035 WideTy, Depth + 1);
2036 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2037 const SCEV *WideMaxBECount =
2038 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2039 const SCEV *OperandExtendedAdd =
2040 getAddExpr(WideStart,
2041 getMulExpr(WideMaxBECount,
2042 getSignExtendExpr(Step, WideTy, Depth + 1),
2045 if (SAdd == OperandExtendedAdd) {
2046 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2047 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2048 // Return the expression with the addrec on the outside.
2049 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2050 Depth + 1);
2051 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2052 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2053 }
2054 // Similar to above, only this time treat the step value as unsigned.
2055 // This covers loops that count up with an unsigned step.
2056 OperandExtendedAdd =
2057 getAddExpr(WideStart,
2058 getMulExpr(WideMaxBECount,
2059 getZeroExtendExpr(Step, WideTy, Depth + 1),
2062 if (SAdd == OperandExtendedAdd) {
2063 // If AR wraps around then
2064 //
2065 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2066 // => SAdd != OperandExtendedAdd
2067 //
2068 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2069 // (SAdd == OperandExtendedAdd => AR is NW)
2070
2071 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2072
2073 // Return the expression with the addrec on the outside.
2074 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2075 Depth + 1);
2076 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2077 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2078 }
2079 }
2080 }
2081
2082 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2083 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2084 if (AR->hasNoSignedWrap()) {
2085 // Same as nsw case above - duplicated here to avoid a compile time
2086 // issue. It's not clear that the order of checks does matter, but
2087 // it's one of two issue possible causes for a change which was
2088 // reverted. Be conservative for the moment.
2089 Start =
2090 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2091 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2092 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2093 }
2094
2095 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2096 // if D + (C - D + Step * n) could be proven to not signed wrap
2097 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2098 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2099 const APInt &C = SC->getAPInt();
2100 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2101 if (D != 0) {
2102 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2103 const SCEV *SResidual =
2104 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2105 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2106 return getAddExpr(SSExtD, SSExtR,
2108 Depth + 1);
2109 }
2110 }
2111
2112 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2113 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2114 Start =
2115 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2116 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2117 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2118 }
2119 }
2120
2121 // If the input value is provably positive and we could not simplify
2122 // away the sext build a zext instead.
2124 return getZeroExtendExpr(Op, Ty, Depth + 1);
2125
2126 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2127 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2128 if (isa<SCEVSMinExpr>(Op) || isa<SCEVSMaxExpr>(Op)) {
2129 auto *MinMax = cast<SCEVMinMaxExpr>(Op);
2131 for (auto *Operand : MinMax->operands())
2132 Operands.push_back(getSignExtendExpr(Operand, Ty));
2133 if (isa<SCEVSMinExpr>(MinMax))
2134 return getSMinExpr(Operands);
2135 return getSMaxExpr(Operands);
2136 }
2137
2138 // The cast wasn't folded; create an explicit cast node.
2139 // Recompute the insert position, as it may have been invalidated.
2140 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2141 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2142 Op, Ty);
2143 UniqueSCEVs.InsertNode(S, IP);
2144 registerUser(S, { Op });
2145 return S;
2146}
2147
2149 Type *Ty) {
2150 switch (Kind) {
2151 case scTruncate:
2152 return getTruncateExpr(Op, Ty);
2153 case scZeroExtend:
2154 return getZeroExtendExpr(Op, Ty);
2155 case scSignExtend:
2156 return getSignExtendExpr(Op, Ty);
2157 case scPtrToInt:
2158 return getPtrToIntExpr(Op, Ty);
2159 default:
2160 llvm_unreachable("Not a SCEV cast expression!");
2161 }
2162}
2163
2164/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2165/// unspecified bits out to the given type.
2167 Type *Ty) {
2168 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2169 "This is not an extending conversion!");
2170 assert(isSCEVable(Ty) &&
2171 "This is not a conversion to a SCEVable type!");
2172 Ty = getEffectiveSCEVType(Ty);
2173
2174 // Sign-extend negative constants.
2175 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2176 if (SC->getAPInt().isNegative())
2177 return getSignExtendExpr(Op, Ty);
2178
2179 // Peel off a truncate cast.
2180 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2181 const SCEV *NewOp = T->getOperand();
2182 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2183 return getAnyExtendExpr(NewOp, Ty);
2184 return getTruncateOrNoop(NewOp, Ty);
2185 }
2186
2187 // Next try a zext cast. If the cast is folded, use it.
2188 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2189 if (!isa<SCEVZeroExtendExpr>(ZExt))
2190 return ZExt;
2191
2192 // Next try a sext cast. If the cast is folded, use it.
2193 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2194 if (!isa<SCEVSignExtendExpr>(SExt))
2195 return SExt;
2196
2197 // Force the cast to be folded into the operands of an addrec.
2198 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2200 for (const SCEV *Op : AR->operands())
2201 Ops.push_back(getAnyExtendExpr(Op, Ty));
2202 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2203 }
2204
2205 // If the expression is obviously signed, use the sext cast value.
2206 if (isa<SCEVSMaxExpr>(Op))
2207 return SExt;
2208
2209 // Absent any other information, use the zext cast value.
2210 return ZExt;
2211}
2212
2213/// Process the given Ops list, which is a list of operands to be added under
2214/// the given scale, update the given map. This is a helper function for
2215/// getAddRecExpr. As an example of what it does, given a sequence of operands
2216/// that would form an add expression like this:
2217///
2218/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2219///
2220/// where A and B are constants, update the map with these values:
2221///
2222/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2223///
2224/// and add 13 + A*B*29 to AccumulatedConstant.
2225/// This will allow getAddRecExpr to produce this:
2226///
2227/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2228///
2229/// This form often exposes folding opportunities that are hidden in
2230/// the original operand list.
2231///
2232/// Return true iff it appears that any interesting folding opportunities
2233/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2234/// the common case where no interesting opportunities are present, and
2235/// is also used as a check to avoid infinite recursion.
2236static bool
2239 APInt &AccumulatedConstant,
2240 ArrayRef<const SCEV *> Ops, const APInt &Scale,
2241 ScalarEvolution &SE) {
2242 bool Interesting = false;
2243
2244 // Iterate over the add operands. They are sorted, with constants first.
2245 unsigned i = 0;
2246 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2247 ++i;
2248 // Pull a buried constant out to the outside.
2249 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2250 Interesting = true;
2251 AccumulatedConstant += Scale * C->getAPInt();
2252 }
2253
2254 // Next comes everything else. We're especially interested in multiplies
2255 // here, but they're in the middle, so just visit the rest with one loop.
2256 for (; i != Ops.size(); ++i) {
2257 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2258 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2259 APInt NewScale =
2260 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2261 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2262 // A multiplication of a constant with another add; recurse.
2263 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2264 Interesting |=
2265 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2266 Add->operands(), NewScale, SE);
2267 } else {
2268 // A multiplication of a constant with some other value. Update
2269 // the map.
2270 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2271 const SCEV *Key = SE.getMulExpr(MulOps);
2272 auto Pair = M.insert({Key, NewScale});
2273 if (Pair.second) {
2274 NewOps.push_back(Pair.first->first);
2275 } else {
2276 Pair.first->second += NewScale;
2277 // The map already had an entry for this value, which may indicate
2278 // a folding opportunity.
2279 Interesting = true;
2280 }
2281 }
2282 } else {
2283 // An ordinary operand. Update the map.
2284 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2285 M.insert({Ops[i], Scale});
2286 if (Pair.second) {
2287 NewOps.push_back(Pair.first->first);
2288 } else {
2289 Pair.first->second += Scale;
2290 // The map already had an entry for this value, which may indicate
2291 // a folding opportunity.
2292 Interesting = true;
2293 }
2294 }
2295 }
2296
2297 return Interesting;
2298}
2299
2301 const SCEV *LHS, const SCEV *RHS,
2302 const Instruction *CtxI) {
2303 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2304 SCEV::NoWrapFlags, unsigned);
2305 switch (BinOp) {
2306 default:
2307 llvm_unreachable("Unsupported binary op");
2308 case Instruction::Add:
2310 break;
2311 case Instruction::Sub:
2313 break;
2314 case Instruction::Mul:
2316 break;
2317 }
2318
2319 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2322
2323 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2324 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2325 auto *WideTy =
2326 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2327
2328 const SCEV *A = (this->*Extension)(
2329 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2330 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2331 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2332 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2333 if (A == B)
2334 return true;
2335 // Can we use context to prove the fact we need?
2336 if (!CtxI)
2337 return false;
2338 // TODO: Support mul.
2339 if (BinOp == Instruction::Mul)
2340 return false;
2341 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2342 // TODO: Lift this limitation.
2343 if (!RHSC)
2344 return false;
2345 APInt C = RHSC->getAPInt();
2346 unsigned NumBits = C.getBitWidth();
2347 bool IsSub = (BinOp == Instruction::Sub);
2348 bool IsNegativeConst = (Signed && C.isNegative());
2349 // Compute the direction and magnitude by which we need to check overflow.
2350 bool OverflowDown = IsSub ^ IsNegativeConst;
2351 APInt Magnitude = C;
2352 if (IsNegativeConst) {
2353 if (C == APInt::getSignedMinValue(NumBits))
2354 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2355 // want to deal with that.
2356 return false;
2357 Magnitude = -C;
2358 }
2359
2361 if (OverflowDown) {
2362 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2363 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2364 : APInt::getMinValue(NumBits);
2365 APInt Limit = Min + Magnitude;
2366 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2367 } else {
2368 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2369 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2370 : APInt::getMaxValue(NumBits);
2371 APInt Limit = Max - Magnitude;
2372 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2373 }
2374}
2375
2376std::optional<SCEV::NoWrapFlags>
2378 const OverflowingBinaryOperator *OBO) {
2379 // It cannot be done any better.
2380 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2381 return std::nullopt;
2382
2384
2385 if (OBO->hasNoUnsignedWrap())
2387 if (OBO->hasNoSignedWrap())
2389
2390 bool Deduced = false;
2391
2392 if (OBO->getOpcode() != Instruction::Add &&
2393 OBO->getOpcode() != Instruction::Sub &&
2394 OBO->getOpcode() != Instruction::Mul)
2395 return std::nullopt;
2396
2397 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2398 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2399
2400 const Instruction *CtxI =
2401 UseContextForNoWrapFlagInference ? dyn_cast<Instruction>(OBO) : nullptr;
2402 if (!OBO->hasNoUnsignedWrap() &&
2404 /* Signed */ false, LHS, RHS, CtxI)) {
2406 Deduced = true;
2407 }
2408
2409 if (!OBO->hasNoSignedWrap() &&
2411 /* Signed */ true, LHS, RHS, CtxI)) {
2413 Deduced = true;
2414 }
2415
2416 if (Deduced)
2417 return Flags;
2418 return std::nullopt;
2419}
2420
2421// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2422// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2423// can't-overflow flags for the operation if possible.
2424static SCEV::NoWrapFlags
2426 const ArrayRef<const SCEV *> Ops,
2427 SCEV::NoWrapFlags Flags) {
2428 using namespace std::placeholders;
2429
2430 using OBO = OverflowingBinaryOperator;
2431
2432 bool CanAnalyze =
2434 (void)CanAnalyze;
2435 assert(CanAnalyze && "don't call from other places!");
2436
2437 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2438 SCEV::NoWrapFlags SignOrUnsignWrap =
2439 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2440
2441 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2442 auto IsKnownNonNegative = [&](const SCEV *S) {
2443 return SE->isKnownNonNegative(S);
2444 };
2445
2446 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2447 Flags =
2448 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2449
2450 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2451
2452 if (SignOrUnsignWrap != SignOrUnsignMask &&
2453 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2454 isa<SCEVConstant>(Ops[0])) {
2455
2456 auto Opcode = [&] {
2457 switch (Type) {
2458 case scAddExpr:
2459 return Instruction::Add;
2460 case scMulExpr:
2461 return Instruction::Mul;
2462 default:
2463 llvm_unreachable("Unexpected SCEV op.");
2464 }
2465 }();
2466
2467 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2468
2469 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2470 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2472 Opcode, C, OBO::NoSignedWrap);
2473 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2475 }
2476
2477 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2478 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2480 Opcode, C, OBO::NoUnsignedWrap);
2481 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2483 }
2484 }
2485
2486 // <0,+,nonnegative><nw> is also nuw
2487 // TODO: Add corresponding nsw case
2489 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2490 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2492
2493 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2495 Ops.size() == 2) {
2496 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2497 if (UDiv->getOperand(1) == Ops[1])
2499 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2500 if (UDiv->getOperand(1) == Ops[0])
2502 }
2503
2504 return Flags;
2505}
2506
2508 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2509}
2510
2511/// Get a canonical add expression, or something simpler if possible.
2513 SCEV::NoWrapFlags OrigFlags,
2514 unsigned Depth) {
2515 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2516 "only nuw or nsw allowed");
2517 assert(!Ops.empty() && "Cannot get empty add!");
2518 if (Ops.size() == 1) return Ops[0];
2519#ifndef NDEBUG
2520 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2521 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2522 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2523 "SCEVAddExpr operand types don't match!");
2524 unsigned NumPtrs = count_if(
2525 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2526 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2527#endif
2528
2529 // Sort by complexity, this groups all similar expression types together.
2530 GroupByComplexity(Ops, &LI, DT);
2531
2532 // If there are any constants, fold them together.
2533 unsigned Idx = 0;
2534 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2535 ++Idx;
2536 assert(Idx < Ops.size());
2537 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2538 // We found two constants, fold them together!
2539 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2540 if (Ops.size() == 2) return Ops[0];
2541 Ops.erase(Ops.begin()+1); // Erase the folded element
2542 LHSC = cast<SCEVConstant>(Ops[0]);
2543 }
2544
2545 // If we are left with a constant zero being added, strip it off.
2546 if (LHSC->getValue()->isZero()) {
2547 Ops.erase(Ops.begin());
2548 --Idx;
2549 }
2550
2551 if (Ops.size() == 1) return Ops[0];
2552 }
2553
2554 // Delay expensive flag strengthening until necessary.
2555 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2556 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2557 };
2558
2559 // Limit recursion calls depth.
2561 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2562
2563 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2564 // Don't strengthen flags if we have no new information.
2565 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2566 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2567 Add->setNoWrapFlags(ComputeFlags(Ops));
2568 return S;
2569 }
2570
2571 // Okay, check to see if the same value occurs in the operand list more than
2572 // once. If so, merge them together into an multiply expression. Since we
2573 // sorted the list, these values are required to be adjacent.
2574 Type *Ty = Ops[0]->getType();
2575 bool FoundMatch = false;
2576 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2577 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2578 // Scan ahead to count how many equal operands there are.
2579 unsigned Count = 2;
2580 while (i+Count != e && Ops[i+Count] == Ops[i])
2581 ++Count;
2582 // Merge the values into a multiply.
2583 const SCEV *Scale = getConstant(Ty, Count);
2584 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2585 if (Ops.size() == Count)
2586 return Mul;
2587 Ops[i] = Mul;
2588 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2589 --i; e -= Count - 1;
2590 FoundMatch = true;
2591 }
2592 if (FoundMatch)
2593 return getAddExpr(Ops, OrigFlags, Depth + 1);
2594
2595 // Check for truncates. If all the operands are truncated from the same
2596 // type, see if factoring out the truncate would permit the result to be
2597 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2598 // if the contents of the resulting outer trunc fold to something simple.
2599 auto FindTruncSrcType = [&]() -> Type * {
2600 // We're ultimately looking to fold an addrec of truncs and muls of only
2601 // constants and truncs, so if we find any other types of SCEV
2602 // as operands of the addrec then we bail and return nullptr here.
2603 // Otherwise, we return the type of the operand of a trunc that we find.
2604 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2605 return T->getOperand()->getType();
2606 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2607 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2608 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2609 return T->getOperand()->getType();
2610 }
2611 return nullptr;
2612 };
2613 if (auto *SrcType = FindTruncSrcType()) {
2615 bool Ok = true;
2616 // Check all the operands to see if they can be represented in the
2617 // source type of the truncate.
2618 for (const SCEV *Op : Ops) {
2619 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2620 if (T->getOperand()->getType() != SrcType) {
2621 Ok = false;
2622 break;
2623 }
2624 LargeOps.push_back(T->getOperand());
2625 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2626 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2627 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2628 SmallVector<const SCEV *, 8> LargeMulOps;
2629 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2630 if (const SCEVTruncateExpr *T =
2631 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2632 if (T->getOperand()->getType() != SrcType) {
2633 Ok = false;
2634 break;
2635 }
2636 LargeMulOps.push_back(T->getOperand());
2637 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2638 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2639 } else {
2640 Ok = false;
2641 break;
2642 }
2643 }
2644 if (Ok)
2645 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2646 } else {
2647 Ok = false;
2648 break;
2649 }
2650 }
2651 if (Ok) {
2652 // Evaluate the expression in the larger type.
2653 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2654 // If it folds to something simple, use it. Otherwise, don't.
2655 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2656 return getTruncateExpr(Fold, Ty);
2657 }
2658 }
2659
2660 if (Ops.size() == 2) {
2661 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2662 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2663 // C1).
2664 const SCEV *A = Ops[0];
2665 const SCEV *B = Ops[1];
2666 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2667 auto *C = dyn_cast<SCEVConstant>(A);
2668 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2669 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2670 auto C2 = C->getAPInt();
2671 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2672
2673 APInt ConstAdd = C1 + C2;
2674 auto AddFlags = AddExpr->getNoWrapFlags();
2675 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2677 ConstAdd.ule(C1)) {
2678 PreservedFlags =
2680 }
2681
2682 // Adding a constant with the same sign and small magnitude is NSW, if the
2683 // original AddExpr was NSW.
2685 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2686 ConstAdd.abs().ule(C1.abs())) {
2687 PreservedFlags =
2689 }
2690
2691 if (PreservedFlags != SCEV::FlagAnyWrap) {
2692 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2693 NewOps[0] = getConstant(ConstAdd);
2694 return getAddExpr(NewOps, PreservedFlags);
2695 }
2696 }
2697 }
2698
2699 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2700 if (Ops.size() == 2) {
2701 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2702 if (Mul && Mul->getNumOperands() == 2 &&
2703 Mul->getOperand(0)->isAllOnesValue()) {
2704 const SCEV *X;
2705 const SCEV *Y;
2706 if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2707 return getMulExpr(Y, getUDivExpr(X, Y));
2708 }
2709 }
2710 }
2711
2712 // Skip past any other cast SCEVs.
2713 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2714 ++Idx;
2715
2716 // If there are add operands they would be next.
2717 if (Idx < Ops.size()) {
2718 bool DeletedAdd = false;
2719 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2720 // common NUW flag for expression after inlining. Other flags cannot be
2721 // preserved, because they may depend on the original order of operations.
2722 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2723 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2724 if (Ops.size() > AddOpsInlineThreshold ||
2725 Add->getNumOperands() > AddOpsInlineThreshold)
2726 break;
2727 // If we have an add, expand the add operands onto the end of the operands
2728 // list.
2729 Ops.erase(Ops.begin()+Idx);
2730 append_range(Ops, Add->operands());
2731 DeletedAdd = true;
2732 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2733 }
2734
2735 // If we deleted at least one add, we added operands to the end of the list,
2736 // and they are not necessarily sorted. Recurse to resort and resimplify
2737 // any operands we just acquired.
2738 if (DeletedAdd)
2739 return getAddExpr(Ops, CommonFlags, Depth + 1);
2740 }
2741
2742 // Skip over the add expression until we get to a multiply.
2743 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2744 ++Idx;
2745
2746 // Check to see if there are any folding opportunities present with
2747 // operands multiplied by constant values.
2748 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2752 APInt AccumulatedConstant(BitWidth, 0);
2753 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2754 Ops, APInt(BitWidth, 1), *this)) {
2755 struct APIntCompare {
2756 bool operator()(const APInt &LHS, const APInt &RHS) const {
2757 return LHS.ult(RHS);
2758 }
2759 };
2760
2761 // Some interesting folding opportunity is present, so its worthwhile to
2762 // re-generate the operands list. Group the operands by constant scale,
2763 // to avoid multiplying by the same constant scale multiple times.
2764 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2765 for (const SCEV *NewOp : NewOps)
2766 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2767 // Re-generate the operands list.
2768 Ops.clear();
2769 if (AccumulatedConstant != 0)
2770 Ops.push_back(getConstant(AccumulatedConstant));
2771 for (auto &MulOp : MulOpLists) {
2772 if (MulOp.first == 1) {
2773 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2774 } else if (MulOp.first != 0) {
2776 getConstant(MulOp.first),
2777 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2778 SCEV::FlagAnyWrap, Depth + 1));
2779 }
2780 }
2781 if (Ops.empty())
2782 return getZero(Ty);
2783 if (Ops.size() == 1)
2784 return Ops[0];
2785 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2786 }
2787 }
2788
2789 // If we are adding something to a multiply expression, make sure the
2790 // something is not already an operand of the multiply. If so, merge it into
2791 // the multiply.
2792 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2793 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2794 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2795 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2796 if (isa<SCEVConstant>(MulOpSCEV))
2797 continue;
2798 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2799 if (MulOpSCEV == Ops[AddOp]) {
2800 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2801 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2802 if (Mul->getNumOperands() != 2) {
2803 // If the multiply has more than two operands, we must get the
2804 // Y*Z term.
2806 Mul->operands().take_front(MulOp));
2807 append_range(MulOps, Mul->operands().drop_front(MulOp + 1));
2808 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2809 }
2810 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2811 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2812 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2814 if (Ops.size() == 2) return OuterMul;
2815 if (AddOp < Idx) {
2816 Ops.erase(Ops.begin()+AddOp);
2817 Ops.erase(Ops.begin()+Idx-1);
2818 } else {
2819 Ops.erase(Ops.begin()+Idx);
2820 Ops.erase(Ops.begin()+AddOp-1);
2821 }
2822 Ops.push_back(OuterMul);
2823 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2824 }
2825
2826 // Check this multiply against other multiplies being added together.
2827 for (unsigned OtherMulIdx = Idx+1;
2828 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2829 ++OtherMulIdx) {
2830 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2831 // If MulOp occurs in OtherMul, we can fold the two multiplies
2832 // together.
2833 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2834 OMulOp != e; ++OMulOp)
2835 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2836 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2837 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2838 if (Mul->getNumOperands() != 2) {
2840 Mul->operands().take_front(MulOp));
2841 append_range(MulOps, Mul->operands().drop_front(MulOp+1));
2842 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2843 }
2844 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2845 if (OtherMul->getNumOperands() != 2) {
2847 OtherMul->operands().take_front(OMulOp));
2848 append_range(MulOps, OtherMul->operands().drop_front(OMulOp+1));
2849 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2850 }
2851 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2852 const SCEV *InnerMulSum =
2853 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2854 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2856 if (Ops.size() == 2) return OuterMul;
2857 Ops.erase(Ops.begin()+Idx);
2858 Ops.erase(Ops.begin()+OtherMulIdx-1);
2859 Ops.push_back(OuterMul);
2860 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2861 }
2862 }
2863 }
2864 }
2865
2866 // If there are any add recurrences in the operands list, see if any other
2867 // added values are loop invariant. If so, we can fold them into the
2868 // recurrence.
2869 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2870 ++Idx;
2871
2872 // Scan over all recurrences, trying to fold loop invariants into them.
2873 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2874 // Scan all of the other operands to this add and add them to the vector if
2875 // they are loop invariant w.r.t. the recurrence.
2877 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2878 const Loop *AddRecLoop = AddRec->getLoop();
2879 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2880 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2881 LIOps.push_back(Ops[i]);
2882 Ops.erase(Ops.begin()+i);
2883 --i; --e;
2884 }
2885
2886 // If we found some loop invariants, fold them into the recurrence.
2887 if (!LIOps.empty()) {
2888 // Compute nowrap flags for the addition of the loop-invariant ops and
2889 // the addrec. Temporarily push it as an operand for that purpose. These
2890 // flags are valid in the scope of the addrec only.
2891 LIOps.push_back(AddRec);
2892 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2893 LIOps.pop_back();
2894
2895 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2896 LIOps.push_back(AddRec->getStart());
2897
2898 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2899
2900 // It is not in general safe to propagate flags valid on an add within
2901 // the addrec scope to one outside it. We must prove that the inner
2902 // scope is guaranteed to execute if the outer one does to be able to
2903 // safely propagate. We know the program is undefined if poison is
2904 // produced on the inner scoped addrec. We also know that *for this use*
2905 // the outer scoped add can't overflow (because of the flags we just
2906 // computed for the inner scoped add) without the program being undefined.
2907 // Proving that entry to the outer scope neccesitates entry to the inner
2908 // scope, thus proves the program undefined if the flags would be violated
2909 // in the outer scope.
2910 SCEV::NoWrapFlags AddFlags = Flags;
2911 if (AddFlags != SCEV::FlagAnyWrap) {
2912 auto *DefI = getDefiningScopeBound(LIOps);
2913 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2914 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2915 AddFlags = SCEV::FlagAnyWrap;
2916 }
2917 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2918
2919 // Build the new addrec. Propagate the NUW and NSW flags if both the
2920 // outer add and the inner addrec are guaranteed to have no overflow.
2921 // Always propagate NW.
2922 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2923 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2924
2925 // If all of the other operands were loop invariant, we are done.
2926 if (Ops.size() == 1) return NewRec;
2927
2928 // Otherwise, add the folded AddRec by the non-invariant parts.
2929 for (unsigned i = 0;; ++i)
2930 if (Ops[i] == AddRec) {
2931 Ops[i] = NewRec;
2932 break;
2933 }
2934 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2935 }
2936
2937 // Okay, if there weren't any loop invariants to be folded, check to see if
2938 // there are multiple AddRec's with the same loop induction variable being
2939 // added together. If so, we can fold them.
2940 for (unsigned OtherIdx = Idx+1;
2941 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2942 ++OtherIdx) {
2943 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2944 // so that the 1st found AddRecExpr is dominated by all others.
2945 assert(DT.dominates(
2946 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2947 AddRec->getLoop()->getHeader()) &&
2948 "AddRecExprs are not sorted in reverse dominance order?");
2949 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2950 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2951 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2952 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2953 ++OtherIdx) {
2954 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2955 if (OtherAddRec->getLoop() == AddRecLoop) {
2956 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2957 i != e; ++i) {
2958 if (i >= AddRecOps.size()) {
2959 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2960 break;
2961 }
2963 AddRecOps[i], OtherAddRec->getOperand(i)};
2964 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2965 }
2966 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2967 }
2968 }
2969 // Step size has changed, so we cannot guarantee no self-wraparound.
2970 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2971 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2972 }
2973 }
2974
2975 // Otherwise couldn't fold anything into this recurrence. Move onto the
2976 // next one.
2977 }
2978
2979 // Okay, it looks like we really DO need an add expr. Check to see if we
2980 // already have one, otherwise create a new one.
2981 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2982}
2983
2984const SCEV *
2985ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2986 SCEV::NoWrapFlags Flags) {
2988 ID.AddInteger(scAddExpr);
2989 for (const SCEV *Op : Ops)
2990 ID.AddPointer(Op);
2991 void *IP = nullptr;
2992 SCEVAddExpr *S =
2993 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2994 if (!S) {
2995 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2996 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2997 S = new (SCEVAllocator)
2998 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2999 UniqueSCEVs.InsertNode(S, IP);
3000 registerUser(S, Ops);
3001 }
3002 S->setNoWrapFlags(Flags);
3003 return S;
3004}
3005
3006const SCEV *
3007ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
3008 const Loop *L, SCEV::NoWrapFlags Flags) {
3010 ID.AddInteger(scAddRecExpr);
3011 for (const SCEV *Op : Ops)
3012 ID.AddPointer(Op);
3013 ID.AddPointer(L);
3014 void *IP = nullptr;
3015 SCEVAddRecExpr *S =
3016 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3017 if (!S) {
3018 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3019 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3020 S = new (SCEVAllocator)
3021 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3022 UniqueSCEVs.InsertNode(S, IP);
3023 LoopUsers[L].push_back(S);
3024 registerUser(S, Ops);
3025 }
3026 setNoWrapFlags(S, Flags);
3027 return S;
3028}
3029
3030const SCEV *
3031ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
3032 SCEV::NoWrapFlags Flags) {
3034 ID.AddInteger(scMulExpr);
3035 for (const SCEV *Op : Ops)
3036 ID.AddPointer(Op);
3037 void *IP = nullptr;
3038 SCEVMulExpr *S =
3039 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3040 if (!S) {
3041 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3042 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3043 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3044 O, Ops.size());
3045 UniqueSCEVs.InsertNode(S, IP);
3046 registerUser(S, Ops);
3047 }
3048 S->setNoWrapFlags(Flags);
3049 return S;
3050}
3051
3052static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3053 uint64_t k = i*j;
3054 if (j > 1 && k / j != i) Overflow = true;
3055 return k;
3056}
3057
3058/// Compute the result of "n choose k", the binomial coefficient. If an
3059/// intermediate computation overflows, Overflow will be set and the return will
3060/// be garbage. Overflow is not cleared on absence of overflow.
3061static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3062 // We use the multiplicative formula:
3063 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3064 // At each iteration, we take the n-th term of the numeral and divide by the
3065 // (k-n)th term of the denominator. This division will always produce an
3066 // integral result, and helps reduce the chance of overflow in the
3067 // intermediate computations. However, we can still overflow even when the
3068 // final result would fit.
3069
3070 if (n == 0 || n == k) return 1;
3071 if (k > n) return 0;
3072
3073 if (k > n/2)
3074 k = n-k;
3075
3076 uint64_t r = 1;
3077 for (uint64_t i = 1; i <= k; ++i) {
3078 r = umul_ov(r, n-(i-1), Overflow);
3079 r /= i;
3080 }
3081 return r;
3082}
3083
3084/// Determine if any of the operands in this SCEV are a constant or if
3085/// any of the add or multiply expressions in this SCEV contain a constant.
3086static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3087 struct FindConstantInAddMulChain {
3088 bool FoundConstant = false;
3089
3090 bool follow(const SCEV *S) {
3091 FoundConstant |= isa<SCEVConstant>(S);
3092 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3093 }
3094
3095 bool isDone() const {
3096 return FoundConstant;
3097 }
3098 };
3099
3100 FindConstantInAddMulChain F;
3102 ST.visitAll(StartExpr);
3103 return F.FoundConstant;
3104}
3105
3106/// Get a canonical multiply expression, or something simpler if possible.
3108 SCEV::NoWrapFlags OrigFlags,
3109 unsigned Depth) {
3110 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3111 "only nuw or nsw allowed");
3112 assert(!Ops.empty() && "Cannot get empty mul!");
3113 if (Ops.size() == 1) return Ops[0];
3114#ifndef NDEBUG
3115 Type *ETy = Ops[0]->getType();
3116 assert(!ETy->isPointerTy());
3117 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3118 assert(Ops[i]->getType() == ETy &&
3119 "SCEVMulExpr operand types don't match!");
3120#endif
3121
3122 // Sort by complexity, this groups all similar expression types together.
3123 GroupByComplexity(Ops, &LI, DT);
3124
3125 // If there are any constants, fold them together.
3126 unsigned Idx = 0;
3127 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3128 ++Idx;
3129 assert(Idx < Ops.size());
3130 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3131 // We found two constants, fold them together!
3132 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3133 if (Ops.size() == 2) return Ops[0];
3134 Ops.erase(Ops.begin()+1); // Erase the folded element
3135 LHSC = cast<SCEVConstant>(Ops[0]);
3136 }
3137
3138 // If we have a multiply of zero, it will always be zero.
3139 if (LHSC->getValue()->isZero())
3140 return LHSC;
3141
3142 // If we are left with a constant one being multiplied, strip it off.
3143 if (LHSC->getValue()->isOne()) {
3144 Ops.erase(Ops.begin());
3145 --Idx;
3146 }
3147
3148 if (Ops.size() == 1)
3149 return Ops[0];
3150 }
3151
3152 // Delay expensive flag strengthening until necessary.
3153 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3154 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3155 };
3156
3157 // Limit recursion calls depth.
3159 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3160
3161 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3162 // Don't strengthen flags if we have no new information.
3163 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3164 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3165 Mul->setNoWrapFlags(ComputeFlags(Ops));
3166 return S;
3167 }
3168
3169 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3170 if (Ops.size() == 2) {
3171 // C1*(C2+V) -> C1*C2 + C1*V
3172 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3173 // If any of Add's ops are Adds or Muls with a constant, apply this
3174 // transformation as well.
3175 //
3176 // TODO: There are some cases where this transformation is not
3177 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3178 // this transformation should be narrowed down.
3179 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) {
3180 const SCEV *LHS = getMulExpr(LHSC, Add->getOperand(0),
3182 const SCEV *RHS = getMulExpr(LHSC, Add->getOperand(1),
3184 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3185 }
3186
3187 if (Ops[0]->isAllOnesValue()) {
3188 // If we have a mul by -1 of an add, try distributing the -1 among the
3189 // add operands.
3190 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3192 bool AnyFolded = false;
3193 for (const SCEV *AddOp : Add->operands()) {
3194 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3195 Depth + 1);
3196 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3197 NewOps.push_back(Mul);
3198 }
3199 if (AnyFolded)
3200 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3201 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3202 // Negation preserves a recurrence's no self-wrap property.
3204 for (const SCEV *AddRecOp : AddRec->operands())
3205 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3206 Depth + 1));
3207 // Let M be the minimum representable signed value. AddRec with nsw
3208 // multiplied by -1 can have signed overflow if and only if it takes a
3209 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3210 // maximum signed value. In all other cases signed overflow is
3211 // impossible.
3212 auto FlagsMask = SCEV::FlagNW;
3213 if (hasFlags(AddRec->getNoWrapFlags(), SCEV::FlagNSW)) {
3214 auto MinInt =
3215 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3216 if (getSignedRangeMin(AddRec) != MinInt)
3217 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3218 }
3219 return getAddRecExpr(Operands, AddRec->getLoop(),
3220 AddRec->getNoWrapFlags(FlagsMask));
3221 }
3222 }
3223 }
3224 }
3225
3226 // Skip over the add expression until we get to a multiply.
3227 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3228 ++Idx;
3229
3230 // If there are mul operands inline them all into this expression.
3231 if (Idx < Ops.size()) {
3232 bool DeletedMul = false;
3233 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3234 if (Ops.size() > MulOpsInlineThreshold)
3235 break;
3236 // If we have an mul, expand the mul operands onto the end of the
3237 // operands list.
3238 Ops.erase(Ops.begin()+Idx);
3239 append_range(Ops, Mul->operands());
3240 DeletedMul = true;
3241 }
3242
3243 // If we deleted at least one mul, we added operands to the end of the
3244 // list, and they are not necessarily sorted. Recurse to resort and
3245 // resimplify any operands we just acquired.
3246 if (DeletedMul)
3247 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3248 }
3249
3250 // If there are any add recurrences in the operands list, see if any other
3251 // added values are loop invariant. If so, we can fold them into the
3252 // recurrence.
3253 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3254 ++Idx;
3255
3256 // Scan over all recurrences, trying to fold loop invariants into them.
3257 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3258 // Scan all of the other operands to this mul and add them to the vector
3259 // if they are loop invariant w.r.t. the recurrence.
3261 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3262 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3263 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3264 LIOps.push_back(Ops[i]);
3265 Ops.erase(Ops.begin()+i);
3266 --i; --e;
3267 }
3268
3269 // If we found some loop invariants, fold them into the recurrence.
3270 if (!LIOps.empty()) {
3271 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3273 NewOps.reserve(AddRec->getNumOperands());
3274 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3275
3276 // If both the mul and addrec are nuw, we can preserve nuw.
3277 // If both the mul and addrec are nsw, we can only preserve nsw if either
3278 // a) they are also nuw, or
3279 // b) all multiplications of addrec operands with scale are nsw.
3280 SCEV::NoWrapFlags Flags =
3281 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3282
3283 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3284 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3285 SCEV::FlagAnyWrap, Depth + 1));
3286
3287 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3289 Instruction::Mul, getSignedRange(Scale),
3291 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3292 Flags = clearFlags(Flags, SCEV::FlagNSW);
3293 }
3294 }
3295
3296 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3297
3298 // If all of the other operands were loop invariant, we are done.
3299 if (Ops.size() == 1) return NewRec;
3300
3301 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3302 for (unsigned i = 0;; ++i)
3303 if (Ops[i] == AddRec) {
3304 Ops[i] = NewRec;
3305 break;
3306 }
3307 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3308 }
3309
3310 // Okay, if there weren't any loop invariants to be folded, check to see
3311 // if there are multiple AddRec's with the same loop induction variable
3312 // being multiplied together. If so, we can fold them.
3313
3314 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3315 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3316 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3317 // ]]],+,...up to x=2n}.
3318 // Note that the arguments to choose() are always integers with values
3319 // known at compile time, never SCEV objects.
3320 //
3321 // The implementation avoids pointless extra computations when the two
3322 // addrec's are of different length (mathematically, it's equivalent to
3323 // an infinite stream of zeros on the right).
3324 bool OpsModified = false;
3325 for (unsigned OtherIdx = Idx+1;
3326 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3327 ++OtherIdx) {
3328 const SCEVAddRecExpr *OtherAddRec =
3329 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3330 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3331 continue;
3332
3333 // Limit max number of arguments to avoid creation of unreasonably big
3334 // SCEVAddRecs with very complex operands.
3335 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3336 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3337 continue;
3338
3339 bool Overflow = false;
3340 Type *Ty = AddRec->getType();
3341 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3343 for (int x = 0, xe = AddRec->getNumOperands() +
3344 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3345 SmallVector <const SCEV *, 7> SumOps;
3346 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3347 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3348 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3349 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3350 z < ze && !Overflow; ++z) {
3351 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3352 uint64_t Coeff;
3353 if (LargerThan64Bits)
3354 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3355 else
3356 Coeff = Coeff1*Coeff2;
3357 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3358 const SCEV *Term1 = AddRec->getOperand(y-z);
3359 const SCEV *Term2 = OtherAddRec->getOperand(z);
3360 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3361 SCEV::FlagAnyWrap, Depth + 1));
3362 }
3363 }
3364 if (SumOps.empty())
3365 SumOps.push_back(getZero(Ty));
3366 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3367 }
3368 if (!Overflow) {
3369 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3371 if (Ops.size() == 2) return NewAddRec;
3372 Ops[Idx] = NewAddRec;
3373 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3374 OpsModified = true;
3375 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3376 if (!AddRec)
3377 break;
3378 }
3379 }
3380 if (OpsModified)
3381 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3382
3383 // Otherwise couldn't fold anything into this recurrence. Move onto the
3384 // next one.
3385 }
3386
3387 // Okay, it looks like we really DO need an mul expr. Check to see if we
3388 // already have one, otherwise create a new one.
3389 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3390}
3391
3392/// Represents an unsigned remainder expression based on unsigned division.
3394 const SCEV *RHS) {
3397 "SCEVURemExpr operand types don't match!");
3398
3399 // Short-circuit easy cases
3400 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3401 // If constant is one, the result is trivial
3402 if (RHSC->getValue()->isOne())
3403 return getZero(LHS->getType()); // X urem 1 --> 0
3404
3405 // If constant is a power of two, fold into a zext(trunc(LHS)).
3406 if (RHSC->getAPInt().isPowerOf2()) {
3407 Type *FullTy = LHS->getType();
3408 Type *TruncTy =
3409 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3410 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3411 }
3412 }
3413
3414 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3415 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3416 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3417 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3418}
3419
3420/// Get a canonical unsigned division expression, or something simpler if
3421/// possible.
3423 const SCEV *RHS) {
3424 assert(!LHS->getType()->isPointerTy() &&
3425 "SCEVUDivExpr operand can't be pointer!");
3426 assert(LHS->getType() == RHS->getType() &&
3427 "SCEVUDivExpr operand types don't match!");
3428
3430 ID.AddInteger(scUDivExpr);
3431 ID.AddPointer(LHS);
3432 ID.AddPointer(RHS);
3433 void *IP = nullptr;
3434 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3435 return S;
3436
3437 // 0 udiv Y == 0
3438 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3439 if (LHSC->getValue()->isZero())
3440 return LHS;
3441
3442 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3443 if (RHSC->getValue()->isOne())
3444 return LHS; // X udiv 1 --> x
3445 // If the denominator is zero, the result of the udiv is undefined. Don't
3446 // try to analyze it, because the resolution chosen here may differ from
3447 // the resolution chosen in other parts of the compiler.
3448 if (!RHSC->getValue()->isZero()) {
3449 // Determine if the division can be folded into the operands of
3450 // its operands.
3451 // TODO: Generalize this to non-constants by using known-bits information.
3452 Type *Ty = LHS->getType();
3453 unsigned LZ = RHSC->getAPInt().countl_zero();
3454 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3455 // For non-power-of-two values, effectively round the value up to the
3456 // nearest power of two.
3457 if (!RHSC->getAPInt().isPowerOf2())
3458 ++MaxShiftAmt;
3459 IntegerType *ExtTy =
3460 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3461 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3462 if (const SCEVConstant *Step =
3463 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3464 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3465 const APInt &StepInt = Step->getAPInt();
3466 const APInt &DivInt = RHSC->getAPInt();
3467 if (!StepInt.urem(DivInt) &&
3468 getZeroExtendExpr(AR, ExtTy) ==
3469 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3470 getZeroExtendExpr(Step, ExtTy),
3471 AR->getLoop(), SCEV::FlagAnyWrap)) {
3473 for (const SCEV *Op : AR->operands())
3474 Operands.push_back(getUDivExpr(Op, RHS));
3475 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3476 }
3477 /// Get a canonical UDivExpr for a recurrence.
3478 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3479 // We can currently only fold X%N if X is constant.
3480 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3481 if (StartC && !DivInt.urem(StepInt) &&
3482 getZeroExtendExpr(AR, ExtTy) ==
3483 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3484 getZeroExtendExpr(Step, ExtTy),
3485 AR->getLoop(), SCEV::FlagAnyWrap)) {
3486 const APInt &StartInt = StartC->getAPInt();
3487 const APInt &StartRem = StartInt.urem(StepInt);
3488 if (StartRem != 0) {
3489 const SCEV *NewLHS =
3490 getAddRecExpr(getConstant(StartInt - StartRem), Step,
3491 AR->getLoop(), SCEV::FlagNW);
3492 if (LHS != NewLHS) {
3493 LHS = NewLHS;
3494
3495 // Reset the ID to include the new LHS, and check if it is
3496 // already cached.
3497 ID.clear();
3498 ID.AddInteger(scUDivExpr);
3499 ID.AddPointer(LHS);
3500 ID.AddPointer(RHS);
3501 IP = nullptr;
3502 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3503 return S;
3504 }
3505 }
3506 }
3507 }
3508 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3509 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3511 for (const SCEV *Op : M->operands())
3512 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3513 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3514 // Find an operand that's safely divisible.
3515 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3516 const SCEV *Op = M->getOperand(i);
3517 const SCEV *Div = getUDivExpr(Op, RHSC);
3518 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3519 Operands = SmallVector<const SCEV *, 4>(M->operands());
3520 Operands[i] = Div;
3521 return getMulExpr(Operands);
3522 }
3523 }
3524 }
3525
3526 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3527 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3528 if (auto *DivisorConstant =
3529 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3530 bool Overflow = false;
3531 APInt NewRHS =
3532 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3533 if (Overflow) {
3534 return getConstant(RHSC->getType(), 0, false);
3535 }
3536 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3537 }
3538 }
3539
3540 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3541 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3543 for (const SCEV *Op : A->operands())
3544 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3545 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3546 Operands.clear();
3547 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3548 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3549 if (isa<SCEVUDivExpr>(Op) ||
3550 getMulExpr(Op, RHS) != A->getOperand(i))
3551 break;
3552 Operands.push_back(Op);
3553 }
3554 if (Operands.size() == A->getNumOperands())
3555 return getAddExpr(Operands);
3556 }
3557 }
3558
3559 // Fold if both operands are constant.
3560 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3561 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3562 }
3563 }
3564
3565 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3566 // changes). Make sure we get a new one.
3567 IP = nullptr;
3568 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3569 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3570 LHS, RHS);
3571 UniqueSCEVs.InsertNode(S, IP);
3572 registerUser(S, {LHS, RHS});
3573 return S;
3574}
3575
3576APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3577 APInt A = C1->getAPInt().abs();
3578 APInt B = C2->getAPInt().abs();
3579 uint32_t ABW = A.getBitWidth();
3580 uint32_t BBW = B.getBitWidth();
3581
3582 if (ABW > BBW)
3583 B = B.zext(ABW);
3584 else if (ABW < BBW)
3585 A = A.zext(BBW);
3586
3587 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3588}
3589
3590/// Get a canonical unsigned division expression, or something simpler if
3591/// possible. There is no representation for an exact udiv in SCEV IR, but we
3592/// can attempt to remove factors from the LHS and RHS. We can't do this when
3593/// it's not exact because the udiv may be clearing bits.
3595 const SCEV *RHS) {
3596 // TODO: we could try to find factors in all sorts of things, but for now we
3597 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3598 // end of this file for inspiration.
3599
3600 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3601 if (!Mul || !Mul->hasNoUnsignedWrap())
3602 return getUDivExpr(LHS, RHS);
3603
3604 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3605 // If the mulexpr multiplies by a constant, then that constant must be the
3606 // first element of the mulexpr.
3607 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3608 if (LHSCst == RHSCst) {
3610 return getMulExpr(Operands);
3611 }
3612
3613 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3614 // that there's a factor provided by one of the other terms. We need to
3615 // check.
3616 APInt Factor = gcd(LHSCst, RHSCst);
3617 if (!Factor.isIntN(1)) {
3618 LHSCst =
3619 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3620 RHSCst =
3621 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3623 Operands.push_back(LHSCst);
3624 append_range(Operands, Mul->operands().drop_front());
3626 RHS = RHSCst;
3627 Mul = dyn_cast<SCEVMulExpr>(LHS);
3628 if (!Mul)
3629 return getUDivExactExpr(LHS, RHS);
3630 }
3631 }
3632 }
3633
3634 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3635 if (Mul->getOperand(i) == RHS) {
3637 append_range(Operands, Mul->operands().take_front(i));
3638 append_range(Operands, Mul->operands().drop_front(i + 1));
3639 return getMulExpr(Operands);
3640 }
3641 }
3642
3643 return getUDivExpr(LHS, RHS);
3644}
3645
3646/// Get an add recurrence expression for the specified loop. Simplify the
3647/// expression as much as possible.
3648const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3649 const Loop *L,
3650 SCEV::NoWrapFlags Flags) {
3652 Operands.push_back(Start);
3653 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3654 if (StepChrec->getLoop() == L) {
3655 append_range(Operands, StepChrec->operands());
3656 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3657 }
3658
3659 Operands.push_back(Step);
3660 return getAddRecExpr(Operands, L, Flags);
3661}
3662
3663/// Get an add recurrence expression for the specified loop. Simplify the
3664/// expression as much as possible.
3665const SCEV *
3667 const Loop *L, SCEV::NoWrapFlags Flags) {
3668 if (Operands.size() == 1) return Operands[0];
3669#ifndef NDEBUG
3671 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3672 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3673 "SCEVAddRecExpr operand types don't match!");
3674 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3675 }
3676 for (const SCEV *Op : Operands)
3678 "SCEVAddRecExpr operand is not available at loop entry!");
3679#endif
3680
3681 if (Operands.back()->isZero()) {
3682 Operands.pop_back();
3683 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3684 }
3685
3686 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3687 // use that information to infer NUW and NSW flags. However, computing a
3688 // BE count requires calling getAddRecExpr, so we may not yet have a
3689 // meaningful BE count at this point (and if we don't, we'd be stuck
3690 // with a SCEVCouldNotCompute as the cached BE count).
3691
3692 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3693
3694 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3695 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3696 const Loop *NestedLoop = NestedAR->getLoop();
3697 if (L->contains(NestedLoop)
3698 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3699 : (!NestedLoop->contains(L) &&
3700 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3701 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3702 Operands[0] = NestedAR->getStart();
3703 // AddRecs require their operands be loop-invariant with respect to their
3704 // loops. Don't perform this transformation if it would break this
3705 // requirement.
3706 bool AllInvariant = all_of(
3707 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3708
3709 if (AllInvariant) {
3710 // Create a recurrence for the outer loop with the same step size.
3711 //
3712 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3713 // inner recurrence has the same property.
3714 SCEV::NoWrapFlags OuterFlags =
3715 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3716
3717 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3718 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3719 return isLoopInvariant(Op, NestedLoop);
3720 });
3721
3722 if (AllInvariant) {
3723 // Ok, both add recurrences are valid after the transformation.
3724 //
3725 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3726 // the outer recurrence has the same property.
3727 SCEV::NoWrapFlags InnerFlags =
3728 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3729 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3730 }
3731 }
3732 // Reset Operands to its original state.
3733 Operands[0] = NestedAR;
3734 }
3735 }
3736
3737 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3738 // already have one, otherwise create a new one.
3739 return getOrCreateAddRecExpr(Operands, L, Flags);
3740}
3741
3742const SCEV *
3744 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3745 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3746 // getSCEV(Base)->getType() has the same address space as Base->getType()
3747 // because SCEV::getType() preserves the address space.
3748 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3749 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3750 if (NW != GEPNoWrapFlags::none()) {
3751 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3752 // but to do that, we have to ensure that said flag is valid in the entire
3753 // defined scope of the SCEV.
3754 // TODO: non-instructions have global scope. We might be able to prove
3755 // some global scope cases
3756 auto *GEPI = dyn_cast<Instruction>(GEP);
3757 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3758 NW = GEPNoWrapFlags::none();
3759 }
3760
3762 if (NW.hasNoUnsignedSignedWrap())
3763 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3764 if (NW.hasNoUnsignedWrap())
3765 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3766
3767 Type *CurTy = GEP->getType();
3768 bool FirstIter = true;
3770 for (const SCEV *IndexExpr : IndexExprs) {
3771 // Compute the (potentially symbolic) offset in bytes for this index.
3772 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3773 // For a struct, add the member offset.
3774 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3775 unsigned FieldNo = Index->getZExtValue();
3776 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3777 Offsets.push_back(FieldOffset);
3778
3779 // Update CurTy to the type of the field at Index.
3780 CurTy = STy->getTypeAtIndex(Index);
3781 } else {
3782 // Update CurTy to its element type.
3783 if (FirstIter) {
3784 assert(isa<PointerType>(CurTy) &&
3785 "The first index of a GEP indexes a pointer");
3786 CurTy = GEP->getSourceElementType();
3787 FirstIter = false;
3788 } else {
3790 }
3791 // For an array, add the element offset, explicitly scaled.
3792 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3793 // Getelementptr indices are signed.
3794 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3795
3796 // Multiply the index by the element size to compute the element offset.
3797 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3798 Offsets.push_back(LocalOffset);
3799 }
3800 }
3801
3802 // Handle degenerate case of GEP without offsets.
3803 if (Offsets.empty())
3804 return BaseExpr;
3805
3806 // Add the offsets together, assuming nsw if inbounds.
3807 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3808 // Add the base address and the offset. We cannot use the nsw flag, as the
3809 // base address is unsigned. However, if we know that the offset is
3810 // non-negative, we can use nuw.
3811 bool NUW = NW.hasNoUnsignedWrap() ||
3814 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3815 assert(BaseExpr->getType() == GEPExpr->getType() &&
3816 "GEP should not change type mid-flight.");
3817 return GEPExpr;
3818}
3819
3820SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3823 ID.AddInteger(SCEVType);
3824 for (const SCEV *Op : Ops)
3825 ID.AddPointer(Op);
3826 void *IP = nullptr;
3827 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3828}
3829
3830const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3832 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3833}
3834
3837 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3838 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3839 if (Ops.size() == 1) return Ops[0];
3840#ifndef NDEBUG
3841 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3842 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3843 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3844 "Operand types don't match!");
3845 assert(Ops[0]->getType()->isPointerTy() ==
3846 Ops[i]->getType()->isPointerTy() &&
3847 "min/max should be consistently pointerish");
3848 }
3849#endif
3850
3851 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3852 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3853
3854 // Sort by complexity, this groups all similar expression types together.
3855 GroupByComplexity(Ops, &LI, DT);
3856
3857 // Check if we have created the same expression before.
3858 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3859 return S;
3860 }
3861
3862 // If there are any constants, fold them together.
3863 unsigned Idx = 0;
3864 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3865 ++Idx;
3866 assert(Idx < Ops.size());
3867 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3868 switch (Kind) {
3869 case scSMaxExpr:
3870 return APIntOps::smax(LHS, RHS);
3871 case scSMinExpr:
3872 return APIntOps::smin(LHS, RHS);
3873 case scUMaxExpr:
3874 return APIntOps::umax(LHS, RHS);
3875 case scUMinExpr:
3876 return APIntOps::umin(LHS, RHS);
3877 default:
3878 llvm_unreachable("Unknown SCEV min/max opcode");
3879 }
3880 };
3881
3882 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3883 // We found two constants, fold them together!
3884 ConstantInt *Fold = ConstantInt::get(
3885 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3886 Ops[0] = getConstant(Fold);
3887 Ops.erase(Ops.begin()+1); // Erase the folded element
3888 if (Ops.size() == 1) return Ops[0];
3889 LHSC = cast<SCEVConstant>(Ops[0]);
3890 }
3891
3892 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3893 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3894
3895 if (IsMax ? IsMinV : IsMaxV) {
3896 // If we are left with a constant minimum(/maximum)-int, strip it off.
3897 Ops.erase(Ops.begin());
3898 --Idx;
3899 } else if (IsMax ? IsMaxV : IsMinV) {
3900 // If we have a max(/min) with a constant maximum(/minimum)-int,
3901 // it will always be the extremum.
3902 return LHSC;
3903 }
3904
3905 if (Ops.size() == 1) return Ops[0];
3906 }
3907
3908 // Find the first operation of the same kind
3909 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3910 ++Idx;
3911
3912 // Check to see if one of the operands is of the same kind. If so, expand its
3913 // operands onto our operand list, and recurse to simplify.
3914 if (Idx < Ops.size()) {
3915 bool DeletedAny = false;
3916 while (Ops[Idx]->getSCEVType() == Kind) {
3917 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3918 Ops.erase(Ops.begin()+Idx);
3919 append_range(Ops, SMME->operands());
3920 DeletedAny = true;
3921 }
3922
3923 if (DeletedAny)
3924 return getMinMaxExpr(Kind, Ops);
3925 }
3926
3927 // Okay, check to see if the same value occurs in the operand list twice. If
3928 // so, delete one. Since we sorted the list, these values are required to
3929 // be adjacent.
3934 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3935 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3936 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3937 if (Ops[i] == Ops[i + 1] ||
3938 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3939 // X op Y op Y --> X op Y
3940 // X op Y --> X, if we know X, Y are ordered appropriately
3941 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3942 --i;
3943 --e;
3944 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3945 Ops[i + 1])) {
3946 // X op Y --> Y, if we know X, Y are ordered appropriately
3947 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3948 --i;
3949 --e;
3950 }
3951 }
3952
3953 if (Ops.size() == 1) return Ops[0];
3954
3955 assert(!Ops.empty() && "Reduced smax down to nothing!");
3956
3957 // Okay, it looks like we really DO need an expr. Check to see if we
3958 // already have one, otherwise create a new one.
3960 ID.AddInteger(Kind);
3961 for (const SCEV *Op : Ops)
3962 ID.AddPointer(Op);
3963 void *IP = nullptr;
3964 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3965 if (ExistingSCEV)
3966 return ExistingSCEV;
3967 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3968 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3969 SCEV *S = new (SCEVAllocator)
3970 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3971
3972 UniqueSCEVs.InsertNode(S, IP);
3973 registerUser(S, Ops);
3974 return S;
3975}
3976
3977namespace {
3978
3979class SCEVSequentialMinMaxDeduplicatingVisitor final
3980 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3981 std::optional<const SCEV *>> {
3982 using RetVal = std::optional<const SCEV *>;
3984
3985 ScalarEvolution &SE;
3986 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3987 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3989
3990 bool canRecurseInto(SCEVTypes Kind) const {
3991 // We can only recurse into the SCEV expression of the same effective type
3992 // as the type of our root SCEV expression.
3993 return RootKind == Kind || NonSequentialRootKind == Kind;
3994 };
3995
3996 RetVal visitAnyMinMaxExpr(const SCEV *S) {
3997 assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
3998 "Only for min/max expressions.");
3999 SCEVTypes Kind = S->getSCEVType();
4000
4001 if (!canRecurseInto(Kind))
4002 return S;
4003
4004 auto *NAry = cast<SCEVNAryExpr>(S);
4006 bool Changed = visit(Kind, NAry->operands(), NewOps);
4007
4008 if (!Changed)
4009 return S;
4010 if (NewOps.empty())
4011 return std::nullopt;
4012
4013 return isa<SCEVSequentialMinMaxExpr>(S)
4014 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4015 : SE.getMinMaxExpr(Kind, NewOps);
4016 }
4017
4018 RetVal visit(const SCEV *S) {
4019 // Has the whole operand been seen already?
4020 if (!SeenOps.insert(S).second)
4021 return std::nullopt;
4022 return Base::visit(S);
4023 }
4024
4025public:
4026 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4027 SCEVTypes RootKind)
4028 : SE(SE), RootKind(RootKind),
4029 NonSequentialRootKind(
4030 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4031 RootKind)) {}
4032
4033 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
4035 bool Changed = false;
4037 Ops.reserve(OrigOps.size());
4038
4039 for (const SCEV *Op : OrigOps) {
4040 RetVal NewOp = visit(Op);
4041 if (NewOp != Op)
4042 Changed = true;
4043 if (NewOp)
4044 Ops.emplace_back(*NewOp);
4045 }
4046
4047 if (Changed)
4048 NewOps = std::move(Ops);
4049 return Changed;
4050 }
4051
4052 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4053
4054 RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4055
4056 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
4057
4058 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4059
4060 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4061
4062 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4063
4064 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4065
4066 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4067
4068 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4069
4070 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4071
4072 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4073 return visitAnyMinMaxExpr(Expr);
4074 }
4075
4076 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4077 return visitAnyMinMaxExpr(Expr);
4078 }
4079
4080 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4081 return visitAnyMinMaxExpr(Expr);
4082 }
4083
4084 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4085 return visitAnyMinMaxExpr(Expr);
4086 }
4087
4088 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4089 return visitAnyMinMaxExpr(Expr);
4090 }
4091
4092 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4093
4094 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4095};
4096
4097} // namespace
4098
4100 switch (Kind) {
4101 case scConstant:
4102 case scVScale:
4103 case scTruncate:
4104 case scZeroExtend:
4105 case scSignExtend:
4106 case scPtrToInt:
4107 case scAddExpr:
4108 case scMulExpr:
4109 case scUDivExpr:
4110 case scAddRecExpr:
4111 case scUMaxExpr:
4112 case scSMaxExpr:
4113 case scUMinExpr:
4114 case scSMinExpr:
4115 case scUnknown:
4116 // If any operand is poison, the whole expression is poison.
4117 return true;
4119 // FIXME: if the *first* operand is poison, the whole expression is poison.
4120 return false; // Pessimistically, say that it does not propagate poison.
4121 case scCouldNotCompute:
4122 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4123 }
4124 llvm_unreachable("Unknown SCEV kind!");
4125}
4126
4127namespace {
4128// The only way poison may be introduced in a SCEV expression is from a
4129// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4130// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4131// introduce poison -- they encode guaranteed, non-speculated knowledge.
4132//
4133// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4134// with the notable exception of umin_seq, where only poison from the first
4135// operand is (unconditionally) propagated.
4136struct SCEVPoisonCollector {
4137 bool LookThroughMaybePoisonBlocking;
4139 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4140 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4141
4142 bool follow(const SCEV *S) {
4143 if (!LookThroughMaybePoisonBlocking &&
4145 return false;
4146
4147 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4148 if (!isGuaranteedNotToBePoison(SU->getValue()))
4149 MaybePoison.insert(SU);
4150 }
4151 return true;
4152 }
4153 bool isDone() const { return false; }
4154};
4155} // namespace
4156
4157/// Return true if V is poison given that AssumedPoison is already poison.
4158static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4159 // First collect all SCEVs that might result in AssumedPoison to be poison.
4160 // We need to look through potentially poison-blocking operations here,
4161 // because we want to find all SCEVs that *might* result in poison, not only
4162 // those that are *required* to.
4163 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4164 visitAll(AssumedPoison, PC1);
4165
4166 // AssumedPoison is never poison. As the assumption is false, the implication
4167 // is true. Don't bother walking the other SCEV in this case.
4168 if (PC1.MaybePoison.empty())
4169 return true;
4170
4171 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4172 // as well. We cannot look through potentially poison-blocking operations
4173 // here, as their arguments only *may* make the result poison.
4174 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4175 visitAll(S, PC2);
4176
4177 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4178 // it will also make S poison by being part of PC2.MaybePoison.
4179 return all_of(PC1.MaybePoison, [&](const SCEVUnknown *S) {
4180 return PC2.MaybePoison.contains(S);
4181 });
4182}
4183
4185 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4186 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4187 visitAll(S, PC);
4188 for (const SCEVUnknown *SU : PC.MaybePoison)
4189 Result.insert(SU->getValue());
4190}
4191
4193 const SCEV *S, Instruction *I,
4194 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4195 // If the instruction cannot be poison, it's always safe to reuse.
4197 return true;
4198
4199 // Otherwise, it is possible that I is more poisonous that S. Collect the
4200 // poison-contributors of S, and then check whether I has any additional
4201 // poison-contributors. Poison that is contributed through poison-generating
4202 // flags is handled by dropping those flags instead.
4204 getPoisonGeneratingValues(PoisonVals, S);
4205
4206 SmallVector<Value *> Worklist;
4208 Worklist.push_back(I);
4209 while (!Worklist.empty()) {
4210 Value *V = Worklist.pop_back_val();
4211 if (!Visited.insert(V).second)
4212 continue;
4213
4214 // Avoid walking large instruction graphs.
4215 if (Visited.size() > 16)
4216 return false;
4217
4218 // Either the value can't be poison, or the S would also be poison if it
4219 // is.
4220 if (PoisonVals.contains(V) || isGuaranteedNotToBePoison(V))
4221 continue;
4222
4223 auto *I = dyn_cast<Instruction>(V);
4224 if (!I)
4225 return false;
4226
4227 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4228 // can't replace an arbitrary add with disjoint or, even if we drop the
4229 // flag. We would need to convert the or into an add.
4230 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4231 if (PDI->isDisjoint())
4232 return false;
4233
4234 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4235 // because SCEV currently assumes it can't be poison. Remove this special
4236 // case once we proper model when vscale can be poison.
4237 if (auto *II = dyn_cast<IntrinsicInst>(I);
4238 II && II->getIntrinsicID() == Intrinsic::vscale)
4239 continue;
4240
4241 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4242 return false;
4243
4244 // If the instruction can't create poison, we can recurse to its operands.
4245 if (I->hasPoisonGeneratingAnnotations())
4246 DropPoisonGeneratingInsts.push_back(I);
4247
4248 for (Value *Op : I->operands())
4249 Worklist.push_back(Op);
4250 }
4251 return true;
4252}
4253
4254const SCEV *
4257 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4258 "Not a SCEVSequentialMinMaxExpr!");
4259 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4260 if (Ops.size() == 1)
4261 return Ops[0];
4262#ifndef NDEBUG
4263 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4264 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4265 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4266 "Operand types don't match!");
4267 assert(Ops[0]->getType()->isPointerTy() ==
4268 Ops[i]->getType()->isPointerTy() &&
4269 "min/max should be consistently pointerish");
4270 }
4271#endif
4272
4273 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4274 // so we can *NOT* do any kind of sorting of the expressions!
4275
4276 // Check if we have created the same expression before.
4277 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4278 return S;
4279
4280 // FIXME: there are *some* simplifications that we can do here.
4281
4282 // Keep only the first instance of an operand.
4283 {
4284 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4285 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4286 if (Changed)
4287 return getSequentialMinMaxExpr(Kind, Ops);
4288 }
4289
4290 // Check to see if one of the operands is of the same kind. If so, expand its
4291 // operands onto our operand list, and recurse to simplify.
4292 {
4293 unsigned Idx = 0;
4294 bool DeletedAny = false;
4295 while (Idx < Ops.size()) {
4296 if (Ops[Idx]->getSCEVType() != Kind) {
4297 ++Idx;
4298 continue;
4299 }
4300 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4301 Ops.erase(Ops.begin() + Idx);
4302 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4303 SMME->operands().end());
4304 DeletedAny = true;
4305 }
4306
4307 if (DeletedAny)
4308 return getSequentialMinMaxExpr(Kind, Ops);
4309 }
4310
4311 const SCEV *SaturationPoint;
4313 switch (Kind) {
4315 SaturationPoint = getZero(Ops[0]->getType());
4316 Pred = ICmpInst::ICMP_ULE;
4317 break;
4318 default:
4319 llvm_unreachable("Not a sequential min/max type.");
4320 }
4321
4322 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4323 // We can replace %x umin_seq %y with %x umin %y if either:
4324 // * %y being poison implies %x is also poison.
4325 // * %x cannot be the saturating value (e.g. zero for umin).
4326 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4327 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4328 SaturationPoint)) {
4329 SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]};
4330 Ops[i - 1] = getMinMaxExpr(
4332 SeqOps);
4333 Ops.erase(Ops.begin() + i);
4334 return getSequentialMinMaxExpr(Kind, Ops);
4335 }
4336 // Fold %x umin_seq %y to %x if %x ule %y.
4337 // TODO: We might be able to prove the predicate for a later operand.
4338 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4339 Ops.erase(Ops.begin() + i);
4340 return getSequentialMinMaxExpr(Kind, Ops);
4341 }
4342 }
4343
4344 // Okay, it looks like we really DO need an expr. Check to see if we
4345 // already have one, otherwise create a new one.
4347 ID.AddInteger(Kind);
4348 for (const SCEV *Op : Ops)
4349 ID.AddPointer(Op);
4350 void *IP = nullptr;
4351 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4352 if (ExistingSCEV)
4353 return ExistingSCEV;
4354
4355 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4356 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4357 SCEV *S = new (SCEVAllocator)
4358 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4359
4360 UniqueSCEVs.InsertNode(S, IP);
4361 registerUser(S, Ops);
4362 return S;
4363}
4364
4365const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4367 return getSMaxExpr(Ops);
4368}
4369
4371 return getMinMaxExpr(scSMaxExpr, Ops);
4372}
4373
4374const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4376 return getUMaxExpr(Ops);
4377}
4378
4380 return getMinMaxExpr(scUMaxExpr, Ops);
4381}
4382
4384 const SCEV *RHS) {
4386 return getSMinExpr(Ops);
4387}
4388
4390 return getMinMaxExpr(scSMinExpr, Ops);
4391}
4392
4393const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4394 bool Sequential) {
4396 return getUMinExpr(Ops, Sequential);
4397}
4398
4400 bool Sequential) {
4401 return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4402 : getMinMaxExpr(scUMinExpr, Ops);
4403}
4404
4405const SCEV *
4407 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4408 if (Size.isScalable())
4409 Res = getMulExpr(Res, getVScale(IntTy));
4410 return Res;
4411}
4412
4414 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4415}
4416
4418 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4419}
4420
4422 StructType *STy,
4423 unsigned FieldNo) {
4424 // We can bypass creating a target-independent constant expression and then
4425 // folding it back into a ConstantInt. This is just a compile-time
4426 // optimization.
4427 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4428 assert(!SL->getSizeInBits().isScalable() &&
4429 "Cannot get offset for structure containing scalable vector types");
4430 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4431}
4432
4434 // Don't attempt to do anything other than create a SCEVUnknown object
4435 // here. createSCEV only calls getUnknown after checking for all other
4436 // interesting possibilities, and any other code that calls getUnknown
4437 // is doing so in order to hide a value from SCEV canonicalization.
4438
4440 ID.AddInteger(scUnknown);
4441 ID.AddPointer(V);
4442 void *IP = nullptr;
4443 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4444 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4445 "Stale SCEVUnknown in uniquing map!");
4446 return S;
4447 }
4448 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4449 FirstUnknown);
4450 FirstUnknown = cast<SCEVUnknown>(S);
4451 UniqueSCEVs.InsertNode(S, IP);
4452 return S;
4453}
4454
4455//===----------------------------------------------------------------------===//
4456// Basic SCEV Analysis and PHI Idiom Recognition Code
4457//
4458
4459/// Test if values of the given type are analyzable within the SCEV
4460/// framework. This primarily includes integer types, and it can optionally
4461/// include pointer types if the ScalarEvolution class has access to
4462/// target-specific information.
4464 // Integers and pointers are always SCEVable.
4465 return Ty->isIntOrPtrTy();
4466}
4467
4468/// Return the size in bits of the specified type, for which isSCEVable must
4469/// return true.
4471 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4472 if (Ty->isPointerTy())
4474 return getDataLayout().getTypeSizeInBits(Ty);
4475}
4476
4477/// Return a type with the same bitwidth as the given type and which represents
4478/// how SCEV will treat the given type, for which isSCEVable must return
4479/// true. For pointer types, this is the pointer index sized integer type.
4481 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4482
4483 if (Ty->isIntegerTy())
4484 return Ty;
4485
4486 // The only other support type is pointer.
4487 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4488 return getDataLayout().getIndexType(Ty);
4489}
4490
4492 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4493}
4494
4496 const SCEV *B) {
4497 /// For a valid use point to exist, the defining scope of one operand
4498 /// must dominate the other.
4499 bool PreciseA, PreciseB;
4500 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4501 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4502