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