LLVM  9.0.0svn
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/CallSite.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/IR/Verifier.h"
115 #include "llvm/Pass.h"
116 #include "llvm/Support/Casting.h"
118 #include "llvm/Support/Compiler.h"
119 #include "llvm/Support/Debug.h"
121 #include "llvm/Support/KnownBits.h"
124 #include <algorithm>
125 #include <cassert>
126 #include <climits>
127 #include <cstddef>
128 #include <cstdint>
129 #include <cstdlib>
130 #include <map>
131 #include <memory>
132 #include <tuple>
133 #include <utility>
134 #include <vector>
135 
136 using namespace llvm;
137 
138 #define DEBUG_TYPE "scalar-evolution"
139 
140 STATISTIC(NumArrayLenItCounts,
141  "Number of trip counts computed with array length");
142 STATISTIC(NumTripCountsComputed,
143  "Number of loops with predictable loop counts");
144 STATISTIC(NumTripCountsNotComputed,
145  "Number of loops without predictable loop counts");
146 STATISTIC(NumBruteForceTripCountsComputed,
147  "Number of loops with trip counts computed by force");
148 
149 static cl::opt<unsigned>
150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
151  cl::desc("Maximum number of iterations SCEV will "
152  "symbolically execute a constant "
153  "derived loop"),
154  cl::init(100));
155 
156 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
158  "verify-scev", cl::Hidden,
159  cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
160 static cl::opt<bool>
161  VerifySCEVMap("verify-scev-maps", cl::Hidden,
162  cl::desc("Verify no dangling value in ScalarEvolution's "
163  "ExprValueMap (slow)"));
164 
165 static cl::opt<bool> VerifyIR(
166  "scev-verify-ir", cl::Hidden,
167  cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
168  cl::init(false));
169 
171  "scev-mulops-inline-threshold", cl::Hidden,
172  cl::desc("Threshold for inlining multiplication operands into a SCEV"),
173  cl::init(32));
174 
176  "scev-addops-inline-threshold", cl::Hidden,
177  cl::desc("Threshold for inlining addition operands into a SCEV"),
178  cl::init(500));
179 
181  "scalar-evolution-max-scev-compare-depth", cl::Hidden,
182  cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
183  cl::init(32));
184 
186  "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
187  cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
188  cl::init(2));
189 
191  "scalar-evolution-max-value-compare-depth", cl::Hidden,
192  cl::desc("Maximum depth of recursive value complexity comparisons"),
193  cl::init(2));
194 
195 static cl::opt<unsigned>
196  MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
197  cl::desc("Maximum depth of recursive arithmetics"),
198  cl::init(32));
199 
201  "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
202  cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
203 
204 static cl::opt<unsigned>
205  MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
206  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
207  cl::init(8));
208 
209 static cl::opt<unsigned>
210  MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
211  cl::desc("Max coefficients in AddRec during evolving"),
212  cl::init(8));
213 
214 static cl::opt<unsigned>
215  HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
216  cl::desc("Size of the expression which is considered huge"),
217  cl::init(4096));
218 
219 //===----------------------------------------------------------------------===//
220 // SCEV class definitions
221 //===----------------------------------------------------------------------===//
222 
223 //===----------------------------------------------------------------------===//
224 // Implementation of the SCEV class.
225 //
226 
227 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
229  print(dbgs());
230  dbgs() << '\n';
231 }
232 #endif
233 
234 void SCEV::print(raw_ostream &OS) const {
235  switch (static_cast<SCEVTypes>(getSCEVType())) {
236  case scConstant:
237  cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
238  return;
239  case scTruncate: {
240  const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
241  const SCEV *Op = Trunc->getOperand();
242  OS << "(trunc " << *Op->getType() << " " << *Op << " to "
243  << *Trunc->getType() << ")";
244  return;
245  }
246  case scZeroExtend: {
247  const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
248  const SCEV *Op = ZExt->getOperand();
249  OS << "(zext " << *Op->getType() << " " << *Op << " to "
250  << *ZExt->getType() << ")";
251  return;
252  }
253  case scSignExtend: {
254  const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
255  const SCEV *Op = SExt->getOperand();
256  OS << "(sext " << *Op->getType() << " " << *Op << " to "
257  << *SExt->getType() << ")";
258  return;
259  }
260  case scAddRecExpr: {
261  const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
262  OS << "{" << *AR->getOperand(0);
263  for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
264  OS << ",+," << *AR->getOperand(i);
265  OS << "}<";
266  if (AR->hasNoUnsignedWrap())
267  OS << "nuw><";
268  if (AR->hasNoSignedWrap())
269  OS << "nsw><";
270  if (AR->hasNoSelfWrap() &&
272  OS << "nw><";
273  AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
274  OS << ">";
275  return;
276  }
277  case scAddExpr:
278  case scMulExpr:
279  case scUMaxExpr:
280  case scSMaxExpr:
281  case scUMinExpr:
282  case scSMinExpr: {
283  const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
284  const char *OpStr = nullptr;
285  switch (NAry->getSCEVType()) {
286  case scAddExpr: OpStr = " + "; break;
287  case scMulExpr: OpStr = " * "; break;
288  case scUMaxExpr: OpStr = " umax "; break;
289  case scSMaxExpr: OpStr = " smax "; break;
290  case scUMinExpr:
291  OpStr = " umin ";
292  break;
293  case scSMinExpr:
294  OpStr = " smin ";
295  break;
296  }
297  OS << "(";
298  for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
299  I != E; ++I) {
300  OS << **I;
301  if (std::next(I) != E)
302  OS << OpStr;
303  }
304  OS << ")";
305  switch (NAry->getSCEVType()) {
306  case scAddExpr:
307  case scMulExpr:
308  if (NAry->hasNoUnsignedWrap())
309  OS << "<nuw>";
310  if (NAry->hasNoSignedWrap())
311  OS << "<nsw>";
312  }
313  return;
314  }
315  case scUDivExpr: {
316  const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
317  OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
318  return;
319  }
320  case scUnknown: {
321  const SCEVUnknown *U = cast<SCEVUnknown>(this);
322  Type *AllocTy;
323  if (U->isSizeOf(AllocTy)) {
324  OS << "sizeof(" << *AllocTy << ")";
325  return;
326  }
327  if (U->isAlignOf(AllocTy)) {
328  OS << "alignof(" << *AllocTy << ")";
329  return;
330  }
331 
332  Type *CTy;
333  Constant *FieldNo;
334  if (U->isOffsetOf(CTy, FieldNo)) {
335  OS << "offsetof(" << *CTy << ", ";
336  FieldNo->printAsOperand(OS, false);
337  OS << ")";
338  return;
339  }
340 
341  // Otherwise just print it normally.
342  U->getValue()->printAsOperand(OS, false);
343  return;
344  }
345  case scCouldNotCompute:
346  OS << "***COULDNOTCOMPUTE***";
347  return;
348  }
349  llvm_unreachable("Unknown SCEV kind!");
350 }
351 
352 Type *SCEV::getType() const {
353  switch (static_cast<SCEVTypes>(getSCEVType())) {
354  case scConstant:
355  return cast<SCEVConstant>(this)->getType();
356  case scTruncate:
357  case scZeroExtend:
358  case scSignExtend:
359  return cast<SCEVCastExpr>(this)->getType();
360  case scAddRecExpr:
361  case scMulExpr:
362  case scUMaxExpr:
363  case scSMaxExpr:
364  case scUMinExpr:
365  case scSMinExpr:
366  return cast<SCEVNAryExpr>(this)->getType();
367  case scAddExpr:
368  return cast<SCEVAddExpr>(this)->getType();
369  case scUDivExpr:
370  return cast<SCEVUDivExpr>(this)->getType();
371  case scUnknown:
372  return cast<SCEVUnknown>(this)->getType();
373  case scCouldNotCompute:
374  llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
375  }
376  llvm_unreachable("Unknown SCEV kind!");
377 }
378 
379 bool SCEV::isZero() const {
380  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
381  return SC->getValue()->isZero();
382  return false;
383 }
384 
385 bool SCEV::isOne() const {
386  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
387  return SC->getValue()->isOne();
388  return false;
389 }
390 
391 bool SCEV::isAllOnesValue() const {
392  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
393  return SC->getValue()->isMinusOne();
394  return false;
395 }
396 
398  const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
399  if (!Mul) return false;
400 
401  // If there is a constant factor, it will be first.
402  const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
403  if (!SC) return false;
404 
405  // Return true if the value is negative, this matches things like (-42 * V).
406  return SC->getAPInt().isNegative();
407 }
408 
411 
413  return S->getSCEVType() == scCouldNotCompute;
414 }
415 
419  ID.AddPointer(V);
420  void *IP = nullptr;
421  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
422  SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
423  UniqueSCEVs.InsertNode(S, IP);
424  return S;
425 }
426 
428  return getConstant(ConstantInt::get(getContext(), Val));
429 }
430 
431 const SCEV *
432 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
433  IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
434  return getConstant(ConstantInt::get(ITy, V, isSigned));
435 }
436 
438  unsigned SCEVTy, const SCEV *op, Type *ty)
439  : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
440 
441 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
442  const SCEV *op, Type *ty)
443  : SCEVCastExpr(ID, scTruncate, op, ty) {
445  "Cannot truncate non-integer value!");
446 }
447 
448 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
449  const SCEV *op, Type *ty)
450  : SCEVCastExpr(ID, scZeroExtend, op, ty) {
452  "Cannot zero extend non-integer value!");
453 }
454 
455 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
456  const SCEV *op, Type *ty)
457  : SCEVCastExpr(ID, scSignExtend, op, ty) {
459  "Cannot sign extend non-integer value!");
460 }
461 
462 void SCEVUnknown::deleted() {
463  // Clear this SCEVUnknown from various maps.
464  SE->forgetMemoizedResults(this);
465 
466  // Remove this SCEVUnknown from the uniquing map.
467  SE->UniqueSCEVs.RemoveNode(this);
468 
469  // Release the value.
470  setValPtr(nullptr);
471 }
472 
473 void SCEVUnknown::allUsesReplacedWith(Value *New) {
474  // Remove this SCEVUnknown from the uniquing map.
475  SE->UniqueSCEVs.RemoveNode(this);
476 
477  // Update this SCEVUnknown to point to the new value. This is needed
478  // because there may still be outstanding SCEVs which still point to
479  // this SCEVUnknown.
480  setValPtr(New);
481 }
482 
483 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
484  if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
485  if (VCE->getOpcode() == Instruction::PtrToInt)
486  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
487  if (CE->getOpcode() == Instruction::GetElementPtr &&
488  CE->getOperand(0)->isNullValue() &&
489  CE->getNumOperands() == 2)
490  if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
491  if (CI->isOne()) {
492  AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
493  ->getElementType();
494  return true;
495  }
496 
497  return false;
498 }
499 
500 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
501  if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
502  if (VCE->getOpcode() == Instruction::PtrToInt)
503  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
504  if (CE->getOpcode() == Instruction::GetElementPtr &&
505  CE->getOperand(0)->isNullValue()) {
506  Type *Ty =
507  cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
508  if (StructType *STy = dyn_cast<StructType>(Ty))
509  if (!STy->isPacked() &&
510  CE->getNumOperands() == 3 &&
511  CE->getOperand(1)->isNullValue()) {
512  if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
513  if (CI->isOne() &&
514  STy->getNumElements() == 2 &&
515  STy->getElementType(0)->isIntegerTy(1)) {
516  AllocTy = STy->getElementType(1);
517  return true;
518  }
519  }
520  }
521 
522  return false;
523 }
524 
525 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
526  if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
527  if (VCE->getOpcode() == Instruction::PtrToInt)
528  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
529  if (CE->getOpcode() == Instruction::GetElementPtr &&
530  CE->getNumOperands() == 3 &&
531  CE->getOperand(0)->isNullValue() &&
532  CE->getOperand(1)->isNullValue()) {
533  Type *Ty =
534  cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
535  // Ignore vector types here so that ScalarEvolutionExpander doesn't
536  // emit getelementptrs that index into vectors.
537  if (Ty->isStructTy() || Ty->isArrayTy()) {
538  CTy = Ty;
539  FieldNo = CE->getOperand(2);
540  return true;
541  }
542  }
543 
544  return false;
545 }
546 
547 //===----------------------------------------------------------------------===//
548 // SCEV Utilities
549 //===----------------------------------------------------------------------===//
550 
551 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
552 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
553 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that
554 /// have been previously deemed to be "equally complex" by this routine. It is
555 /// intended to avoid exponential time complexity in cases like:
556 ///
557 /// %a = f(%x, %y)
558 /// %b = f(%a, %a)
559 /// %c = f(%b, %b)
560 ///
561 /// %d = f(%x, %y)
562 /// %e = f(%d, %d)
563 /// %f = f(%e, %e)
564 ///
565 /// CompareValueComplexity(%f, %c)
566 ///
567 /// Since we do not continue running this routine on expression trees once we
568 /// have seen unequal values, there is no need to track them in the cache.
569 static int
571  const LoopInfo *const LI, Value *LV, Value *RV,
572  unsigned Depth) {
573  if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
574  return 0;
575 
576  // Order pointer values after integer values. This helps SCEVExpander form
577  // GEPs.
578  bool LIsPointer = LV->getType()->isPointerTy(),
579  RIsPointer = RV->getType()->isPointerTy();
580  if (LIsPointer != RIsPointer)
581  return (int)LIsPointer - (int)RIsPointer;
582 
583  // Compare getValueID values.
584  unsigned LID = LV->getValueID(), RID = RV->getValueID();
585  if (LID != RID)
586  return (int)LID - (int)RID;
587 
588  // Sort arguments by their position.
589  if (const auto *LA = dyn_cast<Argument>(LV)) {
590  const auto *RA = cast<Argument>(RV);
591  unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
592  return (int)LArgNo - (int)RArgNo;
593  }
594 
595  if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
596  const auto *RGV = cast<GlobalValue>(RV);
597 
598  const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
599  auto LT = GV->getLinkage();
600  return !(GlobalValue::isPrivateLinkage(LT) ||
602  };
603 
604  // Use the names to distinguish the two values, but only if the
605  // names are semantically important.
606  if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
607  return LGV->getName().compare(RGV->getName());
608  }
609 
610  // For instructions, compare their loop depth, and their operand count. This
611  // is pretty loose.
612  if (const auto *LInst = dyn_cast<Instruction>(LV)) {
613  const auto *RInst = cast<Instruction>(RV);
614 
615  // Compare loop depths.
616  const BasicBlock *LParent = LInst->getParent(),
617  *RParent = RInst->getParent();
618  if (LParent != RParent) {
619  unsigned LDepth = LI->getLoopDepth(LParent),
620  RDepth = LI->getLoopDepth(RParent);
621  if (LDepth != RDepth)
622  return (int)LDepth - (int)RDepth;
623  }
624 
625  // Compare the number of operands.
626  unsigned LNumOps = LInst->getNumOperands(),
627  RNumOps = RInst->getNumOperands();
628  if (LNumOps != RNumOps)
629  return (int)LNumOps - (int)RNumOps;
630 
631  for (unsigned Idx : seq(0u, LNumOps)) {
632  int Result =
633  CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
634  RInst->getOperand(Idx), Depth + 1);
635  if (Result != 0)
636  return Result;
637  }
638  }
639 
640  EqCacheValue.unionSets(LV, RV);
641  return 0;
642 }
643 
644 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
645 // than RHS, respectively. A three-way result allows recursive comparisons to be
646 // more efficient.
649  EquivalenceClasses<const Value *> &EqCacheValue,
650  const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
651  DominatorTree &DT, unsigned Depth = 0) {
652  // Fast-path: SCEVs are uniqued so we can do a quick equality check.
653  if (LHS == RHS)
654  return 0;
655 
656  // Primarily, sort the SCEVs by their getSCEVType().
657  unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
658  if (LType != RType)
659  return (int)LType - (int)RType;
660 
661  if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
662  return 0;
663  // Aside from the getSCEVType() ordering, the particular ordering
664  // isn't very important except that it's beneficial to be consistent,
665  // so that (a + b) and (b + a) don't end up as different expressions.
666  switch (static_cast<SCEVTypes>(LType)) {
667  case scUnknown: {
668  const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
669  const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
670 
671  int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
672  RU->getValue(), Depth + 1);
673  if (X == 0)
674  EqCacheSCEV.unionSets(LHS, RHS);
675  return X;
676  }
677 
678  case scConstant: {
679  const SCEVConstant *LC = cast<SCEVConstant>(LHS);
680  const SCEVConstant *RC = cast<SCEVConstant>(RHS);
681 
682  // Compare constant values.
683  const APInt &LA = LC->getAPInt();
684  const APInt &RA = RC->getAPInt();
685  unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
686  if (LBitWidth != RBitWidth)
687  return (int)LBitWidth - (int)RBitWidth;
688  return LA.ult(RA) ? -1 : 1;
689  }
690 
691  case scAddRecExpr: {
692  const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
693  const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
694 
695  // There is always a dominance between two recs that are used by one SCEV,
696  // so we can safely sort recs by loop header dominance. We require such
697  // order in getAddExpr.
698  const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
699  if (LLoop != RLoop) {
700  const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
701  assert(LHead != RHead && "Two loops share the same header?");
702  if (DT.dominates(LHead, RHead))
703  return 1;
704  else
705  assert(DT.dominates(RHead, LHead) &&
706  "No dominance between recurrences used by one SCEV?");
707  return -1;
708  }
709 
710  // Addrec complexity grows with operand count.
711  unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
712  if (LNumOps != RNumOps)
713  return (int)LNumOps - (int)RNumOps;
714 
715  // Lexicographically compare.
716  for (unsigned i = 0; i != LNumOps; ++i) {
717  int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
718  LA->getOperand(i), RA->getOperand(i), DT,
719  Depth + 1);
720  if (X != 0)
721  return X;
722  }
723  EqCacheSCEV.unionSets(LHS, RHS);
724  return 0;
725  }
726 
727  case scAddExpr:
728  case scMulExpr:
729  case scSMaxExpr:
730  case scUMaxExpr:
731  case scSMinExpr:
732  case scUMinExpr: {
733  const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
734  const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
735 
736  // Lexicographically compare n-ary expressions.
737  unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
738  if (LNumOps != RNumOps)
739  return (int)LNumOps - (int)RNumOps;
740 
741  for (unsigned i = 0; i != LNumOps; ++i) {
742  int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
743  LC->getOperand(i), RC->getOperand(i), DT,
744  Depth + 1);
745  if (X != 0)
746  return X;
747  }
748  EqCacheSCEV.unionSets(LHS, RHS);
749  return 0;
750  }
751 
752  case scUDivExpr: {
753  const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
754  const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
755 
756  // Lexicographically compare udiv expressions.
757  int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
758  RC->getLHS(), DT, Depth + 1);
759  if (X != 0)
760  return X;
761  X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
762  RC->getRHS(), DT, Depth + 1);
763  if (X == 0)
764  EqCacheSCEV.unionSets(LHS, RHS);
765  return X;
766  }
767 
768  case scTruncate:
769  case scZeroExtend:
770  case scSignExtend: {
771  const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
772  const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
773 
774  // Compare cast expressions by operand.
775  int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
776  LC->getOperand(), RC->getOperand(), DT,
777  Depth + 1);
778  if (X == 0)
779  EqCacheSCEV.unionSets(LHS, RHS);
780  return X;
781  }
782 
783  case scCouldNotCompute:
784  llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
785  }
786  llvm_unreachable("Unknown SCEV kind!");
787 }
788 
789 /// Given a list of SCEV objects, order them by their complexity, and group
790 /// objects of the same complexity together by value. When this routine is
791 /// finished, we know that any duplicates in the vector are consecutive and that
792 /// complexity is monotonically increasing.
793 ///
794 /// Note that we go take special precautions to ensure that we get deterministic
795 /// results from this routine. In other words, we don't want the results of
796 /// this to depend on where the addresses of various SCEV objects happened to
797 /// land in memory.
799  LoopInfo *LI, DominatorTree &DT) {
800  if (Ops.size() < 2) return; // Noop
801 
804  if (Ops.size() == 2) {
805  // This is the common case, which also happens to be trivially simple.
806  // Special case it.
807  const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
808  if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
809  std::swap(LHS, RHS);
810  return;
811  }
812 
813  // Do the rough sort by complexity.
814  llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
815  return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) <
816  0;
817  });
818 
819  // Now that we are sorted by complexity, group elements of the same
820  // complexity. Note that this is, at worst, N^2, but the vector is likely to
821  // be extremely short in practice. Note that we take this approach because we
822  // do not want to depend on the addresses of the objects we are grouping.
823  for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
824  const SCEV *S = Ops[i];
825  unsigned Complexity = S->getSCEVType();
826 
827  // If there are any objects of the same complexity and same value as this
828  // one, group them.
829  for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
830  if (Ops[j] == S) { // Found a duplicate.
831  // Move it to immediately after i'th element.
832  std::swap(Ops[i+1], Ops[j]);
833  ++i; // no need to rescan it.
834  if (i == e-2) return; // Done!
835  }
836  }
837  }
838 }
839 
840 // Returns the size of the SCEV S.
841 static inline int sizeOfSCEV(const SCEV *S) {
842  struct FindSCEVSize {
843  int Size = 0;
844 
845  FindSCEVSize() = default;
846 
847  bool follow(const SCEV *S) {
848  ++Size;
849  // Keep looking at all operands of S.
850  return true;
851  }
852 
853  bool isDone() const {
854  return false;
855  }
856  };
857 
858  FindSCEVSize F;
860  ST.visitAll(S);
861  return F.Size;
862 }
863 
864 /// Returns true if the subtree of \p S contains at least HugeExprThreshold
865 /// nodes.
866 static bool isHugeExpression(const SCEV *S) {
867  return S->getExpressionSize() >= HugeExprThreshold;
868 }
869 
870 /// Returns true of \p Ops contains a huge SCEV (see definition above).
872  return any_of(Ops, isHugeExpression);
873 }
874 
875 namespace {
876 
877 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
878 public:
879  // Computes the Quotient and Remainder of the division of Numerator by
880  // Denominator.
881  static void divide(ScalarEvolution &SE, const SCEV *Numerator,
882  const SCEV *Denominator, const SCEV **Quotient,
883  const SCEV **Remainder) {
884  assert(Numerator && Denominator && "Uninitialized SCEV");
885 
886  SCEVDivision D(SE, Numerator, Denominator);
887 
888  // Check for the trivial case here to avoid having to check for it in the
889  // rest of the code.
890  if (Numerator == Denominator) {
891  *Quotient = D.One;
892  *Remainder = D.Zero;
893  return;
894  }
895 
896  if (Numerator->isZero()) {
897  *Quotient = D.Zero;
898  *Remainder = D.Zero;
899  return;
900  }
901 
902  // A simple case when N/1. The quotient is N.
903  if (Denominator->isOne()) {
904  *Quotient = Numerator;
905  *Remainder = D.Zero;
906  return;
907  }
908 
909  // Split the Denominator when it is a product.
910  if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
911  const SCEV *Q, *R;
912  *Quotient = Numerator;
913  for (const SCEV *Op : T->operands()) {
914  divide(SE, *Quotient, Op, &Q, &R);
915  *Quotient = Q;
916 
917  // Bail out when the Numerator is not divisible by one of the terms of
918  // the Denominator.
919  if (!R->isZero()) {
920  *Quotient = D.Zero;
921  *Remainder = Numerator;
922  return;
923  }
924  }
925  *Remainder = D.Zero;
926  return;
927  }
928 
929  D.visit(Numerator);
930  *Quotient = D.Quotient;
931  *Remainder = D.Remainder;
932  }
933 
934  // Except in the trivial case described above, we do not know how to divide
935  // Expr by Denominator for the following functions with empty implementation.
936  void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
937  void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
938  void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
939  void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
940  void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
941  void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
942  void visitSMinExpr(const SCEVSMinExpr *Numerator) {}
943  void visitUMinExpr(const SCEVUMinExpr *Numerator) {}
944  void visitUnknown(const SCEVUnknown *Numerator) {}
945  void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
946 
947  void visitConstant(const SCEVConstant *Numerator) {
948  if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
949  APInt NumeratorVal = Numerator->getAPInt();
950  APInt DenominatorVal = D->getAPInt();
951  uint32_t NumeratorBW = NumeratorVal.getBitWidth();
952  uint32_t DenominatorBW = DenominatorVal.getBitWidth();
953 
954  if (NumeratorBW > DenominatorBW)
955  DenominatorVal = DenominatorVal.sext(NumeratorBW);
956  else if (NumeratorBW < DenominatorBW)
957  NumeratorVal = NumeratorVal.sext(DenominatorBW);
958 
959  APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
960  APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
961  APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
962  Quotient = SE.getConstant(QuotientVal);
963  Remainder = SE.getConstant(RemainderVal);
964  return;
965  }
966  }
967 
968  void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
969  const SCEV *StartQ, *StartR, *StepQ, *StepR;
970  if (!Numerator->isAffine())
971  return cannotDivide(Numerator);
972  divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
973  divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
974  // Bail out if the types do not match.
975  Type *Ty = Denominator->getType();
976  if (Ty != StartQ->getType() || Ty != StartR->getType() ||
977  Ty != StepQ->getType() || Ty != StepR->getType())
978  return cannotDivide(Numerator);
979  Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
980  Numerator->getNoWrapFlags());
981  Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
982  Numerator->getNoWrapFlags());
983  }
984 
985  void visitAddExpr(const SCEVAddExpr *Numerator) {
987  Type *Ty = Denominator->getType();
988 
989  for (const SCEV *Op : Numerator->operands()) {
990  const SCEV *Q, *R;
991  divide(SE, Op, Denominator, &Q, &R);
992 
993  // Bail out if types do not match.
994  if (Ty != Q->getType() || Ty != R->getType())
995  return cannotDivide(Numerator);
996 
997  Qs.push_back(Q);
998  Rs.push_back(R);
999  }
1000 
1001  if (Qs.size() == 1) {
1002  Quotient = Qs[0];
1003  Remainder = Rs[0];
1004  return;
1005  }
1006 
1007  Quotient = SE.getAddExpr(Qs);
1008  Remainder = SE.getAddExpr(Rs);
1009  }
1010 
1011  void visitMulExpr(const SCEVMulExpr *Numerator) {
1013  Type *Ty = Denominator->getType();
1014 
1015  bool FoundDenominatorTerm = false;
1016  for (const SCEV *Op : Numerator->operands()) {
1017  // Bail out if types do not match.
1018  if (Ty != Op->getType())
1019  return cannotDivide(Numerator);
1020 
1021  if (FoundDenominatorTerm) {
1022  Qs.push_back(Op);
1023  continue;
1024  }
1025 
1026  // Check whether Denominator divides one of the product operands.
1027  const SCEV *Q, *R;
1028  divide(SE, Op, Denominator, &Q, &R);
1029  if (!R->isZero()) {
1030  Qs.push_back(Op);
1031  continue;
1032  }
1033 
1034  // Bail out if types do not match.
1035  if (Ty != Q->getType())
1036  return cannotDivide(Numerator);
1037 
1038  FoundDenominatorTerm = true;
1039  Qs.push_back(Q);
1040  }
1041 
1042  if (FoundDenominatorTerm) {
1043  Remainder = Zero;
1044  if (Qs.size() == 1)
1045  Quotient = Qs[0];
1046  else
1047  Quotient = SE.getMulExpr(Qs);
1048  return;
1049  }
1050 
1051  if (!isa<SCEVUnknown>(Denominator))
1052  return cannotDivide(Numerator);
1053 
1054  // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1055  ValueToValueMap RewriteMap;
1056  RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1057  cast<SCEVConstant>(Zero)->getValue();
1058  Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1059 
1060  if (Remainder->isZero()) {
1061  // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1062  RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1063  cast<SCEVConstant>(One)->getValue();
1064  Quotient =
1065  SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1066  return;
1067  }
1068 
1069  // Quotient is (Numerator - Remainder) divided by Denominator.
1070  const SCEV *Q, *R;
1071  const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1072  // This SCEV does not seem to simplify: fail the division here.
1073  if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1074  return cannotDivide(Numerator);
1075  divide(SE, Diff, Denominator, &Q, &R);
1076  if (R != Zero)
1077  return cannotDivide(Numerator);
1078  Quotient = Q;
1079  }
1080 
1081 private:
1082  SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1083  const SCEV *Denominator)
1084  : SE(S), Denominator(Denominator) {
1085  Zero = SE.getZero(Denominator->getType());
1086  One = SE.getOne(Denominator->getType());
1087 
1088  // We generally do not know how to divide Expr by Denominator. We
1089  // initialize the division to a "cannot divide" state to simplify the rest
1090  // of the code.
1091  cannotDivide(Numerator);
1092  }
1093 
1094  // Convenience function for giving up on the division. We set the quotient to
1095  // be equal to zero and the remainder to be equal to the numerator.
1096  void cannotDivide(const SCEV *Numerator) {
1097  Quotient = Zero;
1098  Remainder = Numerator;
1099  }
1100 
1101  ScalarEvolution &SE;
1102  const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1103 };
1104 
1105 } // end anonymous namespace
1106 
1107 //===----------------------------------------------------------------------===//
1108 // Simple SCEV method implementations
1109 //===----------------------------------------------------------------------===//
1110 
1111 /// Compute BC(It, K). The result has width W. Assume, K > 0.
1112 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1113  ScalarEvolution &SE,
1114  Type *ResultTy) {
1115  // Handle the simplest case efficiently.
1116  if (K == 1)
1117  return SE.getTruncateOrZeroExtend(It, ResultTy);
1118 
1119  // We are using the following formula for BC(It, K):
1120  //
1121  // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1122  //
1123  // Suppose, W is the bitwidth of the return value. We must be prepared for
1124  // overflow. Hence, we must assure that the result of our computation is
1125  // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1126  // safe in modular arithmetic.
1127  //
1128  // However, this code doesn't use exactly that formula; the formula it uses
1129  // is something like the following, where T is the number of factors of 2 in
1130  // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1131  // exponentiation:
1132  //
1133  // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1134  //
1135  // This formula is trivially equivalent to the previous formula. However,
1136  // this formula can be implemented much more efficiently. The trick is that
1137  // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1138  // arithmetic. To do exact division in modular arithmetic, all we have
1139  // to do is multiply by the inverse. Therefore, this step can be done at
1140  // width W.
1141  //
1142  // The next issue is how to safely do the division by 2^T. The way this
1143  // is done is by doing the multiplication step at a width of at least W + T
1144  // bits. This way, the bottom W+T bits of the product are accurate. Then,
1145  // when we perform the division by 2^T (which is equivalent to a right shift
1146  // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1147  // truncated out after the division by 2^T.
1148  //
1149  // In comparison to just directly using the first formula, this technique
1150  // is much more efficient; using the first formula requires W * K bits,
1151  // but this formula less than W + K bits. Also, the first formula requires
1152  // a division step, whereas this formula only requires multiplies and shifts.
1153  //
1154  // It doesn't matter whether the subtraction step is done in the calculation
1155  // width or the input iteration count's width; if the subtraction overflows,
1156  // the result must be zero anyway. We prefer here to do it in the width of
1157  // the induction variable because it helps a lot for certain cases; CodeGen
1158  // isn't smart enough to ignore the overflow, which leads to much less
1159  // efficient code if the width of the subtraction is wider than the native
1160  // register width.
1161  //
1162  // (It's possible to not widen at all by pulling out factors of 2 before
1163  // the multiplication; for example, K=2 can be calculated as
1164  // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1165  // extra arithmetic, so it's not an obvious win, and it gets
1166  // much more complicated for K > 3.)
1167 
1168  // Protection from insane SCEVs; this bound is conservative,
1169  // but it probably doesn't matter.
1170  if (K > 1000)
1171  return SE.getCouldNotCompute();
1172 
1173  unsigned W = SE.getTypeSizeInBits(ResultTy);
1174 
1175  // Calculate K! / 2^T and T; we divide out the factors of two before
1176  // multiplying for calculating K! / 2^T to avoid overflow.
1177  // Other overflow doesn't matter because we only care about the bottom
1178  // W bits of the result.
1179  APInt OddFactorial(W, 1);
1180  unsigned T = 1;
1181  for (unsigned i = 3; i <= K; ++i) {
1182  APInt Mult(W, i);
1183  unsigned TwoFactors = Mult.countTrailingZeros();
1184  T += TwoFactors;
1185  Mult.lshrInPlace(TwoFactors);
1186  OddFactorial *= Mult;
1187  }
1188 
1189  // We need at least W + T bits for the multiplication step
1190  unsigned CalculationBits = W + T;
1191 
1192  // Calculate 2^T, at width T+W.
1193  APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1194 
1195  // Calculate the multiplicative inverse of K! / 2^T;
1196  // this multiplication factor will perform the exact division by
1197  // K! / 2^T.
1199  APInt MultiplyFactor = OddFactorial.zext(W+1);
1200  MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1201  MultiplyFactor = MultiplyFactor.trunc(W);
1202 
1203  // Calculate the product, at width T+W
1204  IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1205  CalculationBits);
1206  const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1207  for (unsigned i = 1; i != K; ++i) {
1208  const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1209  Dividend = SE.getMulExpr(Dividend,
1210  SE.getTruncateOrZeroExtend(S, CalculationTy));
1211  }
1212 
1213  // Divide by 2^T
1214  const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1215 
1216  // Truncate the result, and divide by K! / 2^T.
1217 
1218  return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1219  SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1220 }
1221 
1222 /// Return the value of this chain of recurrences at the specified iteration
1223 /// number. We can evaluate this recurrence by multiplying each element in the
1224 /// chain by the binomial coefficient corresponding to it. In other words, we
1225 /// can evaluate {A,+,B,+,C,+,D} as:
1226 ///
1227 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1228 ///
1229 /// where BC(It, k) stands for binomial coefficient.
1231  ScalarEvolution &SE) const {
1232  const SCEV *Result = getStart();
1233  for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1234  // The computation is correct in the face of overflow provided that the
1235  // multiplication is performed _after_ the evaluation of the binomial
1236  // coefficient.
1237  const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1238  if (isa<SCEVCouldNotCompute>(Coeff))
1239  return Coeff;
1240 
1241  Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1242  }
1243  return Result;
1244 }
1245 
1246 //===----------------------------------------------------------------------===//
1247 // SCEV Expression folder implementations
1248 //===----------------------------------------------------------------------===//
1249 
1251  unsigned Depth) {
1252  assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1253  "This is not a truncating conversion!");
1254  assert(isSCEVable(Ty) &&
1255  "This is not a conversion to a SCEVable type!");
1256  Ty = getEffectiveSCEVType(Ty);
1257 
1259  ID.AddInteger(scTruncate);
1260  ID.AddPointer(Op);
1261  ID.AddPointer(Ty);
1262  void *IP = nullptr;
1263  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1264 
1265  // Fold if the operand is constant.
1266  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1267  return getConstant(
1268  cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1269 
1270  // trunc(trunc(x)) --> trunc(x)
1271  if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1272  return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1273 
1274  // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1275  if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1276  return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1277 
1278  // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1279  if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1280  return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1281 
1282  if (Depth > MaxCastDepth) {
1283  SCEV *S =
1284  new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1285  UniqueSCEVs.InsertNode(S, IP);
1286  addToLoopUseLists(S);
1287  return S;
1288  }
1289 
1290  // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1291  // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1292  // if after transforming we have at most one truncate, not counting truncates
1293  // that replace other casts.
1294  if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1295  auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1297  unsigned numTruncs = 0;
1298  for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1299  ++i) {
1300  const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1301  if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
1302  numTruncs++;
1303  Operands.push_back(S);
1304  }
1305  if (numTruncs < 2) {
1306  if (isa<SCEVAddExpr>(Op))
1307  return getAddExpr(Operands);
1308  else if (isa<SCEVMulExpr>(Op))
1309  return getMulExpr(Operands);
1310  else
1311  llvm_unreachable("Unexpected SCEV type for Op.");
1312  }
1313  // Although we checked in the beginning that ID is not in the cache, it is
1314  // possible that during recursion and different modification ID was inserted
1315  // into the cache. So if we find it, just return it.
1316  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1317  return S;
1318  }
1319 
1320  // If the input value is a chrec scev, truncate the chrec's operands.
1321  if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1323  for (const SCEV *Op : AddRec->operands())
1324  Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1325  return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1326  }
1327 
1328  // The cast wasn't folded; create an explicit cast node. We can reuse
1329  // the existing insert position since if we get here, we won't have
1330  // made any changes which would invalidate it.
1331  SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1332  Op, Ty);
1333  UniqueSCEVs.InsertNode(S, IP);
1334  addToLoopUseLists(S);
1335  return S;
1336 }
1337 
1338 // Get the limit of a recurrence such that incrementing by Step cannot cause
1339 // signed overflow as long as the value of the recurrence within the
1340 // loop does not exceed this limit before incrementing.
1341 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1342  ICmpInst::Predicate *Pred,
1343  ScalarEvolution *SE) {
1344  unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1345  if (SE->isKnownPositive(Step)) {
1346  *Pred = ICmpInst::ICMP_SLT;
1347  return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1348  SE->getSignedRangeMax(Step));
1349  }
1350  if (SE->isKnownNegative(Step)) {
1351  *Pred = ICmpInst::ICMP_SGT;
1352  return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1353  SE->getSignedRangeMin(Step));
1354  }
1355  return nullptr;
1356 }
1357 
1358 // Get the limit of a recurrence such that incrementing by Step cannot cause
1359 // unsigned overflow as long as the value of the recurrence within the loop does
1360 // not exceed this limit before incrementing.
1361 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1362  ICmpInst::Predicate *Pred,
1363  ScalarEvolution *SE) {
1364  unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1365  *Pred = ICmpInst::ICMP_ULT;
1366 
1367  return SE->getConstant(APInt::getMinValue(BitWidth) -
1368  SE->getUnsignedRangeMax(Step));
1369 }
1370 
1371 namespace {
1372 
1373 struct ExtendOpTraitsBase {
1374  typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1375  unsigned);
1376 };
1377 
1378 // Used to make code generic over signed and unsigned overflow.
1379 template <typename ExtendOp> struct ExtendOpTraits {
1380  // Members present:
1381  //
1382  // static const SCEV::NoWrapFlags WrapType;
1383  //
1384  // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1385  //
1386  // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1387  // ICmpInst::Predicate *Pred,
1388  // ScalarEvolution *SE);
1389 };
1390 
1391 template <>
1392 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1393  static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1394 
1395  static const GetExtendExprTy GetExtendExpr;
1396 
1397  static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1398  ICmpInst::Predicate *Pred,
1399  ScalarEvolution *SE) {
1400  return getSignedOverflowLimitForStep(Step, Pred, SE);
1401  }
1402 };
1403 
1404 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1405  SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1406 
1407 template <>
1408 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1409  static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1410 
1411  static const GetExtendExprTy GetExtendExpr;
1412 
1413  static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1414  ICmpInst::Predicate *Pred,
1415  ScalarEvolution *SE) {
1416  return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1417  }
1418 };
1419 
1420 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1421  SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1422 
1423 } // end anonymous namespace
1424 
1425 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1426 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1427 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1428 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1429 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1430 // expression "Step + sext/zext(PreIncAR)" is congruent with
1431 // "sext/zext(PostIncAR)"
1432 template <typename ExtendOpTy>
1433 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1434  ScalarEvolution *SE, unsigned Depth) {
1435  auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1436  auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1437 
1438  const Loop *L = AR->getLoop();
1439  const SCEV *Start = AR->getStart();
1440  const SCEV *Step = AR->getStepRecurrence(*SE);
1441 
1442  // Check for a simple looking step prior to loop entry.
1443  const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1444  if (!SA)
1445  return nullptr;
1446 
1447  // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1448  // subtraction is expensive. For this purpose, perform a quick and dirty
1449  // difference, by checking for Step in the operand list.
1451  for (const SCEV *Op : SA->operands())
1452  if (Op != Step)
1453  DiffOps.push_back(Op);
1454 
1455  if (DiffOps.size() == SA->getNumOperands())
1456  return nullptr;
1457 
1458  // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1459  // `Step`:
1460 
1461  // 1. NSW/NUW flags on the step increment.
1462  auto PreStartFlags =
1464  const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1465  const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1466  SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1467 
1468  // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1469  // "S+X does not sign/unsign-overflow".
1470  //
1471 
1472  const SCEV *BECount = SE->getBackedgeTakenCount(L);
1473  if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1474  !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1475  return PreStart;
1476 
1477  // 2. Direct overflow check on the step operation's expression.
1478  unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1479  Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1480  const SCEV *OperandExtendedStart =
1481  SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1482  (SE->*GetExtendExpr)(Step, WideTy, Depth));
1483  if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1484  if (PreAR && AR->getNoWrapFlags(WrapType)) {
1485  // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1486  // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1487  // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1488  const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1489  }
1490  return PreStart;
1491  }
1492 
1493  // 3. Loop precondition.
1494  ICmpInst::Predicate Pred;
1495  const SCEV *OverflowLimit =
1496  ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1497 
1498  if (OverflowLimit &&
1499  SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1500  return PreStart;
1501 
1502  return nullptr;
1503 }
1504 
1505 // Get the normalized zero or sign extended expression for this AddRec's Start.
1506 template <typename ExtendOpTy>
1507 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1508  ScalarEvolution *SE,
1509  unsigned Depth) {
1510  auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1511 
1512  const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1513  if (!PreStart)
1514  return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1515 
1516  return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1517  Depth),
1518  (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1519 }
1520 
1521 // Try to prove away overflow by looking at "nearby" add recurrences. A
1522 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1523 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1524 //
1525 // Formally:
1526 //
1527 // {S,+,X} == {S-T,+,X} + T
1528 // => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1529 //
1530 // If ({S-T,+,X} + T) does not overflow ... (1)
1531 //
1532 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1533 //
1534 // If {S-T,+,X} does not overflow ... (2)
1535 //
1536 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1537 // == {Ext(S-T)+Ext(T),+,Ext(X)}
1538 //
1539 // If (S-T)+T does not overflow ... (3)
1540 //
1541 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1542 // == {Ext(S),+,Ext(X)} == LHS
1543 //
1544 // Thus, if (1), (2) and (3) are true for some T, then
1545 // Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1546 //
1547 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1548 // does not overflow" restricted to the 0th iteration. Therefore we only need
1549 // to check for (1) and (2).
1550 //
1551 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1552 // is `Delta` (defined below).
1553 template <typename ExtendOpTy>
1554 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1555  const SCEV *Step,
1556  const Loop *L) {
1557  auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1558 
1559  // We restrict `Start` to a constant to prevent SCEV from spending too much
1560  // time here. It is correct (but more expensive) to continue with a
1561  // non-constant `Start` and do a general SCEV subtraction to compute
1562  // `PreStart` below.
1563  const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1564  if (!StartC)
1565  return false;
1566 
1567  APInt StartAI = StartC->getAPInt();
1568 
1569  for (unsigned Delta : {-2, -1, 1, 2}) {
1570  const SCEV *PreStart = getConstant(StartAI - Delta);
1571 
1574  ID.AddPointer(PreStart);
1575  ID.AddPointer(Step);
1576  ID.AddPointer(L);
1577  void *IP = nullptr;
1578  const auto *PreAR =
1579  static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1580 
1581  // Give up if we don't already have the add recurrence we need because
1582  // actually constructing an add recurrence is relatively expensive.
1583  if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1584  const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1586  const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1587  DeltaS, &Pred, this);
1588  if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1589  return true;
1590  }
1591  }
1592 
1593  return false;
1594 }
1595 
1596 // Finds an integer D for an expression (C + x + y + ...) such that the top
1597 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1598 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1599 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1600 // the (C + x + y + ...) expression is \p WholeAddExpr.
1602  const SCEVConstant *ConstantTerm,
1603  const SCEVAddExpr *WholeAddExpr) {
1604  const APInt C = ConstantTerm->getAPInt();
1605  const unsigned BitWidth = C.getBitWidth();
1606  // Find number of trailing zeros of (x + y + ...) w/o the C first:
1607  uint32_t TZ = BitWidth;
1608  for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1609  TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1610  if (TZ) {
1611  // Set D to be as many least significant bits of C as possible while still
1612  // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1613  return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1614  }
1615  return APInt(BitWidth, 0);
1616 }
1617 
1618 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1619 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1620 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1621 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1623  const APInt &ConstantStart,
1624  const SCEV *Step) {
1625  const unsigned BitWidth = ConstantStart.getBitWidth();
1626  const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1627  if (TZ)
1628  return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1629  : ConstantStart;
1630  return APInt(BitWidth, 0);
1631 }
1632 
1633 const SCEV *
1635  assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1636  "This is not an extending conversion!");
1637  assert(isSCEVable(Ty) &&
1638  "This is not a conversion to a SCEVable type!");
1639  Ty = getEffectiveSCEVType(Ty);
1640 
1641  // Fold if the operand is constant.
1642  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1643  return getConstant(
1644  cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1645 
1646  // zext(zext(x)) --> zext(x)
1647  if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1648  return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1649 
1650  // Before doing any expensive analysis, check to see if we've already
1651  // computed a SCEV for this Op and Ty.
1654  ID.AddPointer(Op);
1655  ID.AddPointer(Ty);
1656  void *IP = nullptr;
1657  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1658  if (Depth > MaxCastDepth) {
1659  SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1660  Op, Ty);
1661  UniqueSCEVs.InsertNode(S, IP);
1662  addToLoopUseLists(S);
1663  return S;
1664  }
1665 
1666  // zext(trunc(x)) --> zext(x) or x or trunc(x)
1667  if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1668  // It's possible the bits taken off by the truncate were all zero bits. If
1669  // so, we should be able to simplify this further.
1670  const SCEV *X = ST->getOperand();
1671  ConstantRange CR = getUnsignedRange(X);
1672  unsigned TruncBits = getTypeSizeInBits(ST->getType());
1673  unsigned NewBits = getTypeSizeInBits(Ty);
1674  if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1675  CR.zextOrTrunc(NewBits)))
1676  return getTruncateOrZeroExtend(X, Ty, Depth);
1677  }
1678 
1679  // If the input value is a chrec scev, and we can prove that the value
1680  // did not overflow the old, smaller, value, we can zero extend all of the
1681  // operands (often constants). This allows analysis of something like
1682  // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1683  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1684  if (AR->isAffine()) {
1685  const SCEV *Start = AR->getStart();
1686  const SCEV *Step = AR->getStepRecurrence(*this);
1687  unsigned BitWidth = getTypeSizeInBits(AR->getType());
1688  const Loop *L = AR->getLoop();
1689 
1690  if (!AR->hasNoUnsignedWrap()) {
1691  auto NewFlags = proveNoWrapViaConstantRanges(AR);
1692  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1693  }
1694 
1695  // If we have special knowledge that this addrec won't overflow,
1696  // we don't need to do any further analysis.
1697  if (AR->hasNoUnsignedWrap())
1698  return getAddRecExpr(
1699  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1700  getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1701 
1702  // Check whether the backedge-taken count is SCEVCouldNotCompute.
1703  // Note that this serves two purposes: It filters out loops that are
1704  // simply not analyzable, and it covers the case where this code is
1705  // being called from within backedge-taken count analysis, such that
1706  // attempting to ask for the backedge-taken count would likely result
1707  // in infinite recursion. In the later case, the analysis code will
1708  // cope with a conservative value, and it will take care to purge
1709  // that value once it has finished.
1710  const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1711  if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1712  // Manually compute the final value for AR, checking for
1713  // overflow.
1714 
1715  // Check whether the backedge-taken count can be losslessly casted to
1716  // the addrec's type. The count is always unsigned.
1717  const SCEV *CastedMaxBECount =
1718  getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1719  const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1720  CastedMaxBECount, MaxBECount->getType(), Depth);
1721  if (MaxBECount == RecastedMaxBECount) {
1722  Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1723  // Check whether Start+Step*MaxBECount has no unsigned overflow.
1724  const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1725  SCEV::FlagAnyWrap, Depth + 1);
1726  const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1728  Depth + 1),
1729  WideTy, Depth + 1);
1730  const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1731  const SCEV *WideMaxBECount =
1732  getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1733  const SCEV *OperandExtendedAdd =
1734  getAddExpr(WideStart,
1735  getMulExpr(WideMaxBECount,
1736  getZeroExtendExpr(Step, WideTy, Depth + 1),
1737  SCEV::FlagAnyWrap, Depth + 1),
1738  SCEV::FlagAnyWrap, Depth + 1);
1739  if (ZAdd == OperandExtendedAdd) {
1740  // Cache knowledge of AR NUW, which is propagated to this AddRec.
1741  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1742  // Return the expression with the addrec on the outside.
1743  return getAddRecExpr(
1744  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1745  Depth + 1),
1746  getZeroExtendExpr(Step, Ty, Depth + 1), L,
1747  AR->getNoWrapFlags());
1748  }
1749  // Similar to above, only this time treat the step value as signed.
1750  // This covers loops that count down.
1751  OperandExtendedAdd =
1752  getAddExpr(WideStart,
1753  getMulExpr(WideMaxBECount,
1754  getSignExtendExpr(Step, WideTy, Depth + 1),
1755  SCEV::FlagAnyWrap, Depth + 1),
1756  SCEV::FlagAnyWrap, Depth + 1);
1757  if (ZAdd == OperandExtendedAdd) {
1758  // Cache knowledge of AR NW, which is propagated to this AddRec.
1759  // Negative step causes unsigned wrap, but it still can't self-wrap.
1760  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1761  // Return the expression with the addrec on the outside.
1762  return getAddRecExpr(
1763  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1764  Depth + 1),
1765  getSignExtendExpr(Step, Ty, Depth + 1), L,
1766  AR->getNoWrapFlags());
1767  }
1768  }
1769  }
1770 
1771  // Normally, in the cases we can prove no-overflow via a
1772  // backedge guarding condition, we can also compute a backedge
1773  // taken count for the loop. The exceptions are assumptions and
1774  // guards present in the loop -- SCEV is not great at exploiting
1775  // these to compute max backedge taken counts, but can still use
1776  // these to prove lack of overflow. Use this fact to avoid
1777  // doing extra work that may not pay off.
1778  if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1779  !AC.assumptions().empty()) {
1780  // If the backedge is guarded by a comparison with the pre-inc
1781  // value the addrec is safe. Also, if the entry is guarded by
1782  // a comparison with the start value and the backedge is
1783  // guarded by a comparison with the post-inc value, the addrec
1784  // is safe.
1785  if (isKnownPositive(Step)) {
1786  const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1787  getUnsignedRangeMax(Step));
1788  if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1789  isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1790  // Cache knowledge of AR NUW, which is propagated to this
1791  // AddRec.
1792  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1793  // Return the expression with the addrec on the outside.
1794  return getAddRecExpr(
1795  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1796  Depth + 1),
1797  getZeroExtendExpr(Step, Ty, Depth + 1), L,
1798  AR->getNoWrapFlags());
1799  }
1800  } else if (isKnownNegative(Step)) {
1801  const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1802  getSignedRangeMin(Step));
1803  if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1804  isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1805  // Cache knowledge of AR NW, which is propagated to this
1806  // AddRec. Negative step causes unsigned wrap, but it
1807  // still can't self-wrap.
1808  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1809  // Return the expression with the addrec on the outside.
1810  return getAddRecExpr(
1811  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1812  Depth + 1),
1813  getSignExtendExpr(Step, Ty, Depth + 1), L,
1814  AR->getNoWrapFlags());
1815  }
1816  }
1817  }
1818 
1819  // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1820  // if D + (C - D + Step * n) could be proven to not unsigned wrap
1821  // where D maximizes the number of trailing zeros of (C - D + Step * n)
1822  if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1823  const APInt &C = SC->getAPInt();
1824  const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1825  if (D != 0) {
1826  const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1827  const SCEV *SResidual =
1828  getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1829  const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1830  return getAddExpr(SZExtD, SZExtR,
1832  Depth + 1);
1833  }
1834  }
1835 
1836  if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1837  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1838  return getAddRecExpr(
1839  getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1840  getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1841  }
1842  }
1843 
1844  // zext(A % B) --> zext(A) % zext(B)
1845  {
1846  const SCEV *LHS;
1847  const SCEV *RHS;
1848  if (matchURem(Op, LHS, RHS))
1849  return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1850  getZeroExtendExpr(RHS, Ty, Depth + 1));
1851  }
1852 
1853  // zext(A / B) --> zext(A) / zext(B).
1854  if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1855  return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1856  getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1857 
1858  if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1859  // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1860  if (SA->hasNoUnsignedWrap()) {
1861  // If the addition does not unsign overflow then we can, by definition,
1862  // commute the zero extension with the addition operation.
1864  for (const auto *Op : SA->operands())
1865  Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1866  return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1867  }
1868 
1869  // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1870  // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1871  // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1872  //
1873  // Often address arithmetics contain expressions like
1874  // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1875  // This transformation is useful while proving that such expressions are
1876  // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1877  if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1878  const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1879  if (D != 0) {
1880  const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1881  const SCEV *SResidual =
1882  getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1883  const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1884  return getAddExpr(SZExtD, SZExtR,
1886  Depth + 1);
1887  }
1888  }
1889  }
1890 
1891  if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1892  // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1893  if (SM->hasNoUnsignedWrap()) {
1894  // If the multiply does not unsign overflow then we can, by definition,
1895  // commute the zero extension with the multiply operation.
1897  for (const auto *Op : SM->operands())
1898  Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1899  return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1900  }
1901 
1902  // zext(2^K * (trunc X to iN)) to iM ->
1903  // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1904  //
1905  // Proof:
1906  //
1907  // zext(2^K * (trunc X to iN)) to iM
1908  // = zext((trunc X to iN) << K) to iM
1909  // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1910  // (because shl removes the top K bits)
1911  // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1912  // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1913  //
1914  if (SM->getNumOperands() == 2)
1915  if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1916  if (MulLHS->getAPInt().isPowerOf2())
1917  if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1918  int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1919  MulLHS->getAPInt().logBase2();
1920  Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1921  return getMulExpr(
1922  getZeroExtendExpr(MulLHS, Ty),
1923  getZeroExtendExpr(
1924  getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1925  SCEV::FlagNUW, Depth + 1);
1926  }
1927  }
1928 
1929  // The cast wasn't folded; create an explicit cast node.
1930  // Recompute the insert position, as it may have been invalidated.
1931  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1932  SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1933  Op, Ty);
1934  UniqueSCEVs.InsertNode(S, IP);
1935  addToLoopUseLists(S);
1936  return S;
1937 }
1938 
1939 const SCEV *
1941  assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1942  "This is not an extending conversion!");
1943  assert(isSCEVable(Ty) &&
1944  "This is not a conversion to a SCEVable type!");
1945  Ty = getEffectiveSCEVType(Ty);
1946 
1947  // Fold if the operand is constant.
1948  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1949  return getConstant(
1950  cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1951 
1952  // sext(sext(x)) --> sext(x)
1953  if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1954  return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1955 
1956  // sext(zext(x)) --> zext(x)
1957  if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1958  return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1959 
1960  // Before doing any expensive analysis, check to see if we've already
1961  // computed a SCEV for this Op and Ty.
1964  ID.AddPointer(Op);
1965  ID.AddPointer(Ty);
1966  void *IP = nullptr;
1967  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1968  // Limit recursion depth.
1969  if (Depth > MaxCastDepth) {
1970  SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1971  Op, Ty);
1972  UniqueSCEVs.InsertNode(S, IP);
1973  addToLoopUseLists(S);
1974  return S;
1975  }
1976 
1977  // sext(trunc(x)) --> sext(x) or x or trunc(x)
1978  if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1979  // It's possible the bits taken off by the truncate were all sign bits. If
1980  // so, we should be able to simplify this further.
1981  const SCEV *X = ST->getOperand();
1982  ConstantRange CR = getSignedRange(X);
1983  unsigned TruncBits = getTypeSizeInBits(ST->getType());
1984  unsigned NewBits = getTypeSizeInBits(Ty);
1985  if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1986  CR.sextOrTrunc(NewBits)))
1987  return getTruncateOrSignExtend(X, Ty, Depth);
1988  }
1989 
1990  if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1991  // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1992  if (SA->hasNoSignedWrap()) {
1993  // If the addition does not sign overflow then we can, by definition,
1994  // commute the sign extension with the addition operation.
1996  for (const auto *Op : SA->operands())
1997  Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1998  return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1999  }
2000 
2001  // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2002  // if D + (C - D + x + y + ...) could be proven to not signed wrap
2003  // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2004  //
2005  // For instance, this will bring two seemingly different expressions:
2006  // 1 + sext(5 + 20 * %x + 24 * %y) and
2007  // sext(6 + 20 * %x + 24 * %y)
2008  // to the same form:
2009  // 2 + sext(4 + 20 * %x + 24 * %y)
2010  if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2011  const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2012  if (D != 0) {
2013  const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2014  const SCEV *SResidual =
2015  getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
2016  const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2017  return getAddExpr(SSExtD, SSExtR,
2019  Depth + 1);
2020  }
2021  }
2022  }
2023  // If the input value is a chrec scev, and we can prove that the value
2024  // did not overflow the old, smaller, value, we can sign extend all of the
2025  // operands (often constants). This allows analysis of something like
2026  // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2027  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
2028  if (AR->isAffine()) {
2029  const SCEV *Start = AR->getStart();
2030  const SCEV *Step = AR->getStepRecurrence(*this);
2031  unsigned BitWidth = getTypeSizeInBits(AR->getType());
2032  const Loop *L = AR->getLoop();
2033 
2034  if (!AR->hasNoSignedWrap()) {
2035  auto NewFlags = proveNoWrapViaConstantRanges(AR);
2036  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
2037  }
2038 
2039  // If we have special knowledge that this addrec won't overflow,
2040  // we don't need to do any further analysis.
2041  if (AR->hasNoSignedWrap())
2042  return getAddRecExpr(
2043  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2044  getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
2045 
2046  // Check whether the backedge-taken count is SCEVCouldNotCompute.
2047  // Note that this serves two purposes: It filters out loops that are
2048  // simply not analyzable, and it covers the case where this code is
2049  // being called from within backedge-taken count analysis, such that
2050  // attempting to ask for the backedge-taken count would likely result
2051  // in infinite recursion. In the later case, the analysis code will
2052  // cope with a conservative value, and it will take care to purge
2053  // that value once it has finished.
2054  const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
2055  if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2056  // Manually compute the final value for AR, checking for
2057  // overflow.
2058 
2059  // Check whether the backedge-taken count can be losslessly casted to
2060  // the addrec's type. The count is always unsigned.
2061  const SCEV *CastedMaxBECount =
2062  getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2063  const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2064  CastedMaxBECount, MaxBECount->getType(), Depth);
2065  if (MaxBECount == RecastedMaxBECount) {
2066  Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2067  // Check whether Start+Step*MaxBECount has no signed overflow.
2068  const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2069  SCEV::FlagAnyWrap, Depth + 1);
2070  const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2072  Depth + 1),
2073  WideTy, Depth + 1);
2074  const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2075  const SCEV *WideMaxBECount =
2076  getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2077  const SCEV *OperandExtendedAdd =
2078  getAddExpr(WideStart,
2079  getMulExpr(WideMaxBECount,
2080  getSignExtendExpr(Step, WideTy, Depth + 1),
2081  SCEV::FlagAnyWrap, Depth + 1),
2082  SCEV::FlagAnyWrap, Depth + 1);
2083  if (SAdd == OperandExtendedAdd) {
2084  // Cache knowledge of AR NSW, which is propagated to this AddRec.
2085  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2086  // Return the expression with the addrec on the outside.
2087  return getAddRecExpr(
2088  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2089  Depth + 1),
2090  getSignExtendExpr(Step, Ty, Depth + 1), L,
2091  AR->getNoWrapFlags());
2092  }
2093  // Similar to above, only this time treat the step value as unsigned.
2094  // This covers loops that count up with an unsigned step.
2095  OperandExtendedAdd =
2096  getAddExpr(WideStart,
2097  getMulExpr(WideMaxBECount,
2098  getZeroExtendExpr(Step, WideTy, Depth + 1),
2099  SCEV::FlagAnyWrap, Depth + 1),
2100  SCEV::FlagAnyWrap, Depth + 1);
2101  if (SAdd == OperandExtendedAdd) {
2102  // If AR wraps around then
2103  //
2104  // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2105  // => SAdd != OperandExtendedAdd
2106  //
2107  // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2108  // (SAdd == OperandExtendedAdd => AR is NW)
2109 
2110  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
2111 
2112  // Return the expression with the addrec on the outside.
2113  return getAddRecExpr(
2114  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2115  Depth + 1),
2116  getZeroExtendExpr(Step, Ty, Depth + 1), L,
2117  AR->getNoWrapFlags());
2118  }
2119  }
2120  }
2121 
2122  // Normally, in the cases we can prove no-overflow via a
2123  // backedge guarding condition, we can also compute a backedge
2124  // taken count for the loop. The exceptions are assumptions and
2125  // guards present in the loop -- SCEV is not great at exploiting
2126  // these to compute max backedge taken counts, but can still use
2127  // these to prove lack of overflow. Use this fact to avoid
2128  // doing extra work that may not pay off.
2129 
2130  if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
2131  !AC.assumptions().empty()) {
2132  // If the backedge is guarded by a comparison with the pre-inc
2133  // value the addrec is safe. Also, if the entry is guarded by
2134  // a comparison with the start value and the backedge is
2135  // guarded by a comparison with the post-inc value, the addrec
2136  // is safe.
2137  ICmpInst::Predicate Pred;
2138  const SCEV *OverflowLimit =
2139  getSignedOverflowLimitForStep(Step, &Pred, this);
2140  if (OverflowLimit &&
2141  (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
2142  isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
2143  // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2144  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2145  return getAddRecExpr(
2146  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2147  getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2148  }
2149  }
2150 
2151  // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2152  // if D + (C - D + Step * n) could be proven to not signed wrap
2153  // where D maximizes the number of trailing zeros of (C - D + Step * n)
2154  if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2155  const APInt &C = SC->getAPInt();
2156  const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2157  if (D != 0) {
2158  const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2159  const SCEV *SResidual =
2160  getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2161  const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2162  return getAddExpr(SSExtD, SSExtR,
2164  Depth + 1);
2165  }
2166  }
2167 
2168  if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2169  const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2170  return getAddRecExpr(
2171  getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2172  getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2173  }
2174  }
2175 
2176  // If the input value is provably positive and we could not simplify
2177  // away the sext build a zext instead.
2178  if (isKnownNonNegative(Op))
2179  return getZeroExtendExpr(Op, Ty, Depth + 1);
2180 
2181  // The cast wasn't folded; create an explicit cast node.
2182  // Recompute the insert position, as it may have been invalidated.
2183  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2184  SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2185  Op, Ty);
2186  UniqueSCEVs.InsertNode(S, IP);
2187  addToLoopUseLists(S);
2188  return S;
2189 }
2190 
2191 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2192 /// unspecified bits out to the given type.
2194  Type *Ty) {
2195  assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2196  "This is not an extending conversion!");
2197  assert(isSCEVable(Ty) &&
2198  "This is not a conversion to a SCEVable type!");
2199  Ty = getEffectiveSCEVType(Ty);
2200 
2201  // Sign-extend negative constants.
2202  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2203  if (SC->getAPInt().isNegative())
2204  return getSignExtendExpr(Op, Ty);
2205 
2206  // Peel off a truncate cast.
2207  if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2208  const SCEV *NewOp = T->getOperand();
2209  if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2210  return getAnyExtendExpr(NewOp, Ty);
2211  return getTruncateOrNoop(NewOp, Ty);
2212  }
2213 
2214  // Next try a zext cast. If the cast is folded, use it.
2215  const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2216  if (!isa<SCEVZeroExtendExpr>(ZExt))
2217  return ZExt;
2218 
2219  // Next try a sext cast. If the cast is folded, use it.
2220  const SCEV *SExt = getSignExtendExpr(Op, Ty);
2221  if (!isa<SCEVSignExtendExpr>(SExt))
2222  return SExt;
2223 
2224  // Force the cast to be folded into the operands of an addrec.
2225  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2227  for (const SCEV *Op : AR->operands())
2228  Ops.push_back(getAnyExtendExpr(Op, Ty));
2229  return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2230  }
2231 
2232  // If the expression is obviously signed, use the sext cast value.
2233  if (isa<SCEVSMaxExpr>(Op))
2234  return SExt;
2235 
2236  // Absent any other information, use the zext cast value.
2237  return ZExt;
2238 }
2239 
2240 /// Process the given Ops list, which is a list of operands to be added under
2241 /// the given scale, update the given map. This is a helper function for
2242 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2243 /// that would form an add expression like this:
2244 ///
2245 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2246 ///
2247 /// where A and B are constants, update the map with these values:
2248 ///
2249 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2250 ///
2251 /// and add 13 + A*B*29 to AccumulatedConstant.
2252 /// This will allow getAddRecExpr to produce this:
2253 ///
2254 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2255 ///
2256 /// This form often exposes folding opportunities that are hidden in
2257 /// the original operand list.
2258 ///
2259 /// Return true iff it appears that any interesting folding opportunities
2260 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2261 /// the common case where no interesting opportunities are present, and
2262 /// is also used as a check to avoid infinite recursion.
2263 static bool
2266  APInt &AccumulatedConstant,
2267  const SCEV *const *Ops, size_t NumOperands,
2268  const APInt &Scale,
2269  ScalarEvolution &SE) {
2270  bool Interesting = false;
2271 
2272  // Iterate over the add operands. They are sorted, with constants first.
2273  unsigned i = 0;
2274  while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2275  ++i;
2276  // Pull a buried constant out to the outside.
2277  if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2278  Interesting = true;
2279  AccumulatedConstant += Scale * C->getAPInt();
2280  }
2281 
2282  // Next comes everything else. We're especially interested in multiplies
2283  // here, but they're in the middle, so just visit the rest with one loop.
2284  for (; i != NumOperands; ++i) {
2285  const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2286  if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2287  APInt NewScale =
2288  Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2289  if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2290  // A multiplication of a constant with another add; recurse.
2291  const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2292  Interesting |=
2293  CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2294  Add->op_begin(), Add->getNumOperands(),
2295  NewScale, SE);
2296  } else {
2297  // A multiplication of a constant with some other value. Update
2298  // the map.
2299  SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2300  const SCEV *Key = SE.getMulExpr(MulOps);
2301  auto Pair = M.insert({Key, NewScale});
2302  if (Pair.second) {
2303  NewOps.push_back(Pair.first->first);
2304  } else {
2305  Pair.first->second += NewScale;
2306  // The map already had an entry for this value, which may indicate
2307  // a folding opportunity.
2308  Interesting = true;
2309  }
2310  }
2311  } else {
2312  // An ordinary operand. Update the map.
2313  std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2314  M.insert({Ops[i], Scale});
2315  if (Pair.second) {
2316  NewOps.push_back(Pair.first->first);
2317  } else {
2318  Pair.first->second += Scale;
2319  // The map already had an entry for this value, which may indicate
2320  // a folding opportunity.
2321  Interesting = true;
2322  }
2323  }
2324  }
2325 
2326  return Interesting;
2327 }
2328 
2329 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2330 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2331 // can't-overflow flags for the operation if possible.
2332 static SCEV::NoWrapFlags
2334  const ArrayRef<const SCEV *> Ops,
2335  SCEV::NoWrapFlags Flags) {
2336  using namespace std::placeholders;
2337 
2338  using OBO = OverflowingBinaryOperator;
2339 
2340  bool CanAnalyze =
2341  Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2342  (void)CanAnalyze;
2343  assert(CanAnalyze && "don't call from other places!");
2344 
2345  int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2346  SCEV::NoWrapFlags SignOrUnsignWrap =
2347  ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2348 
2349  // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2350  auto IsKnownNonNegative = [&](const SCEV *S) {
2351  return SE->isKnownNonNegative(S);
2352  };
2353 
2354  if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2355  Flags =
2356  ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2357 
2358  SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2359 
2360  if (SignOrUnsignWrap != SignOrUnsignMask &&
2361  (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2362  isa<SCEVConstant>(Ops[0])) {
2363 
2364  auto Opcode = [&] {
2365  switch (Type) {
2366  case scAddExpr:
2367  return Instruction::Add;
2368  case scMulExpr:
2369  return Instruction::Mul;
2370  default:
2371  llvm_unreachable("Unexpected SCEV op.");
2372  }
2373  }();
2374 
2375  const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2376 
2377  // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2378  if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2380  Opcode, C, OBO::NoSignedWrap);
2381  if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2382  Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2383  }
2384 
2385  // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2386  if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2388  Opcode, C, OBO::NoUnsignedWrap);
2389  if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2390  Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2391  }
2392  }
2393 
2394  return Flags;
2395 }
2396 
2398  return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2399 }
2400 
2401 /// Get a canonical add expression, or something simpler if possible.
2403  SCEV::NoWrapFlags Flags,
2404  unsigned Depth) {
2405  assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2406  "only nuw or nsw allowed");
2407  assert(!Ops.empty() && "Cannot get empty add!");
2408  if (Ops.size() == 1) return Ops[0];
2409 #ifndef NDEBUG
2410  Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2411  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2412  assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2413  "SCEVAddExpr operand types don't match!");
2414 #endif
2415 
2416  // Sort by complexity, this groups all similar expression types together.
2417  GroupByComplexity(Ops, &LI, DT);
2418 
2419  Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2420 
2421  // If there are any constants, fold them together.
2422  unsigned Idx = 0;
2423  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2424  ++Idx;
2425  assert(Idx < Ops.size());
2426  while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2427  // We found two constants, fold them together!
2428  Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2429  if (Ops.size() == 2) return Ops[0];
2430  Ops.erase(Ops.begin()+1); // Erase the folded element
2431  LHSC = cast<SCEVConstant>(Ops[0]);
2432  }
2433 
2434  // If we are left with a constant zero being added, strip it off.
2435  if (LHSC->getValue()->isZero()) {
2436  Ops.erase(Ops.begin());
2437  --Idx;
2438  }
2439 
2440  if (Ops.size() == 1) return Ops[0];
2441  }
2442 
2443  // Limit recursion calls depth.
2444  if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2445  return getOrCreateAddExpr(Ops, Flags);
2446 
2447  // Okay, check to see if the same value occurs in the operand list more than
2448  // once. If so, merge them together into an multiply expression. Since we
2449  // sorted the list, these values are required to be adjacent.
2450  Type *Ty = Ops[0]->getType();
2451  bool FoundMatch = false;
2452  for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2453  if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2454  // Scan ahead to count how many equal operands there are.
2455  unsigned Count = 2;
2456  while (i+Count != e && Ops[i+Count] == Ops[i])
2457  ++Count;
2458  // Merge the values into a multiply.
2459  const SCEV *Scale = getConstant(Ty, Count);
2460  const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2461  if (Ops.size() == Count)
2462  return Mul;
2463  Ops[i] = Mul;
2464  Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2465  --i; e -= Count - 1;
2466  FoundMatch = true;
2467  }
2468  if (FoundMatch)
2469  return getAddExpr(Ops, Flags, Depth + 1);
2470 
2471  // Check for truncates. If all the operands are truncated from the same
2472  // type, see if factoring out the truncate would permit the result to be
2473  // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2474  // if the contents of the resulting outer trunc fold to something simple.
2475  auto FindTruncSrcType = [&]() -> Type * {
2476  // We're ultimately looking to fold an addrec of truncs and muls of only
2477  // constants and truncs, so if we find any other types of SCEV
2478  // as operands of the addrec then we bail and return nullptr here.
2479  // Otherwise, we return the type of the operand of a trunc that we find.
2480  if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2481  return T->getOperand()->getType();
2482  if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2483  const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2484  if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2485  return T->getOperand()->getType();
2486  }
2487  return nullptr;
2488  };
2489  if (auto *SrcType = FindTruncSrcType()) {
2491  bool Ok = true;
2492  // Check all the operands to see if they can be represented in the
2493  // source type of the truncate.
2494  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2495  if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2496  if (T->getOperand()->getType() != SrcType) {
2497  Ok = false;
2498  break;
2499  }
2500  LargeOps.push_back(T->getOperand());
2501  } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2502  LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2503  } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2504  SmallVector<const SCEV *, 8> LargeMulOps;
2505  for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2506  if (const SCEVTruncateExpr *T =
2507  dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2508  if (T->getOperand()->getType() != SrcType) {
2509  Ok = false;
2510  break;
2511  }
2512  LargeMulOps.push_back(T->getOperand());
2513  } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2514  LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2515  } else {
2516  Ok = false;
2517  break;
2518  }
2519  }
2520  if (Ok)
2521  LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2522  } else {
2523  Ok = false;
2524  break;
2525  }
2526  }
2527  if (Ok) {
2528  // Evaluate the expression in the larger type.
2529  const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2530  // If it folds to something simple, use it. Otherwise, don't.
2531  if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2532  return getTruncateExpr(Fold, Ty);
2533  }
2534  }
2535 
2536  // Skip past any other cast SCEVs.
2537  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2538  ++Idx;
2539 
2540  // If there are add operands they would be next.
2541  if (Idx < Ops.size()) {
2542  bool DeletedAdd = false;
2543  while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2544  if (Ops.size() > AddOpsInlineThreshold ||
2545  Add->getNumOperands() > AddOpsInlineThreshold)
2546  break;
2547  // If we have an add, expand the add operands onto the end of the operands
2548  // list.
2549  Ops.erase(Ops.begin()+Idx);
2550  Ops.append(Add->op_begin(), Add->op_end());
2551  DeletedAdd = true;
2552  }
2553 
2554  // If we deleted at least one add, we added operands to the end of the list,
2555  // and they are not necessarily sorted. Recurse to resort and resimplify
2556  // any operands we just acquired.
2557  if (DeletedAdd)
2558  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2559  }
2560 
2561  // Skip over the add expression until we get to a multiply.
2562  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2563  ++Idx;
2564 
2565  // Check to see if there are any folding opportunities present with
2566  // operands multiplied by constant values.
2567  if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2568  uint64_t BitWidth = getTypeSizeInBits(Ty);
2571  APInt AccumulatedConstant(BitWidth, 0);
2572  if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2573  Ops.data(), Ops.size(),
2574  APInt(BitWidth, 1), *this)) {
2575  struct APIntCompare {
2576  bool operator()(const APInt &LHS, const APInt &RHS) const {
2577  return LHS.ult(RHS);
2578  }
2579  };
2580 
2581  // Some interesting folding opportunity is present, so its worthwhile to
2582  // re-generate the operands list. Group the operands by constant scale,
2583  // to avoid multiplying by the same constant scale multiple times.
2584  std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2585  for (const SCEV *NewOp : NewOps)
2586  MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2587  // Re-generate the operands list.
2588  Ops.clear();
2589  if (AccumulatedConstant != 0)
2590  Ops.push_back(getConstant(AccumulatedConstant));
2591  for (auto &MulOp : MulOpLists)
2592  if (MulOp.first != 0)
2593  Ops.push_back(getMulExpr(
2594  getConstant(MulOp.first),
2595  getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2596  SCEV::FlagAnyWrap, Depth + 1));
2597  if (Ops.empty())
2598  return getZero(Ty);
2599  if (Ops.size() == 1)
2600  return Ops[0];
2601  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2602  }
2603  }
2604 
2605  // If we are adding something to a multiply expression, make sure the
2606  // something is not already an operand of the multiply. If so, merge it into
2607  // the multiply.
2608  for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2609  const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2610  for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2611  const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2612  if (isa<SCEVConstant>(MulOpSCEV))
2613  continue;
2614  for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2615  if (MulOpSCEV == Ops[AddOp]) {
2616  // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2617  const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2618  if (Mul->getNumOperands() != 2) {
2619  // If the multiply has more than two operands, we must get the
2620  // Y*Z term.
2621  SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2622  Mul->op_begin()+MulOp);
2623  MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2624  InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2625  }
2626  SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2627  const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2628  const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2629  SCEV::FlagAnyWrap, Depth + 1);
2630  if (Ops.size() == 2) return OuterMul;
2631  if (AddOp < Idx) {
2632  Ops.erase(Ops.begin()+AddOp);
2633  Ops.erase(Ops.begin()+Idx-1);
2634  } else {
2635  Ops.erase(Ops.begin()+Idx);
2636  Ops.erase(Ops.begin()+AddOp-1);
2637  }
2638  Ops.push_back(OuterMul);
2639  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2640  }
2641 
2642  // Check this multiply against other multiplies being added together.
2643  for (unsigned OtherMulIdx = Idx+1;
2644  OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2645  ++OtherMulIdx) {
2646  const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2647  // If MulOp occurs in OtherMul, we can fold the two multiplies
2648  // together.
2649  for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2650  OMulOp != e; ++OMulOp)
2651  if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2652  // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2653  const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2654  if (Mul->getNumOperands() != 2) {
2655  SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2656  Mul->op_begin()+MulOp);
2657  MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2658  InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2659  }
2660  const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2661  if (OtherMul->getNumOperands() != 2) {
2662  SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2663  OtherMul->op_begin()+OMulOp);
2664  MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2665  InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2666  }
2667  SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2668  const SCEV *InnerMulSum =
2669  getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2670  const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2671  SCEV::FlagAnyWrap, Depth + 1);
2672  if (Ops.size() == 2) return OuterMul;
2673  Ops.erase(Ops.begin()+Idx);
2674  Ops.erase(Ops.begin()+OtherMulIdx-1);
2675  Ops.push_back(OuterMul);
2676  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2677  }
2678  }
2679  }
2680  }
2681 
2682  // If there are any add recurrences in the operands list, see if any other
2683  // added values are loop invariant. If so, we can fold them into the
2684  // recurrence.
2685  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2686  ++Idx;
2687 
2688  // Scan over all recurrences, trying to fold loop invariants into them.
2689  for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2690  // Scan all of the other operands to this add and add them to the vector if
2691  // they are loop invariant w.r.t. the recurrence.
2693  const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2694  const Loop *AddRecLoop = AddRec->getLoop();
2695  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2696  if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2697  LIOps.push_back(Ops[i]);
2698  Ops.erase(Ops.begin()+i);
2699  --i; --e;
2700  }
2701 
2702  // If we found some loop invariants, fold them into the recurrence.
2703  if (!LIOps.empty()) {
2704  // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2705  LIOps.push_back(AddRec->getStart());
2706 
2707  SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2708  AddRec->op_end());
2709  // This follows from the fact that the no-wrap flags on the outer add
2710  // expression are applicable on the 0th iteration, when the add recurrence
2711  // will be equal to its start value.
2712  AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2713 
2714  // Build the new addrec. Propagate the NUW and NSW flags if both the
2715  // outer add and the inner addrec are guaranteed to have no overflow.
2716  // Always propagate NW.
2717  Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2718  const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2719 
2720  // If all of the other operands were loop invariant, we are done.
2721  if (Ops.size() == 1) return NewRec;
2722 
2723  // Otherwise, add the folded AddRec by the non-invariant parts.
2724  for (unsigned i = 0;; ++i)
2725  if (Ops[i] == AddRec) {
2726  Ops[i] = NewRec;
2727  break;
2728  }
2729  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2730  }
2731 
2732  // Okay, if there weren't any loop invariants to be folded, check to see if
2733  // there are multiple AddRec's with the same loop induction variable being
2734  // added together. If so, we can fold them.
2735  for (unsigned OtherIdx = Idx+1;
2736  OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2737  ++OtherIdx) {
2738  // We expect the AddRecExpr's to be sorted in reverse dominance order,
2739  // so that the 1st found AddRecExpr is dominated by all others.
2740  assert(DT.dominates(
2741  cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2742  AddRec->getLoop()->getHeader()) &&
2743  "AddRecExprs are not sorted in reverse dominance order?");
2744  if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2745  // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2746  SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2747  AddRec->op_end());
2748  for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2749  ++OtherIdx) {
2750  const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2751  if (OtherAddRec->getLoop() == AddRecLoop) {
2752  for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2753  i != e; ++i) {
2754  if (i >= AddRecOps.size()) {
2755  AddRecOps.append(OtherAddRec->op_begin()+i,
2756  OtherAddRec->op_end());
2757  break;
2758  }
2759  SmallVector<const SCEV *, 2> TwoOps = {
2760  AddRecOps[i], OtherAddRec->getOperand(i)};
2761  AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2762  }
2763  Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2764  }
2765  }
2766  // Step size has changed, so we cannot guarantee no self-wraparound.
2767  Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2768  return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2769  }
2770  }
2771 
2772  // Otherwise couldn't fold anything into this recurrence. Move onto the
2773  // next one.
2774  }
2775 
2776  // Okay, it looks like we really DO need an add expr. Check to see if we
2777  // already have one, otherwise create a new one.
2778  return getOrCreateAddExpr(Ops, Flags);
2779 }
2780 
2781 const SCEV *
2782 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2783  SCEV::NoWrapFlags Flags) {
2785  ID.AddInteger(scAddExpr);
2786  for (const SCEV *Op : Ops)
2787  ID.AddPointer(Op);
2788  void *IP = nullptr;
2789  SCEVAddExpr *S =
2790  static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2791  if (!S) {
2792  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2793  std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2794  S = new (SCEVAllocator)
2795  SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2796  UniqueSCEVs.InsertNode(S, IP);
2797  addToLoopUseLists(S);
2798  }
2799  S->setNoWrapFlags(Flags);
2800  return S;
2801 }
2802 
2803 const SCEV *
2804 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2805  const Loop *L, SCEV::NoWrapFlags Flags) {
2808  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2809  ID.AddPointer(Ops[i]);
2810  ID.AddPointer(L);
2811  void *IP = nullptr;
2812  SCEVAddRecExpr *S =
2813  static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2814  if (!S) {
2815  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2816  std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2817  S = new (SCEVAllocator)
2818  SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2819  UniqueSCEVs.InsertNode(S, IP);
2820  addToLoopUseLists(S);
2821  }
2822  S->setNoWrapFlags(Flags);
2823  return S;
2824 }
2825 
2826 const SCEV *
2827 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2828  SCEV::NoWrapFlags Flags) {
2830  ID.AddInteger(scMulExpr);
2831  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2832  ID.AddPointer(Ops[i]);
2833  void *IP = nullptr;
2834  SCEVMulExpr *S =
2835  static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2836  if (!S) {
2837  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2838  std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2839  S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2840  O, Ops.size());
2841  UniqueSCEVs.InsertNode(S, IP);
2842  addToLoopUseLists(S);
2843  }
2844  S->setNoWrapFlags(Flags);
2845  return S;
2846 }
2847 
2848 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2849  uint64_t k = i*j;
2850  if (j > 1 && k / j != i) Overflow = true;
2851  return k;
2852 }
2853 
2854 /// Compute the result of "n choose k", the binomial coefficient. If an
2855 /// intermediate computation overflows, Overflow will be set and the return will
2856 /// be garbage. Overflow is not cleared on absence of overflow.
2857 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2858  // We use the multiplicative formula:
2859  // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2860  // At each iteration, we take the n-th term of the numeral and divide by the
2861  // (k-n)th term of the denominator. This division will always produce an
2862  // integral result, and helps reduce the chance of overflow in the
2863  // intermediate computations. However, we can still overflow even when the
2864  // final result would fit.
2865 
2866  if (n == 0 || n == k) return 1;
2867  if (k > n) return 0;
2868 
2869  if (k > n/2)
2870  k = n-k;
2871 
2872  uint64_t r = 1;
2873  for (uint64_t i = 1; i <= k; ++i) {
2874  r = umul_ov(r, n-(i-1), Overflow);
2875  r /= i;
2876  }
2877  return r;
2878 }
2879 
2880 /// Determine if any of the operands in this SCEV are a constant or if
2881 /// any of the add or multiply expressions in this SCEV contain a constant.
2882 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2883  struct FindConstantInAddMulChain {
2884  bool FoundConstant = false;
2885 
2886  bool follow(const SCEV *S) {
2887  FoundConstant |= isa<SCEVConstant>(S);
2888  return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2889  }
2890 
2891  bool isDone() const {
2892  return FoundConstant;
2893  }
2894  };
2895 
2896  FindConstantInAddMulChain F;
2898  ST.visitAll(StartExpr);
2899  return F.FoundConstant;
2900 }
2901 
2902 /// Get a canonical multiply expression, or something simpler if possible.
2904  SCEV::NoWrapFlags Flags,
2905  unsigned Depth) {
2906  assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2907  "only nuw or nsw allowed");
2908  assert(!Ops.empty() && "Cannot get empty mul!");
2909  if (Ops.size() == 1) return Ops[0];
2910 #ifndef NDEBUG
2911  Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2912  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2913  assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2914  "SCEVMulExpr operand types don't match!");
2915 #endif
2916 
2917  // Sort by complexity, this groups all similar expression types together.
2918  GroupByComplexity(Ops, &LI, DT);
2919 
2920  Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2921 
2922  // Limit recursion calls depth.
2923  if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2924  return getOrCreateMulExpr(Ops, Flags);
2925 
2926  // If there are any constants, fold them together.
2927  unsigned Idx = 0;
2928  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2929 
2930  if (Ops.size() == 2)
2931  // C1*(C2+V) -> C1*C2 + C1*V
2932  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2933  // If any of Add's ops are Adds or Muls with a constant, apply this
2934  // transformation as well.
2935  //
2936  // TODO: There are some cases where this transformation is not
2937  // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
2938  // this transformation should be narrowed down.
2939  if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2940  return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2941  SCEV::FlagAnyWrap, Depth + 1),
2942  getMulExpr(LHSC, Add->getOperand(1),
2943  SCEV::FlagAnyWrap, Depth + 1),
2944  SCEV::FlagAnyWrap, Depth + 1);
2945 
2946  ++Idx;
2947  while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2948  // We found two constants, fold them together!
2949  ConstantInt *Fold =
2950  ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2951  Ops[0] = getConstant(Fold);
2952  Ops.erase(Ops.begin()+1); // Erase the folded element
2953  if (Ops.size() == 1) return Ops[0];
2954  LHSC = cast<SCEVConstant>(Ops[0]);
2955  }
2956 
2957  // If we are left with a constant one being multiplied, strip it off.
2958  if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2959  Ops.erase(Ops.begin());
2960  --Idx;
2961  } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2962  // If we have a multiply of zero, it will always be zero.
2963  return Ops[0];
2964  } else if (Ops[0]->isAllOnesValue()) {
2965  // If we have a mul by -1 of an add, try distributing the -1 among the
2966  // add operands.
2967  if (Ops.size() == 2) {
2968  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2970  bool AnyFolded = false;
2971  for (const SCEV *AddOp : Add->operands()) {
2972  const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2973  Depth + 1);
2974  if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2975  NewOps.push_back(Mul);
2976  }
2977  if (AnyFolded)
2978  return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2979  } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2980  // Negation preserves a recurrence's no self-wrap property.
2982  for (const SCEV *AddRecOp : AddRec->operands())
2983  Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2984  Depth + 1));
2985 
2986  return getAddRecExpr(Operands, AddRec->getLoop(),
2987  AddRec->getNoWrapFlags(SCEV::FlagNW));
2988  }
2989  }
2990  }
2991 
2992  if (Ops.size() == 1)
2993  return Ops[0];
2994  }
2995 
2996  // Skip over the add expression until we get to a multiply.
2997  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2998  ++Idx;
2999 
3000  // If there are mul operands inline them all into this expression.
3001  if (Idx < Ops.size()) {
3002  bool DeletedMul = false;
3003  while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3004  if (Ops.size() > MulOpsInlineThreshold)
3005  break;
3006  // If we have an mul, expand the mul operands onto the end of the
3007  // operands list.
3008  Ops.erase(Ops.begin()+Idx);
3009  Ops.append(Mul->op_begin(), Mul->op_end());
3010  DeletedMul = true;
3011  }
3012 
3013  // If we deleted at least one mul, we added operands to the end of the
3014  // list, and they are not necessarily sorted. Recurse to resort and
3015  // resimplify any operands we just acquired.
3016  if (DeletedMul)
3017  return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3018  }
3019 
3020  // If there are any add recurrences in the operands list, see if any other
3021  // added values are loop invariant. If so, we can fold them into the
3022  // recurrence.
3023  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3024  ++Idx;
3025 
3026  // Scan over all recurrences, trying to fold loop invariants into them.
3027  for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3028  // Scan all of the other operands to this mul and add them to the vector
3029  // if they are loop invariant w.r.t. the recurrence.
3031  const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3032  const Loop *AddRecLoop = AddRec->getLoop();
3033  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3034  if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3035  LIOps.push_back(Ops[i]);
3036  Ops.erase(Ops.begin()+i);
3037  --i; --e;
3038  }
3039 
3040  // If we found some loop invariants, fold them into the recurrence.
3041  if (!LIOps.empty()) {
3042  // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3044  NewOps.reserve(AddRec->getNumOperands());
3045  const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3046  for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3047  NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3048  SCEV::FlagAnyWrap, Depth + 1));
3049 
3050  // Build the new addrec. Propagate the NUW and NSW flags if both the
3051  // outer mul and the inner addrec are guaranteed to have no overflow.
3052  //
3053  // No self-wrap cannot be guaranteed after changing the step size, but
3054  // will be inferred if either NUW or NSW is true.
3055  Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
3056  const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
3057 
3058  // If all of the other operands were loop invariant, we are done.
3059  if (Ops.size() == 1) return NewRec;
3060 
3061  // Otherwise, multiply the folded AddRec by the non-invariant parts.
3062  for (unsigned i = 0;; ++i)
3063  if (Ops[i] == AddRec) {
3064  Ops[i] = NewRec;
3065  break;
3066  }
3067  return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3068  }
3069 
3070  // Okay, if there weren't any loop invariants to be folded, check to see
3071  // if there are multiple AddRec's with the same loop induction variable
3072  // being multiplied together. If so, we can fold them.
3073 
3074  // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3075  // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3076  // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3077  // ]]],+,...up to x=2n}.
3078  // Note that the arguments to choose() are always integers with values
3079  // known at compile time, never SCEV objects.
3080  //
3081  // The implementation avoids pointless extra computations when the two
3082  // addrec's are of different length (mathematically, it's equivalent to
3083  // an infinite stream of zeros on the right).
3084  bool OpsModified = false;
3085  for (unsigned OtherIdx = Idx+1;
3086  OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3087  ++OtherIdx) {
3088  const SCEVAddRecExpr *OtherAddRec =
3089  dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3090  if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3091  continue;
3092 
3093  // Limit max number of arguments to avoid creation of unreasonably big
3094  // SCEVAddRecs with very complex operands.
3095  if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3096  MaxAddRecSize || isHugeExpression(AddRec) ||
3097  isHugeExpression(OtherAddRec))
3098  continue;
3099 
3100  bool Overflow = false;
3101  Type *Ty = AddRec->getType();
3102  bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3103  SmallVector<const SCEV*, 7> AddRecOps;
3104  for (int x = 0, xe = AddRec->getNumOperands() +
3105  OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3107  for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3108  uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3109  for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3110  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3111  z < ze && !Overflow; ++z) {
3112  uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3113  uint64_t Coeff;
3114  if (LargerThan64Bits)
3115  Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3116  else
3117  Coeff = Coeff1*Coeff2;
3118  const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3119  const SCEV *Term1 = AddRec->getOperand(y-z);
3120  const SCEV *Term2 = OtherAddRec->getOperand(z);
3121  SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3122  SCEV::FlagAnyWrap, Depth + 1));
3123  }
3124  }
3125  if (SumOps.empty())
3126  SumOps.push_back(getZero(Ty));
3127  AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3128  }
3129  if (!Overflow) {
3130  const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3132  if (Ops.size() == 2) return NewAddRec;
3133  Ops[Idx] = NewAddRec;
3134  Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3135  OpsModified = true;
3136  AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3137  if (!AddRec)
3138  break;
3139  }
3140  }
3141  if (OpsModified)
3142  return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3143 
3144  // Otherwise couldn't fold anything into this recurrence. Move onto the
3145  // next one.
3146  }
3147 
3148  // Okay, it looks like we really DO need an mul expr. Check to see if we
3149  // already have one, otherwise create a new one.
3150  return getOrCreateMulExpr(Ops, Flags);
3151 }
3152 
3153 /// Represents an unsigned remainder expression based on unsigned division.
3155  const SCEV *RHS) {
3156  assert(getEffectiveSCEVType(LHS->getType()) ==
3157  getEffectiveSCEVType(RHS->getType()) &&
3158  "SCEVURemExpr operand types don't match!");
3159 
3160  // Short-circuit easy cases
3161  if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3162  // If constant is one, the result is trivial
3163  if (RHSC->getValue()->isOne())
3164  return getZero(LHS->getType()); // X urem 1 --> 0
3165 
3166  // If constant is a power of two, fold into a zext(trunc(LHS)).
3167  if (RHSC->getAPInt().isPowerOf2()) {
3168  Type *FullTy = LHS->getType();
3169  Type *TruncTy =
3170  IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3171  return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3172  }
3173  }
3174 
3175  // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3176  const SCEV *UDiv = getUDivExpr(LHS, RHS);
3177  const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3178  return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3179 }
3180 
3181 /// Get a canonical unsigned division expression, or something simpler if
3182 /// possible.
3184  const SCEV *RHS) {
3185  assert(getEffectiveSCEVType(LHS->getType()) ==
3186  getEffectiveSCEVType(RHS->getType()) &&
3187  "SCEVUDivExpr operand types don't match!");
3188 
3189  if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3190  if (RHSC->getValue()->isOne())
3191  return LHS; // X udiv 1 --> x
3192  // If the denominator is zero, the result of the udiv is undefined. Don't
3193  // try to analyze it, because the resolution chosen here may differ from
3194  // the resolution chosen in other parts of the compiler.
3195  if (!RHSC->getValue()->isZero()) {
3196  // Determine if the division can be folded into the operands of
3197  // its operands.
3198  // TODO: Generalize this to non-constants by using known-bits information.
3199  Type *Ty = LHS->getType();
3200  unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3201  unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3202  // For non-power-of-two values, effectively round the value up to the
3203  // nearest power of two.
3204  if (!RHSC->getAPInt().isPowerOf2())
3205  ++MaxShiftAmt;
3206  IntegerType *ExtTy =
3207  IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3208  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3209  if (const SCEVConstant *Step =
3210  dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3211  // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3212  const APInt &StepInt = Step->getAPInt();
3213  const APInt &DivInt = RHSC->getAPInt();
3214  if (!StepInt.urem(DivInt) &&
3215  getZeroExtendExpr(AR, ExtTy) ==
3216  getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3217  getZeroExtendExpr(Step, ExtTy),
3218  AR->getLoop(), SCEV::FlagAnyWrap)) {
3220  for (const SCEV *Op : AR->operands())
3221  Operands.push_back(getUDivExpr(Op, RHS));
3222  return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3223  }
3224  /// Get a canonical UDivExpr for a recurrence.
3225  /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3226  // We can currently only fold X%N if X is constant.
3227  const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3228  if (StartC && !DivInt.urem(StepInt) &&
3229  getZeroExtendExpr(AR, ExtTy) ==
3230  getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3231  getZeroExtendExpr(Step, ExtTy),
3232  AR->getLoop(), SCEV::FlagAnyWrap)) {
3233  const APInt &StartInt = StartC->getAPInt();
3234  const APInt &StartRem = StartInt.urem(StepInt);
3235  if (StartRem != 0)
3236  LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3237  AR->getLoop(), SCEV::FlagNW);
3238  }
3239  }
3240  // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3241  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3243  for (const SCEV *Op : M->operands())
3244  Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3245  if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3246  // Find an operand that's safely divisible.
3247  for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3248  const SCEV *Op = M->getOperand(i);
3249  const SCEV *Div = getUDivExpr(Op, RHSC);
3250  if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3251  Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3252  M->op_end());
3253  Operands[i] = Div;
3254  return getMulExpr(Operands);
3255  }
3256  }
3257  }
3258 
3259  // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3260  if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3261  if (auto *DivisorConstant =
3262  dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3263  bool Overflow = false;
3264  APInt NewRHS =
3265  DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3266  if (Overflow) {
3267  return getConstant(RHSC->getType(), 0, false);
3268  }
3269  return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3270  }
3271  }
3272 
3273  // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3274  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3276  for (const SCEV *Op : A->operands())
3277  Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3278  if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3279  Operands.clear();
3280  for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3281  const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3282  if (isa<SCEVUDivExpr>(Op) ||
3283  getMulExpr(Op, RHS) != A->getOperand(i))
3284  break;
3285  Operands.push_back(Op);
3286  }
3287  if (Operands.size() == A->getNumOperands())
3288  return getAddExpr(Operands);
3289  }
3290  }
3291 
3292  // Fold if both operands are constant.
3293  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3294  Constant *LHSCV = LHSC->getValue();
3295  Constant *RHSCV = RHSC->getValue();
3296  return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3297  RHSCV)));
3298  }
3299  }
3300  }
3301 
3303  ID.AddInteger(scUDivExpr);
3304  ID.AddPointer(LHS);
3305  ID.AddPointer(RHS);
3306  void *IP = nullptr;
3307  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3308  SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3309  LHS, RHS);
3310  UniqueSCEVs.InsertNode(S, IP);
3311  addToLoopUseLists(S);
3312  return S;
3313 }
3314 
3315 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3316  APInt A = C1->getAPInt().abs();
3317  APInt B = C2->getAPInt().abs();
3318  uint32_t ABW = A.getBitWidth();
3319  uint32_t BBW = B.getBitWidth();
3320 
3321  if (ABW > BBW)
3322  B = B.zext(ABW);
3323  else if (ABW < BBW)
3324  A = A.zext(BBW);
3325 
3326  return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3327 }
3328 
3329 /// Get a canonical unsigned division expression, or something simpler if
3330 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3331 /// can attempt to remove factors from the LHS and RHS. We can't do this when
3332 /// it's not exact because the udiv may be clearing bits.
3334  const SCEV *RHS) {
3335  // TODO: we could try to find factors in all sorts of things, but for now we
3336  // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3337  // end of this file for inspiration.
3338 
3339  const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3340  if (!Mul || !Mul->hasNoUnsignedWrap())
3341  return getUDivExpr(LHS, RHS);
3342 
3343  if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3344  // If the mulexpr multiplies by a constant, then that constant must be the
3345  // first element of the mulexpr.
3346  if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3347  if (LHSCst == RHSCst) {
3349  Operands.append(Mul->op_begin() + 1, Mul->op_end());
3350  return getMulExpr(Operands);
3351  }
3352 
3353  // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3354  // that there's a factor provided by one of the other terms. We need to
3355  // check.
3356  APInt Factor = gcd(LHSCst, RHSCst);
3357  if (!Factor.isIntN(1)) {
3358  LHSCst =
3359  cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3360  RHSCst =
3361  cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3363  Operands.push_back(LHSCst);
3364  Operands.append(Mul->op_begin() + 1, Mul->op_end());
3365  LHS = getMulExpr(Operands);
3366  RHS = RHSCst;
3367  Mul = dyn_cast<SCEVMulExpr>(LHS);
3368  if (!Mul)
3369  return getUDivExactExpr(LHS, RHS);
3370  }
3371  }
3372  }
3373 
3374  for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3375  if (Mul->getOperand(i) == RHS) {
3377  Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3378  Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3379  return getMulExpr(Operands);
3380  }
3381  }
3382 
3383  return getUDivExpr(LHS, RHS);
3384 }
3385 
3386 /// Get an add recurrence expression for the specified loop. Simplify the
3387 /// expression as much as possible.
3388 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3389  const Loop *L,
3390  SCEV::NoWrapFlags Flags) {
3392  Operands.push_back(Start);
3393  if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3394  if (StepChrec->getLoop() == L) {
3395  Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3396  return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3397  }
3398 
3399  Operands.push_back(Step);
3400  return getAddRecExpr(Operands, L, Flags);
3401 }
3402 
3403 /// Get an add recurrence expression for the specified loop. Simplify the
3404 /// expression as much as possible.
3405 const SCEV *
3407  const Loop *L, SCEV::NoWrapFlags Flags) {
3408  if (Operands.size() == 1) return Operands[0];
3409 #ifndef NDEBUG
3410  Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3411  for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3412  assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3413  "SCEVAddRecExpr operand types don't match!");
3414  for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3415  assert(isLoopInvariant(Operands[i], L) &&
3416  "SCEVAddRecExpr operand is not loop-invariant!");
3417 #endif
3418 
3419  if (Operands.back()->isZero()) {
3420  Operands.pop_back();
3421  return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3422  }
3423 
3424  // It's tempting to want to call getMaxBackedgeTakenCount count here and
3425  // use that information to infer NUW and NSW flags. However, computing a
3426  // BE count requires calling getAddRecExpr, so we may not yet have a
3427  // meaningful BE count at this point (and if we don't, we'd be stuck
3428  // with a SCEVCouldNotCompute as the cached BE count).
3429 
3430  Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3431 
3432  // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3433  if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3434  const Loop *NestedLoop = NestedAR->getLoop();
3435  if (L->contains(NestedLoop)
3436  ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3437  : (!NestedLoop->contains(L) &&
3438  DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3439  SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3440  NestedAR->op_end());
3441  Operands[0] = NestedAR->getStart();
3442  // AddRecs require their operands be loop-invariant with respect to their
3443  // loops. Don't perform this transformation if it would break this
3444  // requirement.
3445  bool AllInvariant = all_of(
3446  Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3447 
3448  if (AllInvariant) {
3449  // Create a recurrence for the outer loop with the same step size.
3450  //
3451  // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3452  // inner recurrence has the same property.
3453  SCEV::NoWrapFlags OuterFlags =
3454  maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3455 
3456  NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3457  AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3458  return isLoopInvariant(Op, NestedLoop);
3459  });
3460 
3461  if (AllInvariant) {
3462  // Ok, both add recurrences are valid after the transformation.
3463  //
3464  // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3465  // the outer recurrence has the same property.
3466  SCEV::NoWrapFlags InnerFlags =
3467  maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3468  return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3469  }
3470  }
3471  // Reset Operands to its original state.
3472  Operands[0] = NestedAR;
3473  }
3474  }
3475 
3476  // Okay, it looks like we really DO need an addrec expr. Check to see if we
3477  // already have one, otherwise create a new one.
3478  return getOrCreateAddRecExpr(Operands, L, Flags);
3479 }
3480 
3481 const SCEV *
3483  const SmallVectorImpl<const SCEV *> &IndexExprs) {
3484  const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3485  // getSCEV(Base)->getType() has the same address space as Base->getType()
3486  // because SCEV::getType() preserves the address space.
3487  Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3488  // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3489  // instruction to its SCEV, because the Instruction may be guarded by control
3490  // flow and the no-overflow bits may not be valid for the expression in any
3491  // context. This can be fixed similarly to how these flags are handled for
3492  // adds.
3495 
3496  const SCEV *TotalOffset = getZero(IntPtrTy);
3497  // The array size is unimportant. The first thing we do on CurTy is getting
3498  // its element type.
3499  Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3500  for (const SCEV *IndexExpr : IndexExprs) {
3501  // Compute the (potentially symbolic) offset in bytes for this index.
3502  if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3503  // For a struct, add the member offset.
3504  ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3505  unsigned FieldNo = Index->getZExtValue();
3506  const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3507 
3508  // Add the field offset to the running total offset.
3509  TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3510 
3511  // Update CurTy to the type of the field at Index.
3512  CurTy = STy->getTypeAtIndex(Index);
3513  } else {
3514  // Update CurTy to its element type.
3515  CurTy = cast<SequentialType>(CurTy)->getElementType();
3516  // For an array, add the element offset, explicitly scaled.
3517  const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3518  // Getelementptr indices are signed.
3519  IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3520 
3521  // Multiply the index by the element size to compute the element offset.
3522  const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3523 
3524  // Add the element offset to the running total offset.
3525  TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3526  }
3527  }
3528 
3529  // Add the total offset from all the GEP indices to the base.
3530  return getAddExpr(BaseExpr, TotalOffset, Wrap);
3531 }
3532 
3533 std::tuple<const SCEV *, FoldingSetNodeID, void *>
3534 ScalarEvolution::findExistingSCEVInCache(int SCEVType,
3535  ArrayRef<const SCEV *> Ops) {
3537  void *IP = nullptr;
3538  ID.AddInteger(SCEVType);
3539  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3540  ID.AddPointer(Ops[i]);
3541  return std::tuple<const SCEV *, FoldingSetNodeID, void *>(
3542  UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3543 }
3544 
3547  assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3548  if (Ops.size() == 1) return Ops[0];
3549 #ifndef NDEBUG
3550  Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3551  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3552  assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3553  "Operand types don't match!");
3554 #endif
3555 
3556  bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3557  bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3558 
3559  // Sort by complexity, this groups all similar expression types together.
3560  GroupByComplexity(Ops, &LI, DT);
3561 
3562  // Check if we have created the same expression before.
3563  if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3564  return S;
3565  }
3566 
3567  // If there are any constants, fold them together.
3568  unsigned Idx = 0;
3569  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3570  ++Idx;
3571  assert(Idx < Ops.size());
3572  auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3573  if (Kind == scSMaxExpr)
3574  return APIntOps::smax(LHS, RHS);
3575  else if (Kind == scSMinExpr)
3576  return APIntOps::smin(LHS, RHS);
3577  else if (Kind == scUMaxExpr)
3578  return APIntOps::umax(LHS, RHS);
3579  else if (Kind == scUMinExpr)
3580  return APIntOps::umin(LHS, RHS);
3581  llvm_unreachable("Unknown SCEV min/max opcode");
3582  };
3583 
3584  while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3585  // We found two constants, fold them together!
3586  ConstantInt *Fold = ConstantInt::get(
3587  getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3588  Ops[0] = getConstant(Fold);
3589  Ops.erase(Ops.begin()+1); // Erase the folded element
3590  if (Ops.size() == 1) return Ops[0];
3591  LHSC = cast<SCEVConstant>(Ops[0]);
3592  }
3593 
3594  bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3595  bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3596 
3597  if (IsMax ? IsMinV : IsMaxV) {
3598  // If we are left with a constant minimum(/maximum)-int, strip it off.
3599  Ops.erase(Ops.begin());
3600  --Idx;
3601  } else if (IsMax ? IsMaxV : IsMinV) {
3602  // If we have a max(/min) with a constant maximum(/minimum)-int,
3603  // it will always be the extremum.
3604  return LHSC;
3605  }
3606 
3607  if (Ops.size() == 1) return Ops[0];
3608  }
3609 
3610  // Find the first operation of the same kind
3611  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3612  ++Idx;
3613 
3614  // Check to see if one of the operands is of the same kind. If so, expand its
3615  // operands onto our operand list, and recurse to simplify.
3616  if (Idx < Ops.size()) {
3617  bool DeletedAny = false;
3618  while (Ops[Idx]->getSCEVType() == Kind) {
3619  const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3620  Ops.erase(Ops.begin()+Idx);
3621  Ops.append(SMME->op_begin(), SMME->op_end());
3622  DeletedAny = true;
3623  }
3624 
3625  if (DeletedAny)
3626  return getMinMaxExpr(Kind, Ops);
3627  }
3628 
3629  // Okay, check to see if the same value occurs in the operand list twice. If
3630  // so, delete one. Since we sorted the list, these values are required to
3631  // be adjacent.
3632  llvm::CmpInst::Predicate GEPred =
3634  llvm::CmpInst::Predicate LEPred =
3636  llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3637  llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3638  for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3639  if (Ops[i] == Ops[i + 1] ||
3640  isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3641  // X op Y op Y --> X op Y
3642  // X op Y --> X, if we know X, Y are ordered appropriately
3643  Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3644  --i;
3645  --e;
3646  } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3647  Ops[i + 1])) {
3648  // X op Y --> Y, if we know X, Y are ordered appropriately
3649  Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3650  --i;
3651  --e;
3652  }
3653  }
3654 
3655  if (Ops.size() == 1) return Ops[0];
3656 
3657  assert(!Ops.empty() && "Reduced smax down to nothing!");
3658 
3659  // Okay, it looks like we really DO need an expr. Check to see if we
3660  // already have one, otherwise create a new one.
3661  const SCEV *ExistingSCEV;
3663  void *IP;
3664  std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3665  if (ExistingSCEV)
3666  return ExistingSCEV;
3667  const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3668  std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3669  SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr(
3670  ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size());
3671 
3672  UniqueSCEVs.InsertNode(S, IP);
3673  addToLoopUseLists(S);
3674  return S;
3675 }
3676 
3677 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3678  SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3679  return getSMaxExpr(Ops);
3680 }
3681 
3683  return getMinMaxExpr(scSMaxExpr, Ops);
3684 }
3685 
3686 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3687  SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3688  return getUMaxExpr(Ops);
3689 }
3690 
3692  return getMinMaxExpr(scUMaxExpr, Ops);
3693 }
3694 
3696  const SCEV *RHS) {
3697  SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3698  return getSMinExpr(Ops);
3699 }
3700 
3702  return getMinMaxExpr(scSMinExpr, Ops);
3703 }
3704 
3706  const SCEV *RHS) {
3707  SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3708  return getUMinExpr(Ops);
3709 }
3710 
3712  return getMinMaxExpr(scUMinExpr, Ops);
3713 }
3714 
3715 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3716  // We can bypass creating a target-independent
3717  // constant expression and then folding it back into a ConstantInt.
3718  // This is just a compile-time optimization.
3719  return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3720 }
3721 
3723  StructType *STy,
3724  unsigned FieldNo) {
3725  // We can bypass creating a target-independent
3726  // constant expression and then folding it back into a ConstantInt.
3727  // This is just a compile-time optimization.
3728  return getConstant(
3729  IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3730 }
3731 
3733  // Don't attempt to do anything other than create a SCEVUnknown object
3734  // here. createSCEV only calls getUnknown after checking for all other
3735  // interesting possibilities, and any other code that calls getUnknown
3736  // is doing so in order to hide a value from SCEV canonicalization.
3737 
3739  ID.AddInteger(scUnknown);
3740  ID.AddPointer(V);
3741  void *IP = nullptr;
3742  if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3743  assert(cast<SCEVUnknown>(S)->getValue() == V &&
3744  "Stale SCEVUnknown in uniquing map!");
3745  return S;
3746  }
3747  SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3748  FirstUnknown);
3749  FirstUnknown = cast<SCEVUnknown>(S);
3750  UniqueSCEVs.InsertNode(S, IP);
3751  return S;
3752 }
3753 
3754 //===----------------------------------------------------------------------===//
3755 // Basic SCEV Analysis and PHI Idiom Recognition Code
3756 //
3757 
3758 /// Test if values of the given type are analyzable within the SCEV
3759 /// framework. This primarily includes integer types, and it can optionally
3760 /// include pointer types if the ScalarEvolution class has access to
3761 /// target-specific information.
3763  // Integers and pointers are always SCEVable.
3764  return Ty->isIntOrPtrTy();
3765 }
3766 
3767 /// Return the size in bits of the specified type, for which isSCEVable must
3768 /// return true.
3770  assert(isSCEVable(Ty) && "Type is not SCEVable!");
3771  if (Ty->isPointerTy())
3772  return getDataLayout().getIndexTypeSizeInBits(Ty);
3773  return getDataLayout().getTypeSizeInBits(Ty);
3774 }
3775 
3776 /// Return a type with the same bitwidth as the given type and which represents
3777 /// how SCEV will treat the given type, for which isSCEVable must return
3778 /// true. For pointer types, this is the pointer-sized integer type.
3780  assert(isSCEVable(Ty) && "Type is not SCEVable!");
3781 
3782  if (Ty->isIntegerTy())
3783  return Ty;
3784 
3785  // The only other support type is pointer.
3786  assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3787  return getDataLayout().getIntPtrType(Ty);
3788 }
3789 
3791  return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3792 }
3793 
3795  return CouldNotCompute.get();
3796 }
3797 
3798 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3799  bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3800  auto *SU = dyn_cast<SCEVUnknown>(S);
3801  return SU && SU->getValue() == nullptr;
3802  });
3803 
3804  return !ContainsNulls;
3805 }
3806 
3808  HasRecMapType::iterator I = HasRecMap.find(S);
3809  if (I != HasRecMap.end())
3810  return I->second;
3811 
3812  bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3813  HasRecMap.insert({S, FoundAddRec});
3814  return FoundAddRec;
3815 }
3816 
3817 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3818 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3819 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3820 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3821  const auto *Add = dyn_cast<SCEVAddExpr>(S);
3822  if (!Add)
3823  return {S, nullptr};
3824 
3825  if (Add->getNumOperands() != 2)
3826  return {S, nullptr};
3827 
3828  auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3829  if (!ConstOp)
3830  return {S, nullptr};
3831 
3832  return {Add->getOperand(1), ConstOp->getValue()};
3833 }
3834 
3835 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3836 /// by the value and offset from any ValueOffsetPair in the set.
3838 ScalarEvolution::getSCEVValues(const SCEV *S) {
3839  ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3840  if (SI == ExprValueMap.end())
3841  return nullptr;
3842 #ifndef NDEBUG
3843  if (VerifySCEVMap) {
3844  // Check there is no dangling Value in the set returned.
3845  for (const auto &VE : SI->second)
3846  assert(ValueExprMap.count(VE.first));
3847  }
3848 #endif
3849  return &SI->second;
3850 }
3851 
3852 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3853 /// cannot be used separately. eraseValueFromMap should be used to remove
3854 /// V from ValueExprMap and ExprValueMap at the same time.
3856  ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3857  if (I != ValueExprMap.end()) {
3858  const SCEV *S = I->second;
3859  // Remove {V, 0} from the set of ExprValueMap[S]
3860  if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3861  SV->remove({V, nullptr});
3862 
3863  // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3864  const SCEV *Stripped;
3866  std::tie(Stripped, Offset) = splitAddExpr(S);
3867  if (Offset != nullptr) {
3868  if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3869  SV->remove({V, Offset});
3870  }
3871  ValueExprMap.erase(V);
3872  }
3873 }
3874 
3875 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3876 /// TODO: In reality it is better to check the poison recursively
3877 /// but this is better than nothing.
3878 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3879  if (auto *I = dyn_cast<Instruction>(V)) {
3880  if (isa<OverflowingBinaryOperator>(I)) {
3881  if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3882  if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3883  return true;
3884  if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3885  return true;
3886  }
3887  } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3888  return true;
3889  }
3890  return false;
3891 }
3892 
3893 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3894 /// create a new one.
3896  assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3897 
3898  const SCEV *S = getExistingSCEV(V);
3899  if (S == nullptr) {
3900  S = createSCEV(V);
3901  // During PHI resolution, it is possible to create two SCEVs for the same
3902  // V, so it is needed to double check whether V->S is inserted into
3903  // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3904  std::pair<ValueExprMapType::iterator, bool> Pair =
3905  ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3906  if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3907  ExprValueMap[S].insert({V, nullptr});
3908 
3909  // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3910  // ExprValueMap.
3911  const SCEV *Stripped = S;
3912  ConstantInt *Offset = nullptr;
3913  std::tie(Stripped, Offset) = splitAddExpr(S);
3914  // If stripped is SCEVUnknown, don't bother to save
3915  // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3916  // increase the complexity of the expansion code.
3917  // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3918  // because it may generate add/sub instead of GEP in SCEV expansion.
3919  if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3920  !isa<GetElementPtrInst>(V))
3921  ExprValueMap[Stripped].insert({V, Offset});
3922  }
3923  }
3924  return S;
3925 }
3926 
3927 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3928  assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3929 
3930  ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3931  if (I != ValueExprMap.end()) {
3932  const SCEV *S = I->second;
3933  if (checkValidity(S))
3934  return S;
3935  eraseValueFromMap(V);
3936  forgetMemoizedResults(S);
3937  }
3938  return nullptr;
3939 }
3940 
3941 /// Return a SCEV corresponding to -V = -1*V
3943  SCEV::NoWrapFlags Flags) {
3944  if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3945  return getConstant(
3946  cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3947 
3948  Type *Ty = V->getType();
3949  Ty = getEffectiveSCEVType(Ty);
3950  return getMulExpr(
3951  V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3952 }
3953 
3954 /// If Expr computes ~A, return A else return nullptr
3955 static const SCEV *MatchNotExpr(const SCEV *Expr) {
3956  const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3957  if (!Add || Add->getNumOperands() != 2 ||
3958  !Add->getOperand(0)->isAllOnesValue())
3959  return nullptr;
3960 
3961  const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3962  if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3963  !AddRHS->getOperand(0)->isAllOnesValue())
3964  return nullptr;
3965 
3966  return AddRHS->getOperand(1);
3967 }
3968 
3969 /// Return a SCEV corresponding to ~V = -1-V
3971  if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3972  return getConstant(
3973  cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3974 
3975  // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3976  if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3977  auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3978  SmallVector<const SCEV *, 2> MatchedOperands;
3979  for (const SCEV *Operand : MME->operands()) {
3980  const SCEV *Matched = MatchNotExpr(Operand);
3981  if (!Matched)
3982  return (const SCEV *)nullptr;
3983  MatchedOperands.push_back(Matched);
3984  }
3985  return getMinMaxExpr(
3986  SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())),
3987  MatchedOperands);
3988  };
3989  if (const SCEV *Replaced = MatchMinMaxNegation(MME))
3990  return Replaced;
3991  }
3992 
3993  Type *Ty = V->getType();
3994  Ty = getEffectiveSCEVType(Ty);
3995  const SCEV *AllOnes =
3996  getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3997  return getMinusSCEV(AllOnes, V);
3998 }
3999 
4000 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4001  SCEV::NoWrapFlags Flags,
4002  unsigned Depth) {
4003  // Fast path: X - X --> 0.
4004  if (LHS == RHS)
4005  return getZero(LHS->getType());
4006 
4007  // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4008  // makes it so that we cannot make much use of NUW.
4009  auto AddFlags = SCEV::FlagAnyWrap;
4010  const bool RHSIsNotMinSigned =
4011  !getSignedRangeMin(RHS).isMinSignedValue();
4012  if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
4013  // Let M be the minimum representable signed value. Then (-1)*RHS
4014  // signed-wraps if and only if RHS is M. That can happen even for
4015  // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4016  // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4017  // (-1)*RHS, we need to prove that RHS != M.
4018  //
4019  // If LHS is non-negative and we know that LHS - RHS does not
4020  // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4021  // either by proving that RHS > M or that LHS >= 0.
4022  if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4023  AddFlags = SCEV::FlagNSW;
4024  }
4025  }
4026 
4027  // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4028  // RHS is NSW and LHS >= 0.
4029  //
4030  // The difficulty here is that the NSW flag may have been proven
4031  // relative to a loop that is to be found in a recurrence in LHS and
4032  // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4033  // larger scope than intended.
4034  auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4035 
4036  return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4037 }
4038 
4040  unsigned Depth) {
4041  Type *SrcTy = V->getType();
4042  assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4043  "Cannot truncate or zero extend with non-integer arguments!");
4044  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4045  return V; // No conversion
4046  if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4047  return getTruncateExpr(V, Ty, Depth);
4048  return getZeroExtendExpr(V, Ty, Depth);
4049 }
4050 
4052  unsigned Depth) {
4053  Type *SrcTy = V->getType();
4054  assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4055  "Cannot truncate or zero extend with non-integer arguments!");
4056  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4057  return V; // No conversion
4058  if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4059  return getTruncateExpr(V, Ty, Depth);
4060  return getSignExtendExpr(V, Ty, Depth);
4061 }
4062 
4063 const SCEV *
4065  Type *SrcTy = V->getType();
4066  assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4067  "Cannot noop or zero extend with non-integer arguments!");
4068  assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4069  "getNoopOrZeroExtend cannot truncate!");
4070  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4071  return V; // No conversion
4072  return getZeroExtendExpr(V, Ty);
4073 }
4074 
4075 const SCEV *
4077  Type *SrcTy = V->getType();
4078  assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4079  "Cannot noop or sign extend with non-integer arguments!");
4080  assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4081  "getNoopOrSignExtend cannot truncate!");
4082  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4083  return V; // No conversion
4084  return getSignExtendExpr(V, Ty);
4085 }
4086 
4087 const SCEV *
4089  Type *SrcTy = V->getType();
4090  assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4091  "Cannot noop or any extend with non-integer arguments!");
4092  assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4093  "getNoopOrAnyExtend cannot truncate!");
4094  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4095  return V; // No conversion
4096  return getAnyExtendExpr(V, Ty);
4097 }
4098 
4099 const SCEV *
4101  Type *SrcTy = V->getType();
4102  assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4103  "Cannot truncate or noop with non-integer arguments!");
4104  assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4105  "getTruncateOrNoop cannot extend!");
4106  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4107  return V; // No conversion
4108  return getTruncateExpr(V, Ty);
4109 }
4110 
4112  const SCEV *RHS) {
4113  const SCEV *PromotedLHS = LHS;
4114  const SCEV *PromotedRHS = RHS;
4115 
4116  if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4117  PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4118  else
4119  PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4120 
4121  return getUMaxExpr(PromotedLHS, PromotedRHS);
4122 }
4123 
4125  const SCEV *RHS) {
4126  SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4127  return getUMinFromMismatchedTypes(Ops);
4128 }
4129 
4132  assert(!Ops.empty() && "At least one operand must be!");
4133  // Trivial case.
4134  if (Ops.size() == 1)
4135  return Ops[0];
4136 
4137  // Find the max type first.
4138  Type *MaxType = nullptr;
4139  for (auto *S : Ops)
4140  if (MaxType)
4141  MaxType = getWiderType(MaxType, S->getType());
4142  else
4143  MaxType = S->getType();
4144 
4145  // Extend all ops to max type.
4146  SmallVector<const SCEV *, 2> PromotedOps;
4147  for (auto *S : Ops)
4148  PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4149 
4150  // Generate umin.
4151  return getUMinExpr(PromotedOps);
4152 }
4153 
4155  // A pointer operand may evaluate to a nonpointer expression, such as null.
4156  if (!V->getType()->isPointerTy())
4157  return V;
4158 
4159  if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4160  return getPointerBase(Cast->getOperand());
4161  } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4162  const SCEV *PtrOp = nullptr;
4163  for (const SCEV *NAryOp : NAry->operands()) {
4164  if (NAryOp->getType()->isPointerTy()) {
4165  // Cannot find the base of an expression with multiple pointer operands.
4166  if (PtrOp)
4167  return V;
4168  PtrOp = NAryOp;
4169  }
4170  }
4171  if (!PtrOp)
4172  return V;
4173  return getPointerBase(PtrOp);
4174  }
4175  return V;
4176 }
4177 
4178 /// Push users of the given Instruction onto the given Worklist.
4179 static void
4181  SmallVectorImpl<Instruction *> &Worklist) {
4182  // Push the def-use children onto the Worklist stack.
4183  for (User *U : I->users())
4184  Worklist.push_back(cast<Instruction>(U));
4185 }
4186 
4187 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4189  PushDefUseChildren(PN, Worklist);
4190 
4192  Visited.insert(PN);
4193  while (!Worklist.empty()) {
4194  Instruction *I = Worklist.pop_back_val();
4195  if (!Visited.insert(I).second)
4196  continue;
4197 
4198  auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4199  if (It != ValueExprMap.end()) {
4200  const SCEV *Old = It->second;
4201 
4202  // Short-circuit the def-use traversal if the symbolic name
4203  // ceases to appear in expressions.
4204  if (Old != SymName && !hasOperand(Old, SymName))
4205  continue;
4206 
4207  // SCEVUnknown for a PHI either means that it has an unrecognized
4208  // structure, it's a PHI that's in the progress of being computed
4209  // by createNodeForPHI, or it's a single-value PHI. In the first case,
4210  // additional loop trip count information isn't going to change anything.
4211  // In the second case, createNodeForPHI will perform the necessary
4212  // updates on its own when it gets to that point. In the third, we do
4213  // want to forget the SCEVUnknown.
4214  if (!isa<PHINode>(I) ||
4215  !isa<SCEVUnknown>(Old) ||
4216  (I != PN && Old == SymName)) {
4217  eraseValueFromMap(It->first);
4218  forgetMemoizedResults(Old);
4219  }
4220  }
4221 
4222  PushDefUseChildren(I, Worklist);
4223  }
4224 }
4225 
4226 namespace {
4227 
4228 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4229 /// expression in case its Loop is L. If it is not L then
4230 /// if IgnoreOtherLoops is true then use AddRec itself
4231 /// otherwise rewrite cannot be done.
4232 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4233 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4234 public:
4235  static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4236  bool IgnoreOtherLoops = true) {
4237  SCEVInitRewriter Rewriter(L, SE);
4238  const SCEV *Result = Rewriter.visit(S);
4239  if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4240  return SE.getCouldNotCompute();
4241  return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4242  ? SE.getCouldNotCompute()
4243  : Result;
4244  }
4245 
4246  const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4247  if (!SE.isLoopInvariant(Expr, L))
4248  SeenLoopVariantSCEVUnknown = true;
4249  return Expr;
4250  }
4251 
4252  const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4253  // Only re-write AddRecExprs for this loop.
4254  if (Expr->getLoop() == L)
4255  return Expr->getStart();
4256  SeenOtherLoops = true;
4257  return Expr;
4258  }
4259 
4260  bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4261 
4262  bool hasSeenOtherLoops() { return SeenOtherLoops; }
4263 
4264 private:
4265  explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4266  : SCEVRewriteVisitor(SE), L(L) {}
4267 
4268  const Loop *L;
4269  bool SeenLoopVariantSCEVUnknown = false;
4270  bool SeenOtherLoops = false;
4271 };
4272 
4273 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4274 /// increment expression in case its Loop is L. If it is not L then
4275 /// use AddRec itself.
4276 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4277 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4278 public:
4279  static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4280  SCEVPostIncRewriter Rewriter(L, SE);
4281  const SCEV *Result = Rewriter.visit(S);
4282  return Rewriter.hasSeenLoopVariantSCEVUnknown()
4283  ? SE.getCouldNotCompute()
4284  : Result;
4285  }
4286 
4287  const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4288  if (!SE.isLoopInvariant(Expr, L))
4289  SeenLoopVariantSCEVUnknown = true;
4290  return Expr;
4291  }
4292 
4293  const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4294  // Only re-write AddRecExprs for this loop.
4295  if (Expr->getLoop() == L)
4296  return Expr->getPostIncExpr(SE);
4297  SeenOtherLoops = true;
4298  return Expr;
4299  }
4300 
4301  bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4302 
4303  bool hasSeenOtherLoops() { return SeenOtherLoops; }
4304 
4305 private:
4306  explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4307  : SCEVRewriteVisitor(SE), L(L) {}
4308 
4309  const Loop *L;
4310  bool SeenLoopVariantSCEVUnknown = false;
4311  bool SeenOtherLoops = false;
4312 };
4313 
4314 /// This class evaluates the compare condition by matching it against the
4315 /// condition of loop latch. If there is a match we assume a true value
4316 /// for the condition while building SCEV nodes.
4317 class SCEVBackedgeConditionFolder
4318  : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4319 public:
4320  static const SCEV *rewrite(const SCEV *S, const Loop *L,
4321  ScalarEvolution &SE) {
4322  bool IsPosBECond = false;
4323  Value *BECond = nullptr;
4324  if (BasicBlock *Latch = L->getLoopLatch()) {
4325  BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4326  if (BI && BI->isConditional()) {
4327  assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4328  "Both outgoing branches should not target same header!");
4329  BECond = BI->getCondition();
4330  IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4331  } else {
4332  return S;
4333  }
4334  }
4335  SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4336  return Rewriter.visit(S);
4337  }
4338 
4339  const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4340  const SCEV *Result = Expr;
4341  bool InvariantF = SE.isLoopInvariant(Expr, L);
4342 
4343  if (!InvariantF) {
4344  Instruction *I = cast<Instruction>(Expr->getValue());
4345  switch (I->getOpcode()) {
4346  case Instruction::Select: {
4347  SelectInst *SI = cast<SelectInst>(I);
4349  compareWithBackedgeCondition(SI->getCondition());
4350  if (Res.hasValue()) {
4351  bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4352  Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4353  }
4354  break;
4355  }
4356  default: {
4357  Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4358  if (Res.hasValue())
4359  Result = Res.getValue();
4360  break;
4361  }
4362  }
4363  }
4364  return Result;
4365  }
4366 
4367 private:
4368  explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4369  bool IsPosBECond, ScalarEvolution &SE)
4370  : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4371  IsPositiveBECond(IsPosBECond) {}
4372 
4373  Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4374 
4375  const Loop *L;
4376  /// Loop back condition.
4377  Value *BackedgeCond = nullptr;
4378  /// Set to true if loop back is on positive branch condition.
4379  bool IsPositiveBECond;
4380 };
4381 
4383 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4384 
4385  // If value matches the backedge condition for loop latch,
4386  // then return a constant evolution node based on loopback
4387  // branch taken.
4388  if (BackedgeCond == IC)
4389  return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4390  : SE.getZero(Type::getInt1Ty(SE.getContext()));
4391  return None;
4392 }
4393 
4394 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4395 public:
4396  static const SCEV *rewrite(const SCEV *S, const Loop *L,
4397  ScalarEvolution &SE) {
4398  SCEVShiftRewriter Rewriter(L, SE);
4399  const SCEV *Result = Rewriter.visit(S);
4400  return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4401  }
4402 
4403  const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4404  // Only allow AddRecExprs for this loop.
4405  if (!SE.isLoopInvariant(Expr, L))
4406  Valid = false;
4407  return Expr;
4408  }
4409 
4410  const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4411  if (Expr->getLoop() == L && Expr->isAffine())
4412  return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4413  Valid = false;
4414  return Expr;
4415  }
4416 
4417  bool isValid() { return Valid; }
4418 
4419 private:
4420  explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4421  : SCEVRewriteVisitor(SE), L(L) {}
4422 
4423  const Loop *L;
4424  bool Valid = true;
4425 };
4426 
4427 } // end anonymous namespace
4428 
4430 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4431  if (!AR->isAffine())
4432  return SCEV::FlagAnyWrap;
4433 
4434  using OBO = OverflowingBinaryOperator;
4435 
4437 
4438  if (!AR->hasNoSignedWrap()) {
4439  ConstantRange AddRecRange = getSignedRange(AR);
4440  ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4441 
4443  Instruction::Add, IncRange, OBO::NoSignedWrap);
4444  if (NSWRegion.contains(AddRecRange))
4445  Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4446  }
4447 
4448  if (!AR->hasNoUnsignedWrap()) {
4449  ConstantRange AddRecRange = getUnsignedRange(AR);
4450  ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4451 
4453  Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4454  if (NUWRegion.contains(AddRecRange))
4455  Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4456  }
4457 
4458  return Result;
4459 }
4460 
4461 namespace {
4462 
4463 /// Represents an abstract binary operation. This may exist as a
4464 /// normal instruction or constant expression, or may have been
4465 /// derived from an expression tree.
4466 struct BinaryOp {
4467  unsigned Opcode;
4468  Value *LHS;
4469  Value *RHS;
4470  bool IsNSW = false;
4471  bool IsNUW = false;
4472 
4473  /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4474  /// constant expression.
4475  Operator *Op = nullptr;
4476 
4477  explicit BinaryOp(Operator *Op)
4478  : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4479  Op(Op) {
4480  if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4481  IsNSW = OBO->hasNoSignedWrap();
4482  IsNUW = OBO->hasNoUnsignedWrap();
4483  }
4484  }
4485 
4486  explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4487  bool IsNUW = false)
4488  : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4489 };
4490 
4491 } // end anonymous namespace
4492 
4493 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4495  auto *Op = dyn_cast<Operator>(V);
4496  if (!Op)
4497  return None;
4498 
4499  // Implementation detail: all the cleverness here should happen without
4500  // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4501  // SCEV expressions when possible, and we should not break that.
4502 
4503  switch (Op->getOpcode()) {
4504  case Instruction::Add:
4505  case Instruction::Sub:
4506  case Instruction::Mul:
4507  case Instruction::UDiv:
4508  case Instruction::URem:
4509  case Instruction::And:
4510  case Instruction::Or:
4511  case Instruction::AShr:
4512  case Instruction::Shl:
4513  return BinaryOp(Op);
4514 
4515  case Instruction::Xor:
4516  if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4517  // If the RHS of the xor is a signmask, then this is just an add.
4518  // Instcombine turns add of signmask into xor as a strength reduction step.
4519  if (RHSC->getValue().isSignMask())
4520  return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4521  return BinaryOp(Op);
4522 
4523  case Instruction::LShr:
4524  // Turn logical shift right of a constant into a unsigned divide.
4525  if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4526  uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4527 
4528  // If the shift count is not less than the bitwidth, the result of
4529  // the shift is undefined. Don't try to analyze it, because the
4530  // resolution chosen here may differ from the resolution chosen in
4531  // other parts of the compiler.
4532  if (SA->getValue().ult(BitWidth)) {
4533  Constant *X =
4534  ConstantInt::get(SA->getContext(),
4535  APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4536  return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4537  }
4538  }
4539  return BinaryOp(Op);
4540 
4541  case Instruction::ExtractValue: {
4542  auto *EVI = cast<ExtractValueInst>(Op);
4543  if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4544  break;
4545 
4546  auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4547  if (!WO)
4548  break;
4549 
4550  Instruction::BinaryOps BinOp = WO->getBinaryOp();
4551  bool Signed = WO->isSigned();
4552  // TODO: Should add nuw/nsw flags for mul as well.
4553  if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4554  return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4555 
4556  // Now that we know that all uses of the arithmetic-result component of
4557  // CI are guarded by the overflow check, we can go ahead and pretend
4558  // that the arithmetic is non-overflowing.
4559  return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4560  /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4561  }
4562 
4563  default:
4564  break;
4565  }
4566 
4567  return None;
4568 }
4569 
4570 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4571 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4572 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4573 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4574 /// follows one of the following patterns:
4575 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4576 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4577 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4578 /// we return the type of the truncation operation, and indicate whether the
4579 /// truncated type should be treated as signed/unsigned by setting
4580 /// \p Signed to true/false, respectively.
4581 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4582  bool &Signed, ScalarEvolution &SE) {
4583  // The case where Op == SymbolicPHI (that is, with no type conversions on
4584  // the way) is handled by the regular add recurrence creating logic and
4585  // would have already been triggered in createAddRecForPHI. Reaching it here
4586  // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4587  // because one of the other operands of the SCEVAddExpr updating this PHI is
4588  // not invariant).
4589  //
4590  // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4591  // this case predicates that allow us to prove that Op == SymbolicPHI will
4592  // be added.
4593  if (Op == SymbolicPHI)
4594  return nullptr;
4595 
4596  unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4597  unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4598  if (SourceBits != NewBits)
4599  return nullptr;
4600 
4603  if (!SExt && !ZExt)
4604  return nullptr;
4605  const SCEVTruncateExpr *Trunc =
4606  SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4607  : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4608  if (!Trunc)
4609  return nullptr;
4610  const SCEV *X = Trunc->getOperand();
4611  if (X != SymbolicPHI)
4612  return nullptr;
4613  Signed = SExt != nullptr;
4614  return Trunc->getType();
4615 }
4616 
4617 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4618  if (!PN->getType()->isIntegerTy())
4619  return nullptr;
4620  const Loop *L = LI.getLoopFor(PN->getParent());
4621  if (!L || L->getHeader() != PN->getParent())
4622  return nullptr;
4623  return L;
4624 }
4625 
4626 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4627 // computation that updates the phi follows the following pattern:
4628 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4629 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4630 // If so, try to see if it can be rewritten as an AddRecExpr under some
4631 // Predicates. If successful, return them as a pair. Also cache the results
4632 // of the analysis.
4633 //
4634 // Example usage scenario:
4635 // Say the Rewriter is called for the following SCEV:
4636 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4637 // where:
4638 // %X = phi i64 (%Start, %BEValue)
4639 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4640 // and call this function with %SymbolicPHI = %X.
4641 //
4642 // The analysis will find that the value coming around the backedge has
4643 // the following SCEV:
4644 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4645 // Upon concluding that this matches the desired pattern, the function
4646 // will return the pair {NewAddRec, SmallPredsVec} where:
4647 // NewAddRec = {%Start,+,%Step}
4648 // SmallPredsVec = {P1, P2, P3} as follows:
4649 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4650 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4651 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4652 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4653 // under the predicates {P1,P2,P3}.
4654 // This predicated rewrite will be cached in PredicatedSCEVRewrites:
4655 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4656 //
4657 // TODO's:
4658 //
4659 // 1) Extend the Induction descriptor to also support inductions that involve
4660 // casts: When needed (namely, when we are called in the context of the
4661 // vectorizer induction analysis), a Set of cast instructions will be
4662 // populated by this method, and provided back to isInductionPHI. This is
4663 // needed to allow the vectorizer to properly record them to be ignored by
4664 // the cost model and to avoid vectorizing them (otherwise these casts,
4665 // which are redundant under the runtime overflow checks, will be
4666 // vectorized, which can be costly).
4667 //
4668 // 2) Support additional induction/PHISCEV patterns: We also want to support
4669 // inductions where the sext-trunc / zext-trunc operations (partly) occur
4670 // after the induction update operation (the induction increment):
4671 //
4672 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4673 // which correspond to a phi->add->trunc->sext/zext->phi update chain.
4674 //
4675 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4676 // which correspond to a phi->trunc->add->sext/zext->phi update chain.
4677 //
4678 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4680 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4682 
4683  // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4684  // return an AddRec expression under some predicate.
4685 
4686  auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4687  const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4688  assert(L && "Expecting an integer loop header phi");
4689 
4690  // The loop may have multiple entrances or multiple exits; we can analyze
4691  // this phi as an addrec if it has a unique entry value and a unique
4692  // backedge value.
4693  Value *BEValueV = nullptr, *StartValueV = nullptr;
4694  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4695  Value *V = PN->getIncomingValue(i);
4696  if (L->contains(PN->getIncomingBlock(i))) {
4697  if (!BEValueV) {
4698  BEValueV = V;
4699  } else if (BEValueV != V) {
4700  BEValueV = nullptr;
4701  break;
4702  }
4703  } else if (!StartValueV) {
4704  StartValueV = V;
4705  } else if (StartValueV != V) {
4706  StartValueV = nullptr;
4707  break;
4708  }
4709  }
4710  if (!BEValueV || !StartValueV)
4711  return None;
4712 
4713  const SCEV *BEValue = getSCEV(BEValueV);
4714 
4715  // If the value coming around the backedge is an add with the symbolic
4716  // value we just inserted, possibly with casts that we can ignore under
4717  // an appropriate runtime guard, then we found a simple induction variable!
4718  const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4719  if (!Add)
4720  return None;
4721 
4722  // If there is a single occurrence of the symbolic value, possibly
4723  // casted, replace it with a recurrence.
4724  unsigned FoundIndex = Add->getNumOperands();
4725  Type *TruncTy = nullptr;
4726  bool Signed;
4727  for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4728  if ((TruncTy =
4729  isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4730  if (FoundIndex == e) {
4731  FoundIndex = i;
4732  break;
4733  }
4734 
4735  if (FoundIndex == Add->getNumOperands())
4736  return None;
4737 
4738  // Create an add with everything but the specified operand.
4740  for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4741  if (i != FoundIndex)
4742  Ops.push_back(Add->getOperand(i));
4743  const SCEV *Accum = getAddExpr(Ops);
4744 
4745  // The runtime checks will not be valid if the step amount is
4746  // varying inside the loop.
4747  if (!isLoopInvariant(Accum, L))
4748  return None;
4749 
4750  // *** Part2: Create the predicates
4751 
4752  // Analysis was successful: we have a phi-with-cast pattern for which we
4753  // can return an AddRec expression under the following predicates:
4754  //
4755  // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4756  // fits within the truncated type (does not overflow) for i = 0 to n-1.
4757  // P2: An Equal predicate that guarantees that
4758  // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4759  // P3: An Equal predicate that guarantees that
4760  // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4761  //
4762  // As we next prove, the above predicates guarantee that:
4763  // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4764  //
4765  //
4766  // More formally, we want to prove that:
4767  // Expr(i+1) = Start + (i+1) * Accum
4768  // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4769  //
4770  // Given that:
4771  // 1) Expr(0) = Start
4772  // 2) Expr(1) = Start + Accum
4773  // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4774  // 3) Induction hypothesis (step i):
4775  // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4776  //
4777  // Proof:
4778  // Expr(i+1) =
4779  // = Start + (i+1)*Accum
4780  // = (Start + i*Accum) + Accum
4781  // = Expr(i) + Accum
4782  // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4783  // :: from step i
4784  //
4785  // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4786  //
4787  // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4788  // + (Ext ix (Trunc iy (Accum) to ix) to iy)
4789  // + Accum :: from P3
4790  //
4791  // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4792  // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4793  //
4794  // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4795  // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4796  //
4797  // By induction, the same applies to all iterations 1<=i<n:
4798  //
4799 
4800  // Create a truncated addrec for which we will add a no overflow check (P1).
4801  const SCEV *StartVal = getSCEV(StartValueV);
4802  const SCEV *PHISCEV =
4803  getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4804  getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4805 
4806  // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4807  // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4808  // will be constant.
4809  //
4810  // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4811  // add P1.
4812  if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4816  const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4817  Predicates.push_back(AddRecPred);
4818  }
4819 
4820  // Create the Equal Predicates P2,P3:
4821 
4822  // It is possible that the predicates P2 and/or P3 are computable at
4823  // compile time due to StartVal and/or Accum being constants.
4824  // If either one is, then we can check that now and escape if either P2
4825  // or P3 is false.
4826 
4827  // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4828  // for each of StartVal and Accum
4829  auto getExtendedExpr = [&](const SCEV *Expr,
4830  bool CreateSignExtend) -> const SCEV * {
4831  assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4832  const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4833  const SCEV *ExtendedExpr =
4834  CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4835  : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4836  return ExtendedExpr;
4837  };
4838 
4839  // Given:
4840  // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4841  // = getExtendedExpr(Expr)
4842  // Determine whether the predicate P: Expr == ExtendedExpr
4843  // is known to be false at compile time
4844  auto PredIsKnownFalse = [&](const SCEV *Expr,
4845  const SCEV *ExtendedExpr) -> bool {
4846  return Expr != ExtendedExpr &&
4847  isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4848  };
4849 
4850  const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4851  if (PredIsKnownFalse(StartVal, StartExtended)) {
4852  LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4853  return None;
4854  }
4855 
4856  // The Step is always Signed (because the overflow checks are either
4857  // NSSW or NUSW)
4858  const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4859  if (PredIsKnownFalse(Accum, AccumExtended)) {
4860  LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4861  return None;
4862  }
4863 
4864  auto AppendPredicate = [&](const SCEV *Expr,
4865  const SCEV *ExtendedExpr) -> void {
4866  if (Expr != ExtendedExpr &&
4867  !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4868  const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4869  LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4870  Predicates.push_back(Pred);
4871  }
4872  };
4873 
4874  AppendPredicate(StartVal, StartExtended);
4875  AppendPredicate(Accum, AccumExtended);
4876 
4877  // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4878  // which the casts had been folded away. The caller can rewrite SymbolicPHI
4879  // into NewAR if it will also add the runtime overflow checks specified in
4880  // Predicates.
4881  auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4882 
4883  std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4884  std::make_pair(NewAR, Predicates);
4885  // Remember the result of the analysis for this SCEV at this locayyytion.
4886  PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4887  return PredRewrite;
4888 }
4889 
4892  auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4893  const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4894  if (!L)
4895  return None;
4896 
4897  // Check to see if we already analyzed this PHI.
4898  auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4899  if (I != PredicatedSCEVRewrites.end()) {
4900  std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4901  I->second;
4902  // Analysis was done before and failed to create an AddRec:
4903  if (Rewrite.first == SymbolicPHI)
4904  return None;
4905  // Analysis was done before and succeeded to create an AddRec under
4906  // a predicate:
4907  assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4908  assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4909  return Rewrite;
4910  }
4911 
4913  Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4914 
4915  // Record in the cache that the analysis failed
4916  if (!Rewrite) {
4918  PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4919  return None;
4920  }
4921 
4922  return Rewrite;
4923 }
4924 
4925 // FIXME: This utility is currently required because the Rewriter currently
4926 // does not rewrite this expression:
4927 // {0, +, (sext ix (trunc iy to ix) to iy)}
4928 // into {0, +, %step},
4929 // even when the following Equal predicate exists:
4930 // "%step == (sext ix (trunc iy to ix) to iy)".
4932  const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4933  if (AR1 == AR2)
4934  return true;
4935 
4936  auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4937  if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4938  !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4939  return false;
4940  return true;
4941  };
4942 
4943  if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4944  !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4945  return false;
4946  return true;
4947 }
4948 
4949 /// A helper function for createAddRecFromPHI to handle simple cases.
4950 ///
4951 /// This function tries to find an AddRec expression for the simplest (yet most
4952 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4953 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4954 /// technique for finding the AddRec expression.
4955 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4956  Value *BEValueV,
4957  Value *StartValueV) {
4958  const Loop *L = LI.getLoopFor(PN->getParent());
4959  assert(L && L->getHeader() == PN->getParent());
4960  assert(BEValueV && StartValueV);
4961 
4962  auto BO = MatchBinaryOp(BEValueV, DT);
4963  if (!BO)
4964  return nullptr;
4965 
4966  if (BO->Opcode != Instruction::Add)
4967  return nullptr;
4968 
4969  const SCEV *Accum = nullptr;
4970  if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4971  Accum = getSCEV(BO->RHS);
4972  else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4973  Accum = getSCEV(BO->LHS);
4974 
4975  if (!Accum)
4976  return nullptr;
4977 
4979  if (BO->IsNUW)
4980  Flags = setFlags(Flags, SCEV::FlagNUW);
4981  if (BO->IsNSW)
4982  Flags = setFlags(Flags, SCEV::FlagNSW);
4983 
4984  const SCEV *StartVal = getSCEV(StartValueV);
4985  const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4986 
4987  ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4988 
4989  // We can add Flags to the post-inc expression only if we
4990  // know that it is *undefined behavior* for BEValueV to
4991  // overflow.
4992  if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4993  if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4994  (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4995 
4996  return PHISCEV;
4997 }
4998 
4999 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5000  const Loop *L = LI.getLoopFor(PN->getParent());
5001  if (!L || L->getHeader() != PN->getParent())
5002  return nullptr;
5003 
5004  // The loop may have multiple entrances or multiple exits; we can analyze
5005  // this phi as an addrec if it has a unique entry value and a unique
5006  // backedge value.
5007  Value *BEValueV = nullptr, *StartValueV = nullptr;
5008  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5009  Value *V = PN->getIncomingValue(i);
5010  if (L->contains(PN->getIncomingBlock(i))) {
5011  if (!BEValueV) {
5012  BEValueV = V;
5013  } else if (BEValueV != V) {
5014  BEValueV = nullptr;
5015  break;
5016  }
5017  } else if (!StartValueV) {
5018  StartValueV = V;
5019  } else if (StartValueV != V) {
5020  StartValueV = nullptr;
5021  break;
5022  }
5023  }
5024  if (!BEValueV || !StartValueV)
5025  return nullptr;
5026 
5027  assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5028  "PHI node already processed?");
5029 
5030  // First, try to find AddRec expression without creating a fictituos symbolic
5031  // value for PN.
5032  if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5033  return S;
5034 
5035  // Handle PHI node value symbolically.
5036  const SCEV *SymbolicName = getUnknown(PN);
5037  ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5038 
5039  // Using this symbolic name for the PHI, analyze the value coming around
5040  // the back-edge.
5041  const SCEV *BEValue = getSCEV(BEValueV);
5042 
5043  // NOTE: If BEValue is loop invariant, we know that the PHI node just
5044  // has a special value for the first iteration of the loop.
5045 
5046  // If the value coming around the backedge is an add with the symbolic
5047  // value we just inserted, then we found a simple induction variable!
5048  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5049  // If there is a single occurrence of the symbolic value, replace it
5050  // with a recurrence.
5051  unsigned FoundIndex = Add->getNumOperands();
5052  for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5053  if (Add->getOperand(i) == SymbolicName)
5054  if (FoundIndex == e) {
5055  FoundIndex = i;
5056  break;
5057  }
5058 
5059  if (FoundIndex != Add->getNumOperands()) {
5060  // Create an add with everything but the specified operand.
5062  for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5063  if (i != FoundIndex)
5064  Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5065  L, *this));
5066  const SCEV *Accum = getAddExpr(Ops);
5067 
5068  // This is not a valid addrec if the step amount is varying each
5069  // loop iteration, but is not itself an addrec in this loop.
5070  if (isLoopInvariant(Accum, L) ||
5071  (isa<SCEVAddRecExpr>(Accum) &&
5072  cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5074 
5075  if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5076  if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5077  if (BO->IsNUW)
5078  Flags = setFlags(Flags, SCEV::FlagNUW);
5079  if (BO->IsNSW)
5080  Flags = setFlags(Flags, SCEV::FlagNSW);
5081  }
5082  } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5083  // If the increment is an inbounds GEP, then we know the address
5084  // space cannot be wrapped around. We cannot make any guarantee
5085  // about signed or unsigned overflow because pointers are
5086  // unsigned but we may have a negative index from the base
5087  // pointer. We can guarantee that no unsigned wrap occurs if the
5088  // indices form a positive value.
5089  if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5090  Flags = setFlags(Flags, SCEV::FlagNW);
5091 
5092  const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5093  if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5094  Flags = setFlags(Flags, SCEV::FlagNUW);
5095  }
5096 
5097  // We cannot transfer nuw and nsw flags from subtraction
5098  // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5099  // for instance.
5100  }
5101 
5102  const SCEV *StartVal = getSCEV(StartValueV);
5103  const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5104 
5105  // Okay, for the entire analysis of this edge we assumed the PHI
5106  // to be symbolic. We now need to go back and purge all of the
5107  // entries for the scalars that use the symbolic expression.
5108  forgetSymbolicName(PN, SymbolicName);
5109  ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5110 
5111  // We can add Flags to the post-inc expression only if we
5112  // know that it is *undefined behavior* for BEValueV to
5113  // overflow.
5114  if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5115  if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5116  (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5117 
5118  return PHISCEV;
5119  }
5120  }
5121  } else {
5122  // Otherwise, this could be a loop like this:
5123  // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5124  // In this case, j = {1,+,1} and BEValue is j.
5125  // Because the other in-value of i (0) fits the evolution of BEValue
5126  // i really is an addrec evolution.
5127  //
5128  // We can generalize this saying that i is the shifted value of BEValue
5129  // by one iteration:
5130  // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5131  const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5132  const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5133  if (Shifted != getCouldNotCompute() &&
5134  Start != getCouldNotCompute()) {
5135  const SCEV *StartVal = getSCEV(StartValueV);
5136  if (Start == StartVal) {
5137  // Okay, for the entire analysis of this edge we assumed the PHI
5138  // to be symbolic. We now need to go back and purge all of the
5139  // entries for the scalars that use the symbolic expression.
5140  forgetSymbolicName(PN, SymbolicName);
5141  ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5142  return Shifted;
5143  }
5144  }
5145  }
5146 
5147  // Remove the temporary PHI node SCEV that has been inserted while intending
5148  // to create an AddRecExpr for this PHI node. We can not keep this temporary
5149  // as it will prevent later (possibly simpler) SCEV expressions to be added
5150  // to the ValueExprMap.
5151  eraseValueFromMap(PN);
5152 
5153  return nullptr;
5154 }
5155 
5156 // Checks if the SCEV S is available at BB. S is considered available at BB
5157 // if S can be materialized at BB without introducing a fault.
5158 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5159  BasicBlock *BB) {
5160  struct CheckAvailable {
5161  bool TraversalDone = false;
5162  bool Available = true;
5163 
5164  const Loop *L = nullptr; // The loop BB is in (can be nullptr)
5165  BasicBlock *BB = nullptr;
5166  DominatorTree &DT;
5167 
5168  CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5169  : L(L), BB(BB), DT(DT) {}
5170 
5171  bool setUnavailable() {
5172  TraversalDone = true;
5173  Available = false;
5174  return false;
5175  }
5176 
5177  bool follow(const SCEV *S) {
5178  switch (S->getSCEVType()) {
5179  case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5180  case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5181  case scUMinExpr:
5182  case scSMinExpr:
5183  // These expressions are available if their operand(s) is/are.
5184  return true;
5185 
5186  case scAddRecExpr: {
5187  // We allow add recurrences that are on the loop BB is in, or some
5188  // outer loop. This guarantees availability because the value of the
5189  // add recurrence at BB is simply the "current" value of the induction
5190  // variable. We can relax this in the future; for instance an add
5191  // recurrence on a sibling dominating loop is also available at BB.
5192  const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5193  if (L && (ARLoop == L || ARLoop->contains(L)))
5194  return true;
5195 
5196  return setUnavailable();
5197  }
5198 
5199  case scUnknown: {
5200  // For SCEVUnknown, we check for simple dominance.
5201  const auto *SU = cast<SCEVUnknown>(S);
5202  Value *V = SU->getValue();
5203 
5204  if (isa<Argument>(V))
5205  return false;
5206 
5207  if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5208  return false;
5209 
5210  return setUnavailable();
5211  }
5212 
5213  case scUDivExpr:
5214  case scCouldNotCompute:
5215  // We do not try to smart about these at all.
5216  return setUnavailable();
5217  }
5218  llvm_unreachable("switch should be fully covered!");
5219  }
5220 
5221  bool isDone() { return TraversalDone; }
5222  };
5223 
5224  CheckAvailable CA(L, BB, DT);
5226 
5227  ST.visitAll(S);
5228  return CA.Available;
5229 }
5230 
5231 // Try to match a control flow sequence that branches out at BI and merges back
5232 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5233 // match.
5235  Value *&C, Value *&LHS, Value *&RHS) {
5236  C = BI->getCondition();
5237 
5238  BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5239  BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5240 
5241  if (!LeftEdge.isSingleEdge())
5242  return false;
5243 
5244  assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5245 
5246  Use &LeftUse = Merge->getOperandUse(0);
5247  Use &RightUse = Merge->getOperandUse(1);
5248 
5249  if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5250  LHS = LeftUse;
5251  RHS = RightUse;
5252  return true;
5253  }
5254 
5255  if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5256  LHS = RightUse;
5257  RHS = LeftUse;
5258  return true;
5259  }
5260 
5261  return false;
5262 }
5263 
5264 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5265  auto IsReachable =
5266  [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5267  if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5268  const Loop *L = LI.getLoopFor(PN->getParent());
5269 
5270  // We don't want to break LCSSA, even in a SCEV expression tree.
5271  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5272  if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5273  return nullptr;
5274 
5275  // Try to match
5276  //
5277  // br %cond, label %left, label %right
5278  // left:
5279  // br label %merge
5280  // right:
5281  // br label %merge
5282  // merge:
5283  // V = phi [ %x, %left ], [ %y, %right ]
5284  //
5285  // as "select %cond, %x, %y"
5286 
5287  BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5288  assert(IDom && "At least the entry block should dominate PN");
5289 
5290  auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5291  Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5292 
5293  if (BI && BI->isConditional() &&
5294  BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5295  IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5296  IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5297  return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5298  }
5299 
5300  return nullptr;
5301 }
5302 
5303 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5304  if (const SCEV *S = createAddRecFromPHI(PN))
5305  return S;
5306 
5307  if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5308  return S;
5309 
5310  // If the PHI has a single incoming value, follow that value, unless the
5311  // PHI's incoming blocks are in a different loop, in which case doing so
5312  // risks breaking LCSSA form. Instcombine would normally zap these, but
5313  // it doesn't have DominatorTree information, so it may miss cases.
5314  if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5315  if (LI.replacementPreservesLCSSAForm(PN, V))
5316  return getSCEV(V);
5317 
5318  // If it's not a loop phi, we can't handle it yet.
5319  return getUnknown(PN);
5320 }
5321 
5322 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5323  Value *Cond,
5324  Value *TrueVal,
5325  Value *FalseVal) {
5326  // Handle "constant" branch or select. This can occur for instance when a
5327  // loop pass transforms an inner loop and moves on to process the outer loop.
5328  if (auto *CI = dyn_cast<ConstantInt>(Cond))
5329  return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5330 
5331  // Try to match some simple smax or umax patterns.
5332  auto *ICI = dyn_cast<ICmpInst>(Cond);
5333  if (!ICI)
5334  return getUnknown(I);
5335 
5336  Value *LHS = ICI->getOperand(0);
5337  Value *RHS = ICI->getOperand(1);
5338 
5339  switch (ICI->getPredicate()) {
5340  case ICmpInst::ICMP_SLT:
5341  case ICmpInst::ICMP_SLE:
5342  std::swap(LHS, RHS);
5344  case ICmpInst::ICMP_SGT:
5345  case ICmpInst::ICMP_SGE:
5346  // a >s b ? a+x : b+x -> smax(a, b)+x
5347  // a >s b ? b+x : a+x -> smin(a, b)+x
5348  if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5349  const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5350  const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5351  const SCEV *LA = getSCEV(TrueVal);
5352  const SCEV *RA = getSCEV(FalseVal);
5353  const SCEV *LDiff = getMinusSCEV(LA, LS);
5354  const SCEV *RDiff = getMinusSCEV(RA, RS);
5355  if (LDiff == RDiff)
5356  return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5357  LDiff = getMinusSCEV(LA, RS);
5358  RDiff = getMinusSCEV(RA, LS);
5359  if (LDiff == RDiff)
5360  return getAddExpr(getSMinExpr(LS, RS), LDiff);
5361  }
5362  break;
5363  case ICmpInst::ICMP_ULT:
5364  case ICmpInst::ICMP_ULE:
5365  std::swap(LHS, RHS);
5367  case ICmpInst::ICMP_UGT:
5368  case ICmpInst::ICMP_UGE:
5369  // a >u b ? a+x : b+x -> umax(a, b)+x
5370  // a >u b ? b+x : a+x -> umin(a, b)+x
5371  if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5372  const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5373  const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5374  const SCEV *LA = getSCEV(TrueVal);
5375  const SCEV *RA = getSCEV(FalseVal);
5376  const SCEV *LDiff = getMinusSCEV(LA, LS);
5377  const SCEV *RDiff = getMinusSCEV(RA, RS);
5378  if (LDiff == RDiff)
5379  return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5380  LDiff = getMinusSCEV(LA, RS);
5381  RDiff = getMinusSCEV(RA, LS);
5382  if (LDiff == RDiff)
5383  return getAddExpr(getUMinExpr(LS, RS), LDiff);
5384  }
5385  break;
5386  case ICmpInst::ICMP_NE:
5387  // n != 0 ? n+x : 1+x -> umax(n, 1)+x
5388  if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5389  isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5390  const SCEV *One = getOne(I->getType());
5391  const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5392  const SCEV *LA = getSCEV(TrueVal);
5393  const SCEV *RA = getSCEV(FalseVal);
5394  const SCEV *LDiff = getMinusSCEV(LA, LS);
5395  const SCEV *RDiff = getMinusSCEV(RA, One);
5396  if (LDiff == RDiff)
5397  return getAddExpr(getUMaxExpr(One, LS), LDiff);
5398  }
5399  break;
5400  case ICmpInst::ICMP_EQ:
5401  // n == 0 ? 1+x : n+x -> umax(n, 1)+x
5402  if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5403  isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5404  const SCEV *One = getOne(I->getType());
5405  const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5406  const SCEV *LA = getSCEV(TrueVal);
5407  const SCEV *RA = getSCEV(FalseVal);
5408  const SCEV *LDiff = getMinusSCEV(LA, One);
5409  const SCEV *RDiff = getMinusSCEV(RA, LS);
5410  if (LDiff == RDiff)
5411  return getAddExpr(getUMaxExpr(One, LS), LDiff);
5412  }
5413  break;
5414  default:
5415  break;
5416  }
5417 
5418  return getUnknown(I);
5419 }
5420 
5421 /// Expand GEP instructions into add and multiply operations. This allows them
5422 /// to be analyzed by regular SCEV code.
5423 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5424  // Don't attempt to analyze GEPs over unsized objects.
5425  if (!GEP->getSourceElementType()->isSized())
5426  return getUnknown(GEP);
5427 
5428  SmallVector<const SCEV *, 4> IndexExprs;
5429  for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5430  IndexExprs.push_back(getSCEV(*Index