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