ScalarEvolutionExpressions.h 32 KB

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