diff --git a/llvm/include/llvm/ADT/Bitfields.h b/llvm/include/llvm/ADT/Bitfields.h new file mode 100644 --- /dev/null +++ b/llvm/include/llvm/ADT/Bitfields.h @@ -0,0 +1,270 @@ +//===-- llvm/ADT/Bitfield.h - Get and Set bits in an integer ---*- C++ -*--===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// This file implements methods to test, set and extract typed bits from packed +/// unsigned integers. +/// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_ADT_BITFIELDS_H +#define LLVM_ADT_BITFIELDS_H + +#include +#include // CHAR_BIT +#include // size_t +#include // uintXX_t +#include // numeric_limits +#include + +/// Helpers to pack / unpack typed bitfields into an unsigned integer. +/// e.g. +/// +/// uint8_t storage = 0; +/// +/// // Store and retrieve a single bit as bool. +/// using Bool = Bitfield; +/// setField(storage, true); +/// EXPECT_EQ(storage, 0b00000001); +/// // ^ +/// EXPECT_EQ(getField(storage), true); +/// +/// // Store and retrieve a 2 bit typed enum. +/// // Note: enum underlying type must be unsigned. +/// enum class SuitEnum : uint8_t { CLUBS, DIAMONDS, HEARTS, SPADES }; +/// // Note: enum maximum value needs to be passed in. +/// using Suit = Bitfield; +/// setField(storage, SuitEnum::HEARTS); +/// EXPECT_EQ(storage, 0b00000101); +/// // ^^ +/// EXPECT_EQ(getField(storage), SuitEnum::HEARTS); +/// +/// // Store and retrieve a 5 bit value as unsigned. +/// using Value = Bitfield; +/// setField(storage, 10); +/// EXPECT_EQ(storage, 0b01010101); +/// // ^^^^^ +/// EXPECT_EQ(getField(storage), 10U); +/// +/// // Interpret the same 5 bit value as signed. +/// using SignedValue = Bitfield; +/// setField(storage, -2); +/// EXPECT_EQ(storage, 0b11110101); +/// // ^^^^^ +/// EXPECT_EQ(getField(storage), -2); +/// +/// // Ability to efficiently test if a field is non zero. +/// EXPECT_TRUE(testField(storage) != 0U); +/// +/// // Alter storage changes value. +/// storage = 0; +/// EXPECT_EQ(getField(storage), false); +/// EXPECT_EQ(getField(storage), SuitEnum::CLUBS); +/// EXPECT_EQ(getField(storage), 0U); +/// EXPECT_EQ(getField(storage), 0); +/// +/// storage = 255; +/// EXPECT_EQ(getField(storage), true); +/// EXPECT_EQ(getField(storage), SuitEnum::SPADES); +/// EXPECT_EQ(getField(storage), 31U); +/// EXPECT_EQ(getField(storage), -1); + +namespace llvm { + +namespace details { + +/// A struct defining useful bit patterns for n-bits integer types. +template struct BitPatterns { + // Bit patterns are forged using the equivalent unsigned type U because of + // undefined operations over signed types (e.g. Bitwise shift operators). + // Moreover same size casting from unsigned to signed is well defined but the + // opposite is not. + using U = typename std::make_unsigned::type; + static_assert(sizeof(U) == sizeof(T), "Types must have same size"); + + static constexpr unsigned type_bits = sizeof(U) * CHAR_BIT; + static_assert(type_bits >= bits, "n-bit must fit in T"); + + // e.g. with type_bits == 8 and bits == 6. + static constexpr U all_zeros = U(0); // 0b00000000 + static constexpr U all_ones = ~U(0); // 0b11111111 + static constexpr U umin = all_zeros; // 0b00000000 + static constexpr U umax = all_ones >> (type_bits - bits); // 0b00111111 + static constexpr U sign_bit_mask = U(1) << (bits - 1U); // 0b00100000 + static constexpr U smax = umax >> 1U; // 0b00011111 + static constexpr U smin = ~smax; // 0b11100000 + static constexpr U sign_extend = smin << 1U; // 0b11000000 +}; + +/// `Compressor` is used to manipulate the bits of a (possibly signed) integer +/// type so it can be packed and unpacked into a `bits` sized integer, +/// `Compressor` is specialized on signed-ness so no runtime cost is incurred. +/// The `pack` method also checks that the passed in `user_value` is valid. +template ::value> +struct Compressor { + static_assert(std::is_unsigned::value, "type is unsigned"); + using BP = BitPatterns; + + static type pack(type user_value, type user_max_value) { + assert(user_value <= user_max_value && "value is too big"); + assert(user_value <= BP::umax && "value is too big"); + return user_value; + } + + static type unpack(type storage_value) { return storage_value; } +}; + +template struct Compressor { + static_assert(std::is_signed::value, "type is signed"); + using BP = BitPatterns; + + static type pack(type user_value, type user_max_value) { + assert(user_value <= user_max_value && "value is too big"); + assert(user_value <= type(BP::smax) && "value is too big"); + assert(user_value >= type(BP::smin) && "value is too small"); + if (user_value < 0) + user_value &= ~BP::sign_extend; + return user_value; + } + + static type unpack(type storage_value) { + if (storage_value >= type(BP::sign_bit_mask)) + storage_value |= BP::sign_extend; + return storage_value; + } +}; + +/// `bitfield_properties` stores important properties about the Bitfield. +/// It only deals with integer types (conversion from/to enum/bool are done +/// outside of this template). +template ::max(), + T MinValue = std::numeric_limits::min()> +struct bitfield_properties { + using integer_type = T; + static_assert(std::is_integral::value && + std::numeric_limits::is_integer, + "T must be an integer type"); + + static constexpr size_t type_bits = sizeof(integer_type) * CHAR_BIT; + static constexpr unsigned offset = Offset; + static constexpr unsigned bits = Bits; + static constexpr unsigned first_bit = offset; + static constexpr unsigned last_bit = offset + bits; + static constexpr integer_type min_value = MinValue; + static constexpr integer_type max_value = MaxValue; + + static_assert(bits > 0, "Bits must be non zero"); + static_assert(bits <= type_bits, "Bits may not be greater than T size"); + + /// Impl is where Bifield description and storage are put together to interact + /// with values. + template struct Impl { + static_assert(std::is_unsigned::value, + "Storage must be unsigned"); + using C = Compressor; + using BP = BitPatterns; + + static constexpr size_t storage_bits = sizeof(storage_type) * CHAR_BIT; + static_assert(first_bit <= storage_bits, "Data must fit in mask"); + static_assert(last_bit <= storage_bits, "Data must fit in mask"); + static constexpr storage_type mask = BP::umax << offset; + + /// Checks `user_value` is within bounds and packs it between `first_bit` + /// and `last_bit` of `packed_value` leaving the rest unchanged. + static void Update(storage_type &packed, integer_type user_value) { + const storage_type storage_value = C::pack(user_value, max_value); + packed &= ~mask; + packed |= storage_value << offset; + } + + /// Interprets bits between `first_bit` and `last_bit` of `packed` as an + /// `integer_value`. + static integer_type Extract(storage_type packed) { + const storage_type storage_value = (packed & mask) >> offset; + return C::unpack(storage_value); + } + }; +}; + +/// `Bitfield` deals with unsigned enums, signed/unsigned integer and `bool` +/// internally though we only manipulate integer with well defined and +/// consistent semantic, this excludes typed enums and `bool` that are +/// replaced with their unsigned counterparts. +/// The correct type is restored in the public API. +template ::value> +struct resolve_underlying_type { + using type = typename std::underlying_type::type; +}; +template struct resolve_underlying_type { + using type = T; +}; +template <> struct resolve_underlying_type { + /// In case sizeof(bool) != 1, replace `void` by an additionnal + /// std::conditionnal. + using type = std::conditional::type; +}; + +} // namespace details + +/// A struct to hold the bitfield informations. +/// \param Type, the type of the field once in unpacked form, +/// \param Offset, the position of the first bit, +/// \param Size, the size of the field, +/// \param MaxValue, For enums the maximum enum allowed. +template ::value + ? Type(0) // coupled with static_assert below + : std::numeric_limits::max()> +struct Bitfield { + using type = Type; + using integer_type = typename details::resolve_underlying_type::type; + using properties = typename details::bitfield_properties< + integer_type, Offset, Size, static_cast(MaxValue)>; + + static constexpr bool is_enum = std::is_enum::value; + static_assert(!is_enum || MaxValue != Type(0), + "Enum Bitfields must provide a MaxValue"); + static_assert(!is_enum || std::is_unsigned::value, + "Enum must be unsigned"); +}; + +/// Returns whether the two bitfields share common bits. +template static constexpr bool isOverlapping() { + using PA = typename A::properties; + using PB = typename B::properties; + return PA::last_bit > PB::first_bit && PB::last_bit > PA::first_bit; +} + +/// Unpacks the field from the packed value. +template +static typename Bitfield::type getField(StorageType packed) { + using Impl = typename Bitfield::properties::template Impl; + return static_cast(Impl::Extract(packed)); +} + +/// Return a non-zero value if the field is non-zero. +/// It is more efficient than `getField`. +template +static StorageType testField(StorageType packed) { + using Impl = typename Bitfield::properties::template Impl; + return packed & Impl::mask; +} + +/// Sets the typed value in the provided packed value. +/// The method will asserts if the provided value is too big to fit in the +/// packed field. +template +static void setField(StorageType &packed, typename Bitfield::type value) { + using Impl = typename Bitfield::properties::template Impl; + Impl::Update(packed, static_cast(value)); +} + +} // namespace llvm + +#endif // LLVM_ADT_BITFIELDS_H \ No newline at end of file diff --git a/llvm/unittests/ADT/BitFieldsTest.cpp b/llvm/unittests/ADT/BitFieldsTest.cpp new file mode 100644 --- /dev/null +++ b/llvm/unittests/ADT/BitFieldsTest.cpp @@ -0,0 +1,244 @@ +//===- llvm/unittests/ADT/BitFieldsTest.cpp - BitFields unit tests --------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "llvm/ADT/Bitfields.h" +#include "gtest/gtest.h" + +using namespace llvm; + +namespace { + +TEST(BitfieldsTest, Example) { + uint8_t storage = 0; + + // Store and retrieve a single bit as bool. + using Bool = Bitfield; + setField(storage, true); + EXPECT_EQ(storage, 0b00000001); + // ^ + EXPECT_EQ(getField(storage), true); + + // Store and retrieve a 2 bit typed enum. + // Note: enum underlying type must be unsigned. + enum class SuitEnum : uint8_t { CLUBS, DIAMONDS, HEARTS, SPADES }; + // Note: enum maximum value needs to be passed in. + using Suit = Bitfield; + setField(storage, SuitEnum::HEARTS); + EXPECT_EQ(storage, 0b00000101); + // ^^ + EXPECT_EQ(getField(storage), SuitEnum::HEARTS); + + // Store and retrieve a 5 bit value as unsigned. + using Value = Bitfield; + setField(storage, 10); + EXPECT_EQ(storage, 0b01010101); + // ^^^^^ + EXPECT_EQ(getField(storage), 10U); + + // Interpret the same 5 bit value as signed. + using SignedValue = Bitfield; + setField(storage, -2); + EXPECT_EQ(storage, 0b11110101); + // ^^^^^ + EXPECT_EQ(getField(storage), -2); + + // Ability to efficiently test if a field is non zero. + EXPECT_TRUE(testField(storage) != 0U); + + // Alter storage changes value. + storage = 0; + EXPECT_EQ(getField(storage), false); + EXPECT_EQ(getField(storage), SuitEnum::CLUBS); + EXPECT_EQ(getField(storage), 0U); + EXPECT_EQ(getField(storage), 0); + + storage = 255; + EXPECT_EQ(getField(storage), true); + EXPECT_EQ(getField(storage), SuitEnum::SPADES); + EXPECT_EQ(getField(storage), 31U); + EXPECT_EQ(getField(storage), -1); +} + +TEST(BitfieldsTest, FirstBit) { + uint8_t storage = 0; + using FirstBit = Bitfield; + // Set true + setField(storage, true); + EXPECT_EQ(getField(storage), true); + EXPECT_EQ(storage, 0x1ULL); + // Set false + setField(storage, false); + EXPECT_EQ(getField(storage), false); + EXPECT_EQ(storage, 0x0ULL); +} + +TEST(BitfieldsTest, SecondBit) { + uint8_t storage = 0; + using SecondBit = Bitfield; + // Set true + setField(storage, true); + EXPECT_EQ(getField(storage), true); + EXPECT_EQ(storage, 0x2ULL); + // Set false + setField(storage, false); + EXPECT_EQ(getField(storage), false); + EXPECT_EQ(storage, 0x0ULL); +} + +TEST(BitfieldsTest, LastBit) { + uint8_t storage = 0; + using LastBit = Bitfield; + // Set true + setField(storage, true); + EXPECT_EQ(getField(storage), true); + EXPECT_EQ(storage, 0x80ULL); + // Set false + setField(storage, false); + EXPECT_EQ(getField(storage), false); + EXPECT_EQ(storage, 0x0ULL); +} + +TEST(BitfieldsTest, LastBitUint64) { + uint64_t storage = 0; + using LastBit = Bitfield; + // Set true + setField(storage, true); + EXPECT_EQ(getField(storage), true); + EXPECT_EQ(storage, 0x8000000000000000ULL); + // Set false + setField(storage, false); + EXPECT_EQ(getField(storage), false); + EXPECT_EQ(storage, 0x0ULL); +} + +TEST(BitfieldsTest, Enum) { + enum Enum { Zero = 0, Two = 2, LAST = Two }; + + uint8_t storage = 0; + using OrderingField = Bitfield; + EXPECT_EQ(getField(storage), Zero); + setField(storage, Two); + EXPECT_EQ(getField(storage), Two); + EXPECT_EQ(storage, 0b00000100); + // value 2 in ^^ +} + +TEST(BitfieldsTest, EnumClass) { + enum class Enum : unsigned { Zero = 0, Two = 2, LAST = Two }; + + uint8_t storage = 0; + using OrderingField = Bitfield; + EXPECT_EQ(getField(storage), Enum::Zero); + setField(storage, Enum::Two); + EXPECT_EQ(getField(storage), Enum::Two); + EXPECT_EQ(storage, 0b00000100); + // value 2 in ^^ +} + +TEST(BitfieldsTest, OneBitSigned) { + uint8_t storage = 0; + using SignedField = Bitfield; + EXPECT_EQ(getField(storage), 0); + EXPECT_EQ(storage, 0b00000000); + // value 0 in ^ + setField(storage, -1); + EXPECT_EQ(getField(storage), -1); + EXPECT_EQ(storage, 0b00000010); + // value 1 in ^ +} + +TEST(BitfieldsTest, TwoBitSigned) { + uint8_t storage = 0; + using SignedField = Bitfield; + EXPECT_EQ(getField(storage), 0); + EXPECT_EQ(storage, 0b00000000); + // value 0 in ^^ + setField(storage, 1); + EXPECT_EQ(getField(storage), 1); + EXPECT_EQ(storage, 0b00000010); + // value 1 in ^^ + setField(storage, -1); + EXPECT_EQ(getField(storage), -1); + EXPECT_EQ(storage, 0b00000110); + // value -1 in ^^ + setField(storage, -2); + EXPECT_EQ(getField(storage), -2); + EXPECT_EQ(storage, 0b00000100); + // value -2 in ^^ +} + +TEST(BitfieldsTest, isOverlapping) { + // 01234567 + // A: -------- + // B: --- + // C: --- + // D: --- + using A = Bitfield; + using B = Bitfield; + using C = Bitfield; + using D = Bitfield; + EXPECT_TRUE((isOverlapping())); + EXPECT_TRUE((isOverlapping())); + EXPECT_TRUE((isOverlapping())); + EXPECT_TRUE((isOverlapping())); + + EXPECT_TRUE((isOverlapping())); + EXPECT_TRUE((isOverlapping())); + EXPECT_FALSE((isOverlapping())); +} + +TEST(BitfieldsTest, FullUint64) { + uint64_t storage = 0; + using Value = Bitfield; + setField(storage, -1ULL); + EXPECT_EQ(getField(storage), -1ULL); + setField(storage, 0ULL); + EXPECT_EQ(getField(storage), 0ULL); +} + +TEST(BitfieldsTest, FullInt64) { + uint64_t storage = 0; + using Value = Bitfield; + setField(storage, -1); + EXPECT_EQ(getField(storage), -1); + setField(storage, 0); + EXPECT_EQ(getField(storage), 0); +} + +#ifdef EXPECT_DEBUG_DEATH + +TEST(BitfieldsTest, ValueTooBigBool) { + uint64_t storage = 0; + using A = Bitfield; + setField(storage, true); + setField(storage, false); + EXPECT_DEBUG_DEATH(setField(storage, 2), "value is too big"); +} + +TEST(BitfieldsTest, ValueTooBigInt) { + uint64_t storage = 0; + using A = Bitfield; + setField(storage, 3); + EXPECT_DEBUG_DEATH(setField(storage, 4), "value is too big"); + EXPECT_DEBUG_DEATH(setField(storage, -1), "value is too big"); +} + +TEST(BitfieldsTest, ValueTooBigBounded) { + uint8_t storage = 0; + using A = Bitfield; + setField(storage, 1); + setField(storage, 0); + setField(storage, -1); + setField(storage, -2); + EXPECT_DEBUG_DEATH(setField(storage, 2), "value is too big"); + EXPECT_DEBUG_DEATH(setField(storage, -3), "value is too small"); +} + +#endif + +} // namespace \ No newline at end of file diff --git a/llvm/unittests/ADT/CMakeLists.txt b/llvm/unittests/ADT/CMakeLists.txt --- a/llvm/unittests/ADT/CMakeLists.txt +++ b/llvm/unittests/ADT/CMakeLists.txt @@ -8,6 +8,7 @@ APIntTest.cpp APSIntTest.cpp ArrayRefTest.cpp + BitFieldsTest.cpp BitmaskEnumTest.cpp BitVectorTest.cpp BreadthFirstIteratorTest.cpp