Bitfields.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-- llvm/ADT/Bitfield.h - Get and Set bits in an integer ---*- 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. /// \file
  15. /// This file implements methods to test, set and extract typed bits from packed
  16. /// unsigned integers.
  17. ///
  18. /// Why not C++ bitfields?
  19. /// ----------------------
  20. /// C++ bitfields do not offer control over the bit layout nor consistent
  21. /// behavior when it comes to out of range values.
  22. /// For instance, the layout is implementation defined and adjacent bits may be
  23. /// packed together but are not required to. This is problematic when storage is
  24. /// sparse and data must be stored in a particular integer type.
  25. ///
  26. /// The methods provided in this file ensure precise control over the
  27. /// layout/storage as well as protection against out of range values.
  28. ///
  29. /// Usage example
  30. /// -------------
  31. /// \code{.cpp}
  32. /// uint8_t Storage = 0;
  33. ///
  34. /// // Store and retrieve a single bit as bool.
  35. /// using Bool = Bitfield::Element<bool, 0, 1>;
  36. /// Bitfield::set<Bool>(Storage, true);
  37. /// EXPECT_EQ(Storage, 0b00000001);
  38. /// // ^
  39. /// EXPECT_EQ(Bitfield::get<Bool>(Storage), true);
  40. ///
  41. /// // Store and retrieve a 2 bit typed enum.
  42. /// // Note: enum underlying type must be unsigned.
  43. /// enum class SuitEnum : uint8_t { CLUBS, DIAMONDS, HEARTS, SPADES };
  44. /// // Note: enum maximum value needs to be passed in as last parameter.
  45. /// using Suit = Bitfield::Element<SuitEnum, 1, 2, SuitEnum::SPADES>;
  46. /// Bitfield::set<Suit>(Storage, SuitEnum::HEARTS);
  47. /// EXPECT_EQ(Storage, 0b00000101);
  48. /// // ^^
  49. /// EXPECT_EQ(Bitfield::get<Suit>(Storage), SuitEnum::HEARTS);
  50. ///
  51. /// // Store and retrieve a 5 bit value as unsigned.
  52. /// using Value = Bitfield::Element<unsigned, 3, 5>;
  53. /// Bitfield::set<Value>(Storage, 10);
  54. /// EXPECT_EQ(Storage, 0b01010101);
  55. /// // ^^^^^
  56. /// EXPECT_EQ(Bitfield::get<Value>(Storage), 10U);
  57. ///
  58. /// // Interpret the same 5 bit value as signed.
  59. /// using SignedValue = Bitfield::Element<int, 3, 5>;
  60. /// Bitfield::set<SignedValue>(Storage, -2);
  61. /// EXPECT_EQ(Storage, 0b11110101);
  62. /// // ^^^^^
  63. /// EXPECT_EQ(Bitfield::get<SignedValue>(Storage), -2);
  64. ///
  65. /// // Ability to efficiently test if a field is non zero.
  66. /// EXPECT_TRUE(Bitfield::test<Value>(Storage));
  67. ///
  68. /// // Alter Storage changes value.
  69. /// Storage = 0;
  70. /// EXPECT_EQ(Bitfield::get<Bool>(Storage), false);
  71. /// EXPECT_EQ(Bitfield::get<Suit>(Storage), SuitEnum::CLUBS);
  72. /// EXPECT_EQ(Bitfield::get<Value>(Storage), 0U);
  73. /// EXPECT_EQ(Bitfield::get<SignedValue>(Storage), 0);
  74. ///
  75. /// Storage = 255;
  76. /// EXPECT_EQ(Bitfield::get<Bool>(Storage), true);
  77. /// EXPECT_EQ(Bitfield::get<Suit>(Storage), SuitEnum::SPADES);
  78. /// EXPECT_EQ(Bitfield::get<Value>(Storage), 31U);
  79. /// EXPECT_EQ(Bitfield::get<SignedValue>(Storage), -1);
  80. /// \endcode
  81. ///
  82. //===----------------------------------------------------------------------===//
  83. #ifndef LLVM_ADT_BITFIELDS_H
  84. #define LLVM_ADT_BITFIELDS_H
  85. #include <cassert>
  86. #include <climits> // CHAR_BIT
  87. #include <cstddef> // size_t
  88. #include <cstdint> // uintXX_t
  89. #include <limits> // numeric_limits
  90. #include <type_traits>
  91. namespace llvm {
  92. namespace bitfields_details {
  93. /// A struct defining useful bit patterns for n-bits integer types.
  94. template <typename T, unsigned Bits> struct BitPatterns {
  95. /// Bit patterns are forged using the equivalent `Unsigned` type because of
  96. /// undefined operations over signed types (e.g. Bitwise shift operators).
  97. /// Moreover same size casting from unsigned to signed is well defined but not
  98. /// the other way around.
  99. using Unsigned = typename std::make_unsigned<T>::type;
  100. static_assert(sizeof(Unsigned) == sizeof(T), "Types must have same size");
  101. static constexpr unsigned TypeBits = sizeof(Unsigned) * CHAR_BIT;
  102. static_assert(TypeBits >= Bits, "n-bit must fit in T");
  103. /// e.g. with TypeBits == 8 and Bits == 6.
  104. static constexpr Unsigned AllZeros = Unsigned(0); // 00000000
  105. static constexpr Unsigned AllOnes = ~Unsigned(0); // 11111111
  106. static constexpr Unsigned Umin = AllZeros; // 00000000
  107. static constexpr Unsigned Umax = AllOnes >> (TypeBits - Bits); // 00111111
  108. static constexpr Unsigned SignBitMask = Unsigned(1) << (Bits - 1); // 00100000
  109. static constexpr Unsigned Smax = Umax >> 1U; // 00011111
  110. static constexpr Unsigned Smin = ~Smax; // 11100000
  111. static constexpr Unsigned SignExtend = Unsigned(Smin << 1U); // 11000000
  112. };
  113. /// `Compressor` is used to manipulate the bits of a (possibly signed) integer
  114. /// type so it can be packed and unpacked into a `bits` sized integer,
  115. /// `Compressor` is specialized on signed-ness so no runtime cost is incurred.
  116. /// The `pack` method also checks that the passed in `UserValue` is valid.
  117. template <typename T, unsigned Bits, bool = std::is_unsigned<T>::value>
  118. struct Compressor {
  119. static_assert(std::is_unsigned<T>::value, "T is unsigned");
  120. using BP = BitPatterns<T, Bits>;
  121. static T pack(T UserValue, T UserMaxValue) {
  122. assert(UserValue <= UserMaxValue && "value is too big");
  123. assert(UserValue <= BP::Umax && "value is too big");
  124. return UserValue;
  125. }
  126. static T unpack(T StorageValue) { return StorageValue; }
  127. };
  128. template <typename T, unsigned Bits> struct Compressor<T, Bits, false> {
  129. static_assert(std::is_signed<T>::value, "T is signed");
  130. using BP = BitPatterns<T, Bits>;
  131. static T pack(T UserValue, T UserMaxValue) {
  132. assert(UserValue <= UserMaxValue && "value is too big");
  133. assert(UserValue <= T(BP::Smax) && "value is too big");
  134. assert(UserValue >= T(BP::Smin) && "value is too small");
  135. if (UserValue < 0)
  136. UserValue &= ~BP::SignExtend;
  137. return UserValue;
  138. }
  139. static T unpack(T StorageValue) {
  140. if (StorageValue >= T(BP::SignBitMask))
  141. StorageValue |= BP::SignExtend;
  142. return StorageValue;
  143. }
  144. };
  145. /// Impl is where Bifield description and Storage are put together to interact
  146. /// with values.
  147. template <typename Bitfield, typename StorageType> struct Impl {
  148. static_assert(std::is_unsigned<StorageType>::value,
  149. "Storage must be unsigned");
  150. using IntegerType = typename Bitfield::IntegerType;
  151. using C = Compressor<IntegerType, Bitfield::Bits>;
  152. using BP = BitPatterns<StorageType, Bitfield::Bits>;
  153. static constexpr size_t StorageBits = sizeof(StorageType) * CHAR_BIT;
  154. static_assert(Bitfield::FirstBit <= StorageBits, "Data must fit in mask");
  155. static_assert(Bitfield::LastBit <= StorageBits, "Data must fit in mask");
  156. static constexpr StorageType Mask = BP::Umax << Bitfield::Shift;
  157. /// Checks `UserValue` is within bounds and packs it between `FirstBit` and
  158. /// `LastBit` of `Packed` leaving the rest unchanged.
  159. static void update(StorageType &Packed, IntegerType UserValue) {
  160. const StorageType StorageValue = C::pack(UserValue, Bitfield::UserMaxValue);
  161. Packed &= ~Mask;
  162. Packed |= StorageValue << Bitfield::Shift;
  163. }
  164. /// Interprets bits between `FirstBit` and `LastBit` of `Packed` as
  165. /// an`IntegerType`.
  166. static IntegerType extract(StorageType Packed) {
  167. const StorageType StorageValue = (Packed & Mask) >> Bitfield::Shift;
  168. return C::unpack(StorageValue);
  169. }
  170. /// Interprets bits between `FirstBit` and `LastBit` of `Packed` as
  171. /// an`IntegerType`.
  172. static StorageType test(StorageType Packed) { return Packed & Mask; }
  173. };
  174. /// `Bitfield` deals with the following type:
  175. /// - unsigned enums
  176. /// - signed and unsigned integer
  177. /// - `bool`
  178. /// Internally though we only manipulate integer with well defined and
  179. /// consistent semantics, this excludes typed enums and `bool` that are replaced
  180. /// with their unsigned counterparts. The correct type is restored in the public
  181. /// API.
  182. template <typename T, bool = std::is_enum<T>::value>
  183. struct ResolveUnderlyingType {
  184. using type = typename std::underlying_type<T>::type;
  185. };
  186. template <typename T> struct ResolveUnderlyingType<T, false> {
  187. using type = T;
  188. };
  189. template <> struct ResolveUnderlyingType<bool, false> {
  190. /// In case sizeof(bool) != 1, replace `void` by an additionnal
  191. /// std::conditional.
  192. using type = std::conditional<sizeof(bool) == 1, uint8_t, void>::type;
  193. };
  194. } // namespace bitfields_details
  195. /// Holds functions to get, set or test bitfields.
  196. struct Bitfield {
  197. /// Describes an element of a Bitfield. This type is then used with the
  198. /// Bitfield static member functions.
  199. /// \tparam T The type of the field once in unpacked form.
  200. /// \tparam Offset The position of the first bit.
  201. /// \tparam Size The size of the field.
  202. /// \tparam MaxValue For enums the maximum enum allowed.
  203. template <typename T, unsigned Offset, unsigned Size,
  204. T MaxValue = std::is_enum<T>::value
  205. ? T(0) // coupled with static_assert below
  206. : std::numeric_limits<T>::max()>
  207. struct Element {
  208. using Type = T;
  209. using IntegerType =
  210. typename bitfields_details::ResolveUnderlyingType<T>::type;
  211. static constexpr unsigned Shift = Offset;
  212. static constexpr unsigned Bits = Size;
  213. static constexpr unsigned FirstBit = Offset;
  214. static constexpr unsigned LastBit = Shift + Bits - 1;
  215. static constexpr unsigned NextBit = Shift + Bits;
  216. private:
  217. template <typename, typename> friend struct bitfields_details::Impl;
  218. static_assert(Bits > 0, "Bits must be non zero");
  219. static constexpr size_t TypeBits = sizeof(IntegerType) * CHAR_BIT;
  220. static_assert(Bits <= TypeBits, "Bits may not be greater than T size");
  221. static_assert(!std::is_enum<T>::value || MaxValue != T(0),
  222. "Enum Bitfields must provide a MaxValue");
  223. static_assert(!std::is_enum<T>::value ||
  224. std::is_unsigned<IntegerType>::value,
  225. "Enum must be unsigned");
  226. static_assert(std::is_integral<IntegerType>::value &&
  227. std::numeric_limits<IntegerType>::is_integer,
  228. "IntegerType must be an integer type");
  229. static constexpr IntegerType UserMaxValue =
  230. static_cast<IntegerType>(MaxValue);
  231. };
  232. /// Unpacks the field from the `Packed` value.
  233. template <typename Bitfield, typename StorageType>
  234. static typename Bitfield::Type get(StorageType Packed) {
  235. using I = bitfields_details::Impl<Bitfield, StorageType>;
  236. return static_cast<typename Bitfield::Type>(I::extract(Packed));
  237. }
  238. /// Return a non-zero value if the field is non-zero.
  239. /// It is more efficient than `getField`.
  240. template <typename Bitfield, typename StorageType>
  241. static StorageType test(StorageType Packed) {
  242. using I = bitfields_details::Impl<Bitfield, StorageType>;
  243. return I::test(Packed);
  244. }
  245. /// Sets the typed value in the provided `Packed` value.
  246. /// The method will asserts if the provided value is too big to fit in.
  247. template <typename Bitfield, typename StorageType>
  248. static void set(StorageType &Packed, typename Bitfield::Type Value) {
  249. using I = bitfields_details::Impl<Bitfield, StorageType>;
  250. I::update(Packed, static_cast<typename Bitfield::IntegerType>(Value));
  251. }
  252. /// Returns whether the two bitfields share common bits.
  253. template <typename A, typename B> static constexpr bool isOverlapping() {
  254. return A::LastBit >= B::FirstBit && B::LastBit >= A::FirstBit;
  255. }
  256. template <typename A> static constexpr bool areContiguous() { return true; }
  257. template <typename A, typename B, typename... Others>
  258. static constexpr bool areContiguous() {
  259. return A::NextBit == B::FirstBit && areContiguous<B, Others...>();
  260. }
  261. };
  262. } // namespace llvm
  263. #endif // LLVM_ADT_BITFIELDS_H
  264. #ifdef __GNUC__
  265. #pragma GCC diagnostic pop
  266. #endif