Sequence.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- Sequence.h - Utility for producing sequences of values ---*- 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. /// \file
  14. /// Provides some synthesis utilities to produce sequences of values. The names
  15. /// are intentionally kept very short as they tend to occur in common and
  16. /// widely used contexts.
  17. ///
  18. /// The `seq(A, B)` function produces a sequence of values from `A` to up to
  19. /// (but not including) `B`, i.e., [`A`, `B`), that can be safely iterated over.
  20. /// `seq` supports both integral (e.g., `int`, `char`, `uint32_t`) and enum
  21. /// types. `seq_inclusive(A, B)` produces a sequence of values from `A` to `B`,
  22. /// including `B`.
  23. ///
  24. /// Examples with integral types:
  25. /// ```
  26. /// for (int x : seq(0, 3))
  27. /// outs() << x << " ";
  28. /// ```
  29. ///
  30. /// Prints: `0 1 2 `.
  31. ///
  32. /// ```
  33. /// for (int x : seq_inclusive(0, 3))
  34. /// outs() << x << " ";
  35. /// ```
  36. ///
  37. /// Prints: `0 1 2 3 `.
  38. ///
  39. /// Similar to `seq` and `seq_inclusive`, the `enum_seq` and
  40. /// `enum_seq_inclusive` functions produce sequences of enum values that can be
  41. /// iterated over.
  42. /// To enable iteration with enum types, you need to either mark enums as safe
  43. /// to iterate on by specializing `enum_iteration_traits`, or opt into
  44. /// potentially unsafe iteration at every callsite by passing
  45. /// `force_iteration_on_noniterable_enum`.
  46. ///
  47. /// Examples with enum types:
  48. /// ```
  49. /// namespace X {
  50. /// enum class MyEnum : unsigned {A = 0, B, C};
  51. /// } // namespace X
  52. ///
  53. /// template <> struct enum_iteration_traits<X::MyEnum> {
  54. /// static contexpr bool is_iterable = true;
  55. /// };
  56. ///
  57. /// class MyClass {
  58. /// public:
  59. /// enum Safe { D = 3, E, F };
  60. /// enum MaybeUnsafe { G = 1, H = 2, I = 4 };
  61. /// };
  62. ///
  63. /// template <> struct enum_iteration_traits<MyClass::Safe> {
  64. /// static contexpr bool is_iterable = true;
  65. /// };
  66. /// ```
  67. ///
  68. /// ```
  69. /// for (auto v : enum_seq(MyClass::Safe::D, MyClass::Safe::F))
  70. /// outs() << int(v) << " ";
  71. /// ```
  72. ///
  73. /// Prints: `3 4 `.
  74. ///
  75. /// ```
  76. /// for (auto v : enum_seq(MyClass::MaybeUnsafe::H, MyClass::MaybeUnsafe::I,
  77. /// force_iteration_on_noniterable_enum))
  78. /// outs() << int(v) << " ";
  79. /// ```
  80. ///
  81. /// Prints: `2 3 `.
  82. ///
  83. //===----------------------------------------------------------------------===//
  84. #ifndef LLVM_ADT_SEQUENCE_H
  85. #define LLVM_ADT_SEQUENCE_H
  86. #include <cassert> // assert
  87. #include <iterator> // std::random_access_iterator_tag
  88. #include <limits> // std::numeric_limits
  89. #include <type_traits> // std::is_integral, std::is_enum, std::underlying_type,
  90. // std::enable_if
  91. #include "llvm/Support/MathExtras.h" // AddOverflow / SubOverflow
  92. namespace llvm {
  93. // Enum traits that marks enums as safe or unsafe to iterate over.
  94. // By default, enum types are *not* considered safe for iteration.
  95. // To allow iteration for your enum type, provide a specialization with
  96. // `is_iterable` set to `true` in the `llvm` namespace.
  97. // Alternatively, you can pass the `force_iteration_on_noniterable_enum` tag
  98. // to `enum_seq` or `enum_seq_inclusive`.
  99. template <typename EnumT> struct enum_iteration_traits {
  100. static constexpr bool is_iterable = false;
  101. };
  102. struct force_iteration_on_noniterable_enum_t {
  103. explicit force_iteration_on_noniterable_enum_t() = default;
  104. };
  105. inline constexpr force_iteration_on_noniterable_enum_t
  106. force_iteration_on_noniterable_enum;
  107. namespace detail {
  108. // Returns whether a value of type U can be represented with type T.
  109. template <typename T, typename U> bool canTypeFitValue(const U Value) {
  110. const intmax_t BotT = intmax_t(std::numeric_limits<T>::min());
  111. const intmax_t BotU = intmax_t(std::numeric_limits<U>::min());
  112. const uintmax_t TopT = uintmax_t(std::numeric_limits<T>::max());
  113. const uintmax_t TopU = uintmax_t(std::numeric_limits<U>::max());
  114. return !((BotT > BotU && Value < static_cast<U>(BotT)) ||
  115. (TopT < TopU && Value > static_cast<U>(TopT)));
  116. }
  117. // An integer type that asserts when:
  118. // - constructed from a value that doesn't fit into intmax_t,
  119. // - casted to a type that cannot hold the current value,
  120. // - its internal representation overflows.
  121. struct CheckedInt {
  122. // Integral constructor, asserts if Value cannot be represented as intmax_t.
  123. template <typename Integral,
  124. std::enable_if_t<std::is_integral<Integral>::value, bool> = 0>
  125. static CheckedInt from(Integral FromValue) {
  126. if (!canTypeFitValue<intmax_t>(FromValue))
  127. assertOutOfBounds();
  128. CheckedInt Result;
  129. Result.Value = static_cast<intmax_t>(FromValue);
  130. return Result;
  131. }
  132. // Enum constructor, asserts if Value cannot be represented as intmax_t.
  133. template <typename Enum,
  134. std::enable_if_t<std::is_enum<Enum>::value, bool> = 0>
  135. static CheckedInt from(Enum FromValue) {
  136. using type = std::underlying_type_t<Enum>;
  137. return from<type>(static_cast<type>(FromValue));
  138. }
  139. // Equality
  140. bool operator==(const CheckedInt &O) const { return Value == O.Value; }
  141. bool operator!=(const CheckedInt &O) const { return Value != O.Value; }
  142. CheckedInt operator+(intmax_t Offset) const {
  143. CheckedInt Result;
  144. if (AddOverflow(Value, Offset, Result.Value))
  145. assertOutOfBounds();
  146. return Result;
  147. }
  148. intmax_t operator-(CheckedInt Other) const {
  149. intmax_t Result;
  150. if (SubOverflow(Value, Other.Value, Result))
  151. assertOutOfBounds();
  152. return Result;
  153. }
  154. // Convert to integral, asserts if Value cannot be represented as Integral.
  155. template <typename Integral,
  156. std::enable_if_t<std::is_integral<Integral>::value, bool> = 0>
  157. Integral to() const {
  158. if (!canTypeFitValue<Integral>(Value))
  159. assertOutOfBounds();
  160. return static_cast<Integral>(Value);
  161. }
  162. // Convert to enum, asserts if Value cannot be represented as Enum's
  163. // underlying type.
  164. template <typename Enum,
  165. std::enable_if_t<std::is_enum<Enum>::value, bool> = 0>
  166. Enum to() const {
  167. using type = std::underlying_type_t<Enum>;
  168. return Enum(to<type>());
  169. }
  170. private:
  171. static void assertOutOfBounds() { assert(false && "Out of bounds"); }
  172. intmax_t Value;
  173. };
  174. template <typename T, bool IsReverse> struct SafeIntIterator {
  175. using iterator_category = std::random_access_iterator_tag;
  176. using value_type = T;
  177. using difference_type = intmax_t;
  178. using pointer = T *;
  179. using reference = T &;
  180. // Construct from T.
  181. explicit SafeIntIterator(T Value) : SI(CheckedInt::from<T>(Value)) {}
  182. // Construct from other direction.
  183. SafeIntIterator(const SafeIntIterator<T, !IsReverse> &O) : SI(O.SI) {}
  184. // Dereference
  185. value_type operator*() const { return SI.to<T>(); }
  186. // Indexing
  187. value_type operator[](intmax_t Offset) const { return *(*this + Offset); }
  188. // Can be compared for equivalence using the equality/inequality operators.
  189. bool operator==(const SafeIntIterator &O) const { return SI == O.SI; }
  190. bool operator!=(const SafeIntIterator &O) const { return SI != O.SI; }
  191. // Comparison
  192. bool operator<(const SafeIntIterator &O) const { return (*this - O) < 0; }
  193. bool operator>(const SafeIntIterator &O) const { return (*this - O) > 0; }
  194. bool operator<=(const SafeIntIterator &O) const { return (*this - O) <= 0; }
  195. bool operator>=(const SafeIntIterator &O) const { return (*this - O) >= 0; }
  196. // Pre Increment/Decrement
  197. void operator++() { offset(1); }
  198. void operator--() { offset(-1); }
  199. // Post Increment/Decrement
  200. SafeIntIterator operator++(int) {
  201. const auto Copy = *this;
  202. ++*this;
  203. return Copy;
  204. }
  205. SafeIntIterator operator--(int) {
  206. const auto Copy = *this;
  207. --*this;
  208. return Copy;
  209. }
  210. // Compound assignment operators
  211. void operator+=(intmax_t Offset) { offset(Offset); }
  212. void operator-=(intmax_t Offset) { offset(-Offset); }
  213. // Arithmetic
  214. SafeIntIterator operator+(intmax_t Offset) const { return add(Offset); }
  215. SafeIntIterator operator-(intmax_t Offset) const { return add(-Offset); }
  216. // Difference
  217. intmax_t operator-(const SafeIntIterator &O) const {
  218. return IsReverse ? O.SI - SI : SI - O.SI;
  219. }
  220. private:
  221. SafeIntIterator(const CheckedInt &SI) : SI(SI) {}
  222. static intmax_t getOffset(intmax_t Offset) {
  223. return IsReverse ? -Offset : Offset;
  224. }
  225. CheckedInt add(intmax_t Offset) const { return SI + getOffset(Offset); }
  226. void offset(intmax_t Offset) { SI = SI + getOffset(Offset); }
  227. CheckedInt SI;
  228. // To allow construction from the other direction.
  229. template <typename, bool> friend struct SafeIntIterator;
  230. };
  231. } // namespace detail
  232. template <typename T> struct iota_range {
  233. using value_type = T;
  234. using reference = T &;
  235. using const_reference = const T &;
  236. using iterator = detail::SafeIntIterator<value_type, false>;
  237. using const_iterator = iterator;
  238. using reverse_iterator = detail::SafeIntIterator<value_type, true>;
  239. using const_reverse_iterator = reverse_iterator;
  240. using difference_type = intmax_t;
  241. using size_type = std::size_t;
  242. explicit iota_range(T Begin, T End, bool Inclusive)
  243. : BeginValue(Begin), PastEndValue(End) {
  244. assert(Begin <= End && "Begin must be less or equal to End.");
  245. if (Inclusive)
  246. ++PastEndValue;
  247. }
  248. size_t size() const { return PastEndValue - BeginValue; }
  249. bool empty() const { return BeginValue == PastEndValue; }
  250. auto begin() const { return const_iterator(BeginValue); }
  251. auto end() const { return const_iterator(PastEndValue); }
  252. auto rbegin() const { return const_reverse_iterator(PastEndValue - 1); }
  253. auto rend() const { return const_reverse_iterator(BeginValue - 1); }
  254. private:
  255. static_assert(std::is_integral<T>::value || std::is_enum<T>::value,
  256. "T must be an integral or enum type");
  257. static_assert(std::is_same<T, std::remove_cv_t<T>>::value,
  258. "T must not be const nor volatile");
  259. iterator BeginValue;
  260. iterator PastEndValue;
  261. };
  262. /// Iterate over an integral type from Begin up to - but not including - End.
  263. /// Note: Begin and End values have to be within [INTMAX_MIN, INTMAX_MAX] for
  264. /// forward iteration (resp. [INTMAX_MIN + 1, INTMAX_MAX] for reverse
  265. /// iteration).
  266. template <typename T, typename = std::enable_if_t<std::is_integral<T>::value &&
  267. !std::is_enum<T>::value>>
  268. auto seq(T Begin, T End) {
  269. return iota_range<T>(Begin, End, false);
  270. }
  271. /// Iterate over an integral type from Begin to End inclusive.
  272. /// Note: Begin and End values have to be within [INTMAX_MIN, INTMAX_MAX - 1]
  273. /// for forward iteration (resp. [INTMAX_MIN + 1, INTMAX_MAX - 1] for reverse
  274. /// iteration).
  275. template <typename T, typename = std::enable_if_t<std::is_integral<T>::value &&
  276. !std::is_enum<T>::value>>
  277. auto seq_inclusive(T Begin, T End) {
  278. return iota_range<T>(Begin, End, true);
  279. }
  280. /// Iterate over an enum type from Begin up to - but not including - End.
  281. /// Note: `enum_seq` will generate each consecutive value, even if no
  282. /// enumerator with that value exists.
  283. /// Note: Begin and End values have to be within [INTMAX_MIN, INTMAX_MAX] for
  284. /// forward iteration (resp. [INTMAX_MIN + 1, INTMAX_MAX] for reverse
  285. /// iteration).
  286. template <typename EnumT,
  287. typename = std::enable_if_t<std::is_enum<EnumT>::value>>
  288. auto enum_seq(EnumT Begin, EnumT End) {
  289. static_assert(enum_iteration_traits<EnumT>::is_iterable,
  290. "Enum type is not marked as iterable.");
  291. return iota_range<EnumT>(Begin, End, false);
  292. }
  293. /// Iterate over an enum type from Begin up to - but not including - End, even
  294. /// when `EnumT` is not marked as safely iterable by `enum_iteration_traits`.
  295. /// Note: `enum_seq` will generate each consecutive value, even if no
  296. /// enumerator with that value exists.
  297. /// Note: Begin and End values have to be within [INTMAX_MIN, INTMAX_MAX] for
  298. /// forward iteration (resp. [INTMAX_MIN + 1, INTMAX_MAX] for reverse
  299. /// iteration).
  300. template <typename EnumT,
  301. typename = std::enable_if_t<std::is_enum<EnumT>::value>>
  302. auto enum_seq(EnumT Begin, EnumT End, force_iteration_on_noniterable_enum_t) {
  303. return iota_range<EnumT>(Begin, End, false);
  304. }
  305. /// Iterate over an enum type from Begin to End inclusive.
  306. /// Note: `enum_seq_inclusive` will generate each consecutive value, even if no
  307. /// enumerator with that value exists.
  308. /// Note: Begin and End values have to be within [INTMAX_MIN, INTMAX_MAX - 1]
  309. /// for forward iteration (resp. [INTMAX_MIN + 1, INTMAX_MAX - 1] for reverse
  310. /// iteration).
  311. template <typename EnumT,
  312. typename = std::enable_if_t<std::is_enum<EnumT>::value>>
  313. auto enum_seq_inclusive(EnumT Begin, EnumT End) {
  314. static_assert(enum_iteration_traits<EnumT>::is_iterable,
  315. "Enum type is not marked as iterable.");
  316. return iota_range<EnumT>(Begin, End, true);
  317. }
  318. /// Iterate over an enum type from Begin to End inclusive, even when `EnumT`
  319. /// is not marked as safely iterable by `enum_iteration_traits`.
  320. /// Note: `enum_seq_inclusive` will generate each consecutive value, even if no
  321. /// enumerator with that value exists.
  322. /// Note: Begin and End values have to be within [INTMAX_MIN, INTMAX_MAX - 1]
  323. /// for forward iteration (resp. [INTMAX_MIN + 1, INTMAX_MAX - 1] for reverse
  324. /// iteration).
  325. template <typename EnumT,
  326. typename = std::enable_if_t<std::is_enum<EnumT>::value>>
  327. auto enum_seq_inclusive(EnumT Begin, EnumT End,
  328. force_iteration_on_noniterable_enum_t) {
  329. return iota_range<EnumT>(Begin, End, true);
  330. }
  331. } // end namespace llvm
  332. #endif // LLVM_ADT_SEQUENCE_H
  333. #ifdef __GNUC__
  334. #pragma GCC diagnostic pop
  335. #endif