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