ScalarEvolutionExpressions.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Analysis/ScalarEvolutionExpressions.h - SCEV Exprs --*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the classes used to represent and build scalar expressions.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_ANALYSIS_SCALAREVOLUTIONEXPRESSIONS_H
  18. #define LLVM_ANALYSIS_SCALAREVOLUTIONEXPRESSIONS_H
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/iterator_range.h"
  23. #include "llvm/Analysis/ScalarEvolution.h"
  24. #include "llvm/IR/Constants.h"
  25. #include "llvm/IR/ValueHandle.h"
  26. #include "llvm/Support/Casting.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include <cassert>
  29. #include <cstddef>
  30. namespace llvm {
  31. class APInt;
  32. class Constant;
  33. class ConstantInt;
  34. class ConstantRange;
  35. class Loop;
  36. class Type;
  37. class Value;
  38. enum SCEVTypes : unsigned short {
  39. // These should be ordered in terms of increasing complexity to make the
  40. // folders simpler.
  41. scConstant,
  42. scTruncate,
  43. scZeroExtend,
  44. scSignExtend,
  45. scAddExpr,
  46. scMulExpr,
  47. scUDivExpr,
  48. scAddRecExpr,
  49. scUMaxExpr,
  50. scSMaxExpr,
  51. scUMinExpr,
  52. scSMinExpr,
  53. scSequentialUMinExpr,
  54. scPtrToInt,
  55. scUnknown,
  56. scCouldNotCompute
  57. };
  58. /// This class represents a constant integer value.
  59. class SCEVConstant : public SCEV {
  60. friend class ScalarEvolution;
  61. ConstantInt *V;
  62. SCEVConstant(const FoldingSetNodeIDRef ID, ConstantInt *v)
  63. : SCEV(ID, scConstant, 1), V(v) {}
  64. public:
  65. ConstantInt *getValue() const { return V; }
  66. const APInt &getAPInt() const { return getValue()->getValue(); }
  67. Type *getType() const { return V->getType(); }
  68. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  69. static bool classof(const SCEV *S) { return S->getSCEVType() == scConstant; }
  70. };
  71. inline unsigned short computeExpressionSize(ArrayRef<const SCEV *> Args) {
  72. APInt Size(16, 1);
  73. for (const auto *Arg : Args)
  74. Size = Size.uadd_sat(APInt(16, Arg->getExpressionSize()));
  75. return (unsigned short)Size.getZExtValue();
  76. }
  77. /// This is the base class for unary cast operator classes.
  78. class SCEVCastExpr : public SCEV {
  79. protected:
  80. const SCEV *Op;
  81. Type *Ty;
  82. SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, const SCEV *op,
  83. Type *ty);
  84. public:
  85. const SCEV *getOperand() const { return Op; }
  86. const SCEV *getOperand(unsigned i) const {
  87. assert(i == 0 && "Operand index out of range!");
  88. return Op;
  89. }
  90. ArrayRef<const SCEV *> operands() const { return Op; }
  91. size_t getNumOperands() const { return 1; }
  92. Type *getType() const { return Ty; }
  93. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  94. static bool classof(const SCEV *S) {
  95. return S->getSCEVType() == scPtrToInt || S->getSCEVType() == scTruncate ||
  96. S->getSCEVType() == scZeroExtend || S->getSCEVType() == scSignExtend;
  97. }
  98. };
  99. /// This class represents a cast from a pointer to a pointer-sized integer
  100. /// value.
  101. class SCEVPtrToIntExpr : public SCEVCastExpr {
  102. friend class ScalarEvolution;
  103. SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, Type *ITy);
  104. public:
  105. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  106. static bool classof(const SCEV *S) { return S->getSCEVType() == scPtrToInt; }
  107. };
  108. /// This is the base class for unary integral cast operator classes.
  109. class SCEVIntegralCastExpr : public SCEVCastExpr {
  110. protected:
  111. SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
  112. const SCEV *op, Type *ty);
  113. public:
  114. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  115. static bool classof(const SCEV *S) {
  116. return S->getSCEVType() == scTruncate || S->getSCEVType() == scZeroExtend ||
  117. S->getSCEVType() == scSignExtend;
  118. }
  119. };
  120. /// This class represents a truncation of an integer value to a
  121. /// smaller integer value.
  122. class SCEVTruncateExpr : public SCEVIntegralCastExpr {
  123. friend class ScalarEvolution;
  124. SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, Type *ty);
  125. public:
  126. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  127. static bool classof(const SCEV *S) { return S->getSCEVType() == scTruncate; }
  128. };
  129. /// This class represents a zero extension of a small integer value
  130. /// to a larger integer value.
  131. class SCEVZeroExtendExpr : public SCEVIntegralCastExpr {
  132. friend class ScalarEvolution;
  133. SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, const SCEV *op, Type *ty);
  134. public:
  135. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  136. static bool classof(const SCEV *S) {
  137. return S->getSCEVType() == scZeroExtend;
  138. }
  139. };
  140. /// This class represents a sign extension of a small integer value
  141. /// to a larger integer value.
  142. class SCEVSignExtendExpr : public SCEVIntegralCastExpr {
  143. friend class ScalarEvolution;
  144. SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, const SCEV *op, Type *ty);
  145. public:
  146. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  147. static bool classof(const SCEV *S) {
  148. return S->getSCEVType() == scSignExtend;
  149. }
  150. };
  151. /// This node is a base class providing common functionality for
  152. /// n'ary operators.
  153. class SCEVNAryExpr : public SCEV {
  154. protected:
  155. // Since SCEVs are immutable, ScalarEvolution allocates operand
  156. // arrays with its SCEVAllocator, so this class just needs a simple
  157. // pointer rather than a more elaborate vector-like data structure.
  158. // This also avoids the need for a non-trivial destructor.
  159. const SCEV *const *Operands;
  160. size_t NumOperands;
  161. SCEVNAryExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T,
  162. const SCEV *const *O, size_t N)
  163. : SCEV(ID, T, computeExpressionSize(ArrayRef(O, N))), Operands(O),
  164. NumOperands(N) {}
  165. public:
  166. size_t getNumOperands() const { return NumOperands; }
  167. const SCEV *getOperand(unsigned i) const {
  168. assert(i < NumOperands && "Operand index out of range!");
  169. return Operands[i];
  170. }
  171. ArrayRef<const SCEV *> operands() const {
  172. return ArrayRef(Operands, NumOperands);
  173. }
  174. NoWrapFlags getNoWrapFlags(NoWrapFlags Mask = NoWrapMask) const {
  175. return (NoWrapFlags)(SubclassData & Mask);
  176. }
  177. bool hasNoUnsignedWrap() const {
  178. return getNoWrapFlags(FlagNUW) != FlagAnyWrap;
  179. }
  180. bool hasNoSignedWrap() const {
  181. return getNoWrapFlags(FlagNSW) != FlagAnyWrap;
  182. }
  183. bool hasNoSelfWrap() const { return getNoWrapFlags(FlagNW) != FlagAnyWrap; }
  184. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  185. static bool classof(const SCEV *S) {
  186. return S->getSCEVType() == scAddExpr || S->getSCEVType() == scMulExpr ||
  187. S->getSCEVType() == scSMaxExpr || S->getSCEVType() == scUMaxExpr ||
  188. S->getSCEVType() == scSMinExpr || S->getSCEVType() == scUMinExpr ||
  189. S->getSCEVType() == scSequentialUMinExpr ||
  190. S->getSCEVType() == scAddRecExpr;
  191. }
  192. };
  193. /// This node is the base class for n'ary commutative operators.
  194. class SCEVCommutativeExpr : public SCEVNAryExpr {
  195. protected:
  196. SCEVCommutativeExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T,
  197. const SCEV *const *O, size_t N)
  198. : SCEVNAryExpr(ID, T, O, N) {}
  199. public:
  200. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  201. static bool classof(const SCEV *S) {
  202. return S->getSCEVType() == scAddExpr || S->getSCEVType() == scMulExpr ||
  203. S->getSCEVType() == scSMaxExpr || S->getSCEVType() == scUMaxExpr ||
  204. S->getSCEVType() == scSMinExpr || S->getSCEVType() == scUMinExpr;
  205. }
  206. /// Set flags for a non-recurrence without clearing previously set flags.
  207. void setNoWrapFlags(NoWrapFlags Flags) { SubclassData |= Flags; }
  208. };
  209. /// This node represents an addition of some number of SCEVs.
  210. class SCEVAddExpr : public SCEVCommutativeExpr {
  211. friend class ScalarEvolution;
  212. Type *Ty;
  213. SCEVAddExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
  214. : SCEVCommutativeExpr(ID, scAddExpr, O, N) {
  215. auto *FirstPointerTypedOp = find_if(operands(), [](const SCEV *Op) {
  216. return Op->getType()->isPointerTy();
  217. });
  218. if (FirstPointerTypedOp != operands().end())
  219. Ty = (*FirstPointerTypedOp)->getType();
  220. else
  221. Ty = getOperand(0)->getType();
  222. }
  223. public:
  224. Type *getType() const { return Ty; }
  225. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  226. static bool classof(const SCEV *S) { return S->getSCEVType() == scAddExpr; }
  227. };
  228. /// This node represents multiplication of some number of SCEVs.
  229. class SCEVMulExpr : public SCEVCommutativeExpr {
  230. friend class ScalarEvolution;
  231. SCEVMulExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
  232. : SCEVCommutativeExpr(ID, scMulExpr, O, N) {}
  233. public:
  234. Type *getType() const { return getOperand(0)->getType(); }
  235. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  236. static bool classof(const SCEV *S) { return S->getSCEVType() == scMulExpr; }
  237. };
  238. /// This class represents a binary unsigned division operation.
  239. class SCEVUDivExpr : public SCEV {
  240. friend class ScalarEvolution;
  241. std::array<const SCEV *, 2> Operands;
  242. SCEVUDivExpr(const FoldingSetNodeIDRef ID, const SCEV *lhs, const SCEV *rhs)
  243. : SCEV(ID, scUDivExpr, computeExpressionSize({lhs, rhs})) {
  244. Operands[0] = lhs;
  245. Operands[1] = rhs;
  246. }
  247. public:
  248. const SCEV *getLHS() const { return Operands[0]; }
  249. const SCEV *getRHS() const { return Operands[1]; }
  250. size_t getNumOperands() const { return 2; }
  251. const SCEV *getOperand(unsigned i) const {
  252. assert((i == 0 || i == 1) && "Operand index out of range!");
  253. return i == 0 ? getLHS() : getRHS();
  254. }
  255. ArrayRef<const SCEV *> operands() const { return Operands; }
  256. Type *getType() const {
  257. // In most cases the types of LHS and RHS will be the same, but in some
  258. // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
  259. // depend on the type for correctness, but handling types carefully can
  260. // avoid extra casts in the SCEVExpander. The LHS is more likely to be
  261. // a pointer type than the RHS, so use the RHS' type here.
  262. return getRHS()->getType();
  263. }
  264. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  265. static bool classof(const SCEV *S) { return S->getSCEVType() == scUDivExpr; }
  266. };
  267. /// This node represents a polynomial recurrence on the trip count
  268. /// of the specified loop. This is the primary focus of the
  269. /// ScalarEvolution framework; all the other SCEV subclasses are
  270. /// mostly just supporting infrastructure to allow SCEVAddRecExpr
  271. /// expressions to be created and analyzed.
  272. ///
  273. /// All operands of an AddRec are required to be loop invariant.
  274. ///
  275. class SCEVAddRecExpr : public SCEVNAryExpr {
  276. friend class ScalarEvolution;
  277. const Loop *L;
  278. SCEVAddRecExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N,
  279. const Loop *l)
  280. : SCEVNAryExpr(ID, scAddRecExpr, O, N), L(l) {}
  281. public:
  282. Type *getType() const { return getStart()->getType(); }
  283. const SCEV *getStart() const { return Operands[0]; }
  284. const Loop *getLoop() const { return L; }
  285. /// Constructs and returns the recurrence indicating how much this
  286. /// expression steps by. If this is a polynomial of degree N, it
  287. /// returns a chrec of degree N-1. We cannot determine whether
  288. /// the step recurrence has self-wraparound.
  289. const SCEV *getStepRecurrence(ScalarEvolution &SE) const {
  290. if (isAffine())
  291. return getOperand(1);
  292. return SE.getAddRecExpr(
  293. SmallVector<const SCEV *, 3>(operands().drop_front()), getLoop(),
  294. FlagAnyWrap);
  295. }
  296. /// Return true if this represents an expression A + B*x where A
  297. /// and B are loop invariant values.
  298. bool isAffine() const {
  299. // We know that the start value is invariant. This expression is thus
  300. // affine iff the step is also invariant.
  301. return getNumOperands() == 2;
  302. }
  303. /// Return true if this represents an expression A + B*x + C*x^2
  304. /// where A, B and C are loop invariant values. This corresponds
  305. /// to an addrec of the form {L,+,M,+,N}
  306. bool isQuadratic() const { return getNumOperands() == 3; }
  307. /// Set flags for a recurrence without clearing any previously set flags.
  308. /// For AddRec, either NUW or NSW implies NW. Keep track of this fact here
  309. /// to make it easier to propagate flags.
  310. void setNoWrapFlags(NoWrapFlags Flags) {
  311. if (Flags & (FlagNUW | FlagNSW))
  312. Flags = ScalarEvolution::setFlags(Flags, FlagNW);
  313. SubclassData |= Flags;
  314. }
  315. /// Return the value of this chain of recurrences at the specified
  316. /// iteration number.
  317. const SCEV *evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const;
  318. /// Return the value of this chain of recurrences at the specified iteration
  319. /// number. Takes an explicit list of operands to represent an AddRec.
  320. static const SCEV *evaluateAtIteration(ArrayRef<const SCEV *> Operands,
  321. const SCEV *It, ScalarEvolution &SE);
  322. /// Return the number of iterations of this loop that produce
  323. /// values in the specified constant range. Another way of
  324. /// looking at this is that it returns the first iteration number
  325. /// where the value is not in the condition, thus computing the
  326. /// exit count. If the iteration count can't be computed, an
  327. /// instance of SCEVCouldNotCompute is returned.
  328. const SCEV *getNumIterationsInRange(const ConstantRange &Range,
  329. ScalarEvolution &SE) const;
  330. /// Return an expression representing the value of this expression
  331. /// one iteration of the loop ahead.
  332. const SCEVAddRecExpr *getPostIncExpr(ScalarEvolution &SE) const;
  333. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  334. static bool classof(const SCEV *S) {
  335. return S->getSCEVType() == scAddRecExpr;
  336. }
  337. };
  338. /// This node is the base class min/max selections.
  339. class SCEVMinMaxExpr : public SCEVCommutativeExpr {
  340. friend class ScalarEvolution;
  341. static bool isMinMaxType(enum SCEVTypes T) {
  342. return T == scSMaxExpr || T == scUMaxExpr || T == scSMinExpr ||
  343. T == scUMinExpr;
  344. }
  345. protected:
  346. /// Note: Constructing subclasses via this constructor is allowed
  347. SCEVMinMaxExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T,
  348. const SCEV *const *O, size_t N)
  349. : SCEVCommutativeExpr(ID, T, O, N) {
  350. assert(isMinMaxType(T));
  351. // Min and max never overflow
  352. setNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW));
  353. }
  354. public:
  355. Type *getType() const { return getOperand(0)->getType(); }
  356. static bool classof(const SCEV *S) { return isMinMaxType(S->getSCEVType()); }
  357. static enum SCEVTypes negate(enum SCEVTypes T) {
  358. switch (T) {
  359. case scSMaxExpr:
  360. return scSMinExpr;
  361. case scSMinExpr:
  362. return scSMaxExpr;
  363. case scUMaxExpr:
  364. return scUMinExpr;
  365. case scUMinExpr:
  366. return scUMaxExpr;
  367. default:
  368. llvm_unreachable("Not a min or max SCEV type!");
  369. }
  370. }
  371. };
  372. /// This class represents a signed maximum selection.
  373. class SCEVSMaxExpr : public SCEVMinMaxExpr {
  374. friend class ScalarEvolution;
  375. SCEVSMaxExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
  376. : SCEVMinMaxExpr(ID, scSMaxExpr, O, N) {}
  377. public:
  378. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  379. static bool classof(const SCEV *S) { return S->getSCEVType() == scSMaxExpr; }
  380. };
  381. /// This class represents an unsigned maximum selection.
  382. class SCEVUMaxExpr : public SCEVMinMaxExpr {
  383. friend class ScalarEvolution;
  384. SCEVUMaxExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
  385. : SCEVMinMaxExpr(ID, scUMaxExpr, O, N) {}
  386. public:
  387. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  388. static bool classof(const SCEV *S) { return S->getSCEVType() == scUMaxExpr; }
  389. };
  390. /// This class represents a signed minimum selection.
  391. class SCEVSMinExpr : public SCEVMinMaxExpr {
  392. friend class ScalarEvolution;
  393. SCEVSMinExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
  394. : SCEVMinMaxExpr(ID, scSMinExpr, O, N) {}
  395. public:
  396. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  397. static bool classof(const SCEV *S) { return S->getSCEVType() == scSMinExpr; }
  398. };
  399. /// This class represents an unsigned minimum selection.
  400. class SCEVUMinExpr : public SCEVMinMaxExpr {
  401. friend class ScalarEvolution;
  402. SCEVUMinExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
  403. : SCEVMinMaxExpr(ID, scUMinExpr, O, N) {}
  404. public:
  405. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  406. static bool classof(const SCEV *S) { return S->getSCEVType() == scUMinExpr; }
  407. };
  408. /// This node is the base class for sequential/in-order min/max selections.
  409. /// Note that their fundamental difference from SCEVMinMaxExpr's is that they
  410. /// are early-returning upon reaching saturation point.
  411. /// I.e. given `0 umin_seq poison`, the result will be `0`,
  412. /// while the result of `0 umin poison` is `poison`.
  413. class SCEVSequentialMinMaxExpr : public SCEVNAryExpr {
  414. friend class ScalarEvolution;
  415. static bool isSequentialMinMaxType(enum SCEVTypes T) {
  416. return T == scSequentialUMinExpr;
  417. }
  418. /// Set flags for a non-recurrence without clearing previously set flags.
  419. void setNoWrapFlags(NoWrapFlags Flags) { SubclassData |= Flags; }
  420. protected:
  421. /// Note: Constructing subclasses via this constructor is allowed
  422. SCEVSequentialMinMaxExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T,
  423. const SCEV *const *O, size_t N)
  424. : SCEVNAryExpr(ID, T, O, N) {
  425. assert(isSequentialMinMaxType(T));
  426. // Min and max never overflow
  427. setNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW));
  428. }
  429. public:
  430. Type *getType() const { return getOperand(0)->getType(); }
  431. static SCEVTypes getEquivalentNonSequentialSCEVType(SCEVTypes Ty) {
  432. assert(isSequentialMinMaxType(Ty));
  433. switch (Ty) {
  434. case scSequentialUMinExpr:
  435. return scUMinExpr;
  436. default:
  437. llvm_unreachable("Not a sequential min/max type.");
  438. }
  439. }
  440. SCEVTypes getEquivalentNonSequentialSCEVType() const {
  441. return getEquivalentNonSequentialSCEVType(getSCEVType());
  442. }
  443. static bool classof(const SCEV *S) {
  444. return isSequentialMinMaxType(S->getSCEVType());
  445. }
  446. };
  447. /// This class represents a sequential/in-order unsigned minimum selection.
  448. class SCEVSequentialUMinExpr : public SCEVSequentialMinMaxExpr {
  449. friend class ScalarEvolution;
  450. SCEVSequentialUMinExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O,
  451. size_t N)
  452. : SCEVSequentialMinMaxExpr(ID, scSequentialUMinExpr, O, N) {}
  453. public:
  454. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  455. static bool classof(const SCEV *S) {
  456. return S->getSCEVType() == scSequentialUMinExpr;
  457. }
  458. };
  459. /// This means that we are dealing with an entirely unknown SCEV
  460. /// value, and only represent it as its LLVM Value. This is the
  461. /// "bottom" value for the analysis.
  462. class SCEVUnknown final : public SCEV, private CallbackVH {
  463. friend class ScalarEvolution;
  464. /// The parent ScalarEvolution value. This is used to update the
  465. /// parent's maps when the value associated with a SCEVUnknown is
  466. /// deleted or RAUW'd.
  467. ScalarEvolution *SE;
  468. /// The next pointer in the linked list of all SCEVUnknown
  469. /// instances owned by a ScalarEvolution.
  470. SCEVUnknown *Next;
  471. SCEVUnknown(const FoldingSetNodeIDRef ID, Value *V, ScalarEvolution *se,
  472. SCEVUnknown *next)
  473. : SCEV(ID, scUnknown, 1), CallbackVH(V), SE(se), Next(next) {}
  474. // Implement CallbackVH.
  475. void deleted() override;
  476. void allUsesReplacedWith(Value *New) override;
  477. public:
  478. Value *getValue() const { return getValPtr(); }
  479. /// @{
  480. /// Test whether this is a special constant representing a type
  481. /// size, alignment, or field offset in a target-independent
  482. /// manner, and hasn't happened to have been folded with other
  483. /// operations into something unrecognizable. This is mainly only
  484. /// useful for pretty-printing and other situations where it isn't
  485. /// absolutely required for these to succeed.
  486. bool isSizeOf(Type *&AllocTy) const;
  487. bool isAlignOf(Type *&AllocTy) const;
  488. bool isOffsetOf(Type *&STy, Constant *&FieldNo) const;
  489. /// @}
  490. Type *getType() const { return getValPtr()->getType(); }
  491. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  492. static bool classof(const SCEV *S) { return S->getSCEVType() == scUnknown; }
  493. };
  494. /// This class defines a simple visitor class that may be used for
  495. /// various SCEV analysis purposes.
  496. template <typename SC, typename RetVal = void> struct SCEVVisitor {
  497. RetVal visit(const SCEV *S) {
  498. switch (S->getSCEVType()) {
  499. case scConstant:
  500. return ((SC *)this)->visitConstant((const SCEVConstant *)S);
  501. case scPtrToInt:
  502. return ((SC *)this)->visitPtrToIntExpr((const SCEVPtrToIntExpr *)S);
  503. case scTruncate:
  504. return ((SC *)this)->visitTruncateExpr((const SCEVTruncateExpr *)S);
  505. case scZeroExtend:
  506. return ((SC *)this)->visitZeroExtendExpr((const SCEVZeroExtendExpr *)S);
  507. case scSignExtend:
  508. return ((SC *)this)->visitSignExtendExpr((const SCEVSignExtendExpr *)S);
  509. case scAddExpr:
  510. return ((SC *)this)->visitAddExpr((const SCEVAddExpr *)S);
  511. case scMulExpr:
  512. return ((SC *)this)->visitMulExpr((const SCEVMulExpr *)S);
  513. case scUDivExpr:
  514. return ((SC *)this)->visitUDivExpr((const SCEVUDivExpr *)S);
  515. case scAddRecExpr:
  516. return ((SC *)this)->visitAddRecExpr((const SCEVAddRecExpr *)S);
  517. case scSMaxExpr:
  518. return ((SC *)this)->visitSMaxExpr((const SCEVSMaxExpr *)S);
  519. case scUMaxExpr:
  520. return ((SC *)this)->visitUMaxExpr((const SCEVUMaxExpr *)S);
  521. case scSMinExpr:
  522. return ((SC *)this)->visitSMinExpr((const SCEVSMinExpr *)S);
  523. case scUMinExpr:
  524. return ((SC *)this)->visitUMinExpr((const SCEVUMinExpr *)S);
  525. case scSequentialUMinExpr:
  526. return ((SC *)this)
  527. ->visitSequentialUMinExpr((const SCEVSequentialUMinExpr *)S);
  528. case scUnknown:
  529. return ((SC *)this)->visitUnknown((const SCEVUnknown *)S);
  530. case scCouldNotCompute:
  531. return ((SC *)this)->visitCouldNotCompute((const SCEVCouldNotCompute *)S);
  532. }
  533. llvm_unreachable("Unknown SCEV kind!");
  534. }
  535. RetVal visitCouldNotCompute(const SCEVCouldNotCompute *S) {
  536. llvm_unreachable("Invalid use of SCEVCouldNotCompute!");
  537. }
  538. };
  539. /// Visit all nodes in the expression tree using worklist traversal.
  540. ///
  541. /// Visitor implements:
  542. /// // return true to follow this node.
  543. /// bool follow(const SCEV *S);
  544. /// // return true to terminate the search.
  545. /// bool isDone();
  546. template <typename SV> class SCEVTraversal {
  547. SV &Visitor;
  548. SmallVector<const SCEV *, 8> Worklist;
  549. SmallPtrSet<const SCEV *, 8> Visited;
  550. void push(const SCEV *S) {
  551. if (Visited.insert(S).second && Visitor.follow(S))
  552. Worklist.push_back(S);
  553. }
  554. public:
  555. SCEVTraversal(SV &V) : Visitor(V) {}
  556. void visitAll(const SCEV *Root) {
  557. push(Root);
  558. while (!Worklist.empty() && !Visitor.isDone()) {
  559. const SCEV *S = Worklist.pop_back_val();
  560. switch (S->getSCEVType()) {
  561. case scConstant:
  562. case scUnknown:
  563. continue;
  564. case scPtrToInt:
  565. case scTruncate:
  566. case scZeroExtend:
  567. case scSignExtend:
  568. case scAddExpr:
  569. case scMulExpr:
  570. case scUDivExpr:
  571. case scSMaxExpr:
  572. case scUMaxExpr:
  573. case scSMinExpr:
  574. case scUMinExpr:
  575. case scSequentialUMinExpr:
  576. case scAddRecExpr:
  577. for (const auto *Op : S->operands()) {
  578. push(Op);
  579. if (Visitor.isDone())
  580. break;
  581. }
  582. continue;
  583. case scCouldNotCompute:
  584. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  585. }
  586. llvm_unreachable("Unknown SCEV kind!");
  587. }
  588. }
  589. };
  590. /// Use SCEVTraversal to visit all nodes in the given expression tree.
  591. template <typename SV> void visitAll(const SCEV *Root, SV &Visitor) {
  592. SCEVTraversal<SV> T(Visitor);
  593. T.visitAll(Root);
  594. }
  595. /// Return true if any node in \p Root satisfies the predicate \p Pred.
  596. template <typename PredTy>
  597. bool SCEVExprContains(const SCEV *Root, PredTy Pred) {
  598. struct FindClosure {
  599. bool Found = false;
  600. PredTy Pred;
  601. FindClosure(PredTy Pred) : Pred(Pred) {}
  602. bool follow(const SCEV *S) {
  603. if (!Pred(S))
  604. return true;
  605. Found = true;
  606. return false;
  607. }
  608. bool isDone() const { return Found; }
  609. };
  610. FindClosure FC(Pred);
  611. visitAll(Root, FC);
  612. return FC.Found;
  613. }
  614. /// This visitor recursively visits a SCEV expression and re-writes it.
  615. /// The result from each visit is cached, so it will return the same
  616. /// SCEV for the same input.
  617. template <typename SC>
  618. class SCEVRewriteVisitor : public SCEVVisitor<SC, const SCEV *> {
  619. protected:
  620. ScalarEvolution &SE;
  621. // Memoize the result of each visit so that we only compute once for
  622. // the same input SCEV. This is to avoid redundant computations when
  623. // a SCEV is referenced by multiple SCEVs. Without memoization, this
  624. // visit algorithm would have exponential time complexity in the worst
  625. // case, causing the compiler to hang on certain tests.
  626. DenseMap<const SCEV *, const SCEV *> RewriteResults;
  627. public:
  628. SCEVRewriteVisitor(ScalarEvolution &SE) : SE(SE) {}
  629. const SCEV *visit(const SCEV *S) {
  630. auto It = RewriteResults.find(S);
  631. if (It != RewriteResults.end())
  632. return It->second;
  633. auto *Visited = SCEVVisitor<SC, const SCEV *>::visit(S);
  634. auto Result = RewriteResults.try_emplace(S, Visited);
  635. assert(Result.second && "Should insert a new entry");
  636. return Result.first->second;
  637. }
  638. const SCEV *visitConstant(const SCEVConstant *Constant) { return Constant; }
  639. const SCEV *visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) {
  640. const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
  641. return Operand == Expr->getOperand()
  642. ? Expr
  643. : SE.getPtrToIntExpr(Operand, Expr->getType());
  644. }
  645. const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) {
  646. const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
  647. return Operand == Expr->getOperand()
  648. ? Expr
  649. : SE.getTruncateExpr(Operand, Expr->getType());
  650. }
  651. const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
  652. const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
  653. return Operand == Expr->getOperand()
  654. ? Expr
  655. : SE.getZeroExtendExpr(Operand, Expr->getType());
  656. }
  657. const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
  658. const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
  659. return Operand == Expr->getOperand()
  660. ? Expr
  661. : SE.getSignExtendExpr(Operand, Expr->getType());
  662. }
  663. const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
  664. SmallVector<const SCEV *, 2> Operands;
  665. bool Changed = false;
  666. for (const auto *Op : Expr->operands()) {
  667. Operands.push_back(((SC *)this)->visit(Op));
  668. Changed |= Op != Operands.back();
  669. }
  670. return !Changed ? Expr : SE.getAddExpr(Operands);
  671. }
  672. const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
  673. SmallVector<const SCEV *, 2> Operands;
  674. bool Changed = false;
  675. for (const auto *Op : Expr->operands()) {
  676. Operands.push_back(((SC *)this)->visit(Op));
  677. Changed |= Op != Operands.back();
  678. }
  679. return !Changed ? Expr : SE.getMulExpr(Operands);
  680. }
  681. const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) {
  682. auto *LHS = ((SC *)this)->visit(Expr->getLHS());
  683. auto *RHS = ((SC *)this)->visit(Expr->getRHS());
  684. bool Changed = LHS != Expr->getLHS() || RHS != Expr->getRHS();
  685. return !Changed ? Expr : SE.getUDivExpr(LHS, RHS);
  686. }
  687. const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
  688. SmallVector<const SCEV *, 2> Operands;
  689. bool Changed = false;
  690. for (const auto *Op : Expr->operands()) {
  691. Operands.push_back(((SC *)this)->visit(Op));
  692. Changed |= Op != Operands.back();
  693. }
  694. return !Changed ? Expr
  695. : SE.getAddRecExpr(Operands, Expr->getLoop(),
  696. Expr->getNoWrapFlags());
  697. }
  698. const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
  699. SmallVector<const SCEV *, 2> Operands;
  700. bool Changed = false;
  701. for (const auto *Op : Expr->operands()) {
  702. Operands.push_back(((SC *)this)->visit(Op));
  703. Changed |= Op != Operands.back();
  704. }
  705. return !Changed ? Expr : SE.getSMaxExpr(Operands);
  706. }
  707. const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) {
  708. SmallVector<const SCEV *, 2> Operands;
  709. bool Changed = false;
  710. for (const auto *Op : Expr->operands()) {
  711. Operands.push_back(((SC *)this)->visit(Op));
  712. Changed |= Op != Operands.back();
  713. }
  714. return !Changed ? Expr : SE.getUMaxExpr(Operands);
  715. }
  716. const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
  717. SmallVector<const SCEV *, 2> Operands;
  718. bool Changed = false;
  719. for (const auto *Op : Expr->operands()) {
  720. Operands.push_back(((SC *)this)->visit(Op));
  721. Changed |= Op != Operands.back();
  722. }
  723. return !Changed ? Expr : SE.getSMinExpr(Operands);
  724. }
  725. const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
  726. SmallVector<const SCEV *, 2> Operands;
  727. bool Changed = false;
  728. for (const auto *Op : Expr->operands()) {
  729. Operands.push_back(((SC *)this)->visit(Op));
  730. Changed |= Op != Operands.back();
  731. }
  732. return !Changed ? Expr : SE.getUMinExpr(Operands);
  733. }
  734. const SCEV *visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
  735. SmallVector<const SCEV *, 2> Operands;
  736. bool Changed = false;
  737. for (const auto *Op : Expr->operands()) {
  738. Operands.push_back(((SC *)this)->visit(Op));
  739. Changed |= Op != Operands.back();
  740. }
  741. return !Changed ? Expr : SE.getUMinExpr(Operands, /*Sequential=*/true);
  742. }
  743. const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
  744. const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
  745. return Expr;
  746. }
  747. };
  748. using ValueToValueMap = DenseMap<const Value *, Value *>;
  749. using ValueToSCEVMapTy = DenseMap<const Value *, const SCEV *>;
  750. /// The SCEVParameterRewriter takes a scalar evolution expression and updates
  751. /// the SCEVUnknown components following the Map (Value -> SCEV).
  752. class SCEVParameterRewriter : public SCEVRewriteVisitor<SCEVParameterRewriter> {
  753. public:
  754. static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
  755. ValueToSCEVMapTy &Map) {
  756. SCEVParameterRewriter Rewriter(SE, Map);
  757. return Rewriter.visit(Scev);
  758. }
  759. SCEVParameterRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
  760. : SCEVRewriteVisitor(SE), Map(M) {}
  761. const SCEV *visitUnknown(const SCEVUnknown *Expr) {
  762. auto I = Map.find(Expr->getValue());
  763. if (I == Map.end())
  764. return Expr;
  765. return I->second;
  766. }
  767. private:
  768. ValueToSCEVMapTy &Map;
  769. };
  770. using LoopToScevMapT = DenseMap<const Loop *, const SCEV *>;
  771. /// The SCEVLoopAddRecRewriter takes a scalar evolution expression and applies
  772. /// the Map (Loop -> SCEV) to all AddRecExprs.
  773. class SCEVLoopAddRecRewriter
  774. : public SCEVRewriteVisitor<SCEVLoopAddRecRewriter> {
  775. public:
  776. SCEVLoopAddRecRewriter(ScalarEvolution &SE, LoopToScevMapT &M)
  777. : SCEVRewriteVisitor(SE), Map(M) {}
  778. static const SCEV *rewrite(const SCEV *Scev, LoopToScevMapT &Map,
  779. ScalarEvolution &SE) {
  780. SCEVLoopAddRecRewriter Rewriter(SE, Map);
  781. return Rewriter.visit(Scev);
  782. }
  783. const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
  784. SmallVector<const SCEV *, 2> Operands;
  785. for (const SCEV *Op : Expr->operands())
  786. Operands.push_back(visit(Op));
  787. const Loop *L = Expr->getLoop();
  788. if (0 == Map.count(L))
  789. return SE.getAddRecExpr(Operands, L, Expr->getNoWrapFlags());
  790. return SCEVAddRecExpr::evaluateAtIteration(Operands, Map[L], SE);
  791. }
  792. private:
  793. LoopToScevMapT &Map;
  794. };
  795. } // end namespace llvm
  796. #endif // LLVM_ANALYSIS_SCALAREVOLUTIONEXPRESSIONS_H
  797. #ifdef __GNUC__
  798. #pragma GCC diagnostic pop
  799. #endif