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