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,273 @@ +//===-- 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; +/// bitfield(Storage) = true; +/// EXPECT_EQ(Storage, 0b00000001); +/// // ^ +/// EXPECT_EQ(bitfield(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; +/// bitfield(Storage) = SuitEnum::HEARTS; +/// EXPECT_EQ(Storage, 0b00000101); +/// // ^^ +/// EXPECT_EQ(bitfield(Storage), SuitEnum::HEARTS); +/// +/// // Store and retrieve a 5 bit value as unsigned. +/// using Value = Bitfield; +/// bitfield(Storage) = 10; +/// EXPECT_EQ(Storage, 0b01010101); +/// // ^^^^^ +/// EXPECT_EQ(bitfield(Storage), 10U); +/// +/// // Interpret the same 5 bit value as signed. +/// using SignedValue = Bitfield; +/// bitfield(Storage) = -2; +/// EXPECT_EQ(Storage, 0b11110101); +/// // ^^^^^ +/// EXPECT_EQ(bitfield(Storage), -2); +/// +/// // Ability to efficiently test if a field is non zero. +/// EXPECT_TRUE(bitfield(Storage).isSet()); +/// +/// // Alter Storage changes value. +/// Storage = 0; +/// EXPECT_EQ(bitfield(Storage), false); +/// EXPECT_EQ(bitfield(Storage), SuitEnum::CLUBS); +/// EXPECT_EQ(bitfield(Storage), 0U); +/// EXPECT_EQ(bitfield(Storage), 0); +/// +/// Storage = 255; +/// EXPECT_EQ(bitfield(Storage), true); +/// EXPECT_EQ(bitfield(Storage), SuitEnum::SPADES); +/// EXPECT_EQ(bitfield(Storage), 31U); +/// EXPECT_EQ(bitfield(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 because of + // undefined operations over signed types (e.g. Bitwise shift operators). + // Moreover same size casting from unsigned to signed is well defined but not + // the other way around. + using Unsigned = typename std::make_unsigned::type; + static_assert(sizeof(Unsigned) == sizeof(T), "Types must have same size"); + + static constexpr unsigned TypeBits = sizeof(Unsigned) * CHAR_BIT; + static_assert(TypeBits >= Bits, "n-bit must fit in T"); + + // e.g. with TypeBits == 8 and Bits == 6. + static constexpr Unsigned AllZeros = Unsigned(0); // 00000000 + static constexpr Unsigned AllOnes = ~Unsigned(0); // 11111111 + static constexpr Unsigned Umin = AllZeros; // 00000000 + static constexpr Unsigned Umax = AllOnes >> (TypeBits - Bits); // 00111111 + static constexpr Unsigned SignBitMask = Unsigned(1) << (Bits - 1); // 00100000 + static constexpr Unsigned Smax = Umax >> 1U; // 00011111 + static constexpr Unsigned Smin = ~Smax; // 11100000 + static constexpr Unsigned SignExtend = Smin << 1U; // 11000000 +}; + +/// `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 `UserValue` is valid. +template ::value> +struct Compressor { + static_assert(std::is_unsigned::value, "T is unsigned"); + using BP = BitPatterns; + + static T pack(T UserValue, T UserMaxValue) { + assert(UserValue <= UserMaxValue && "value is too big"); + assert(UserValue <= BP::Umax && "value is too big"); + return UserValue; + } + + static T unpack(T StorageValue) { return StorageValue; } +}; + +template struct Compressor { + static_assert(std::is_signed::value, "T is signed"); + using BP = BitPatterns; + + static T pack(T UserValue, T UserMaxValue) { + assert(UserValue <= UserMaxValue && "value is too big"); + assert(UserValue <= T(BP::Smax) && "value is too big"); + assert(UserValue >= T(BP::Smin) && "value is too small"); + if (UserValue < 0) + UserValue &= ~BP::SignExtend; + return UserValue; + } + + static T unpack(T StorageValue) { + if (StorageValue >= T(BP::SignBitMask)) + StorageValue |= BP::SignExtend; + return StorageValue; + } +}; + +/// `BitfieldProperties` stores important properties about the Bitfield. +/// It only deals with proper integer types. The conversion from/to enum/bool +/// are done in the public API outside of this template. +template ::max(), + T MinValue = std::numeric_limits::min()> +struct BitfieldProperties { + using IntegerType = T; + static_assert(std::is_integral::value && + std::numeric_limits::is_integer, + "T must be an integer type"); + + static constexpr size_t TypeBits = sizeof(IntegerType) * CHAR_BIT; + static constexpr unsigned FirstBit = Offset; + static constexpr unsigned LastBit = Offset + Bits; + + static_assert(Bits > 0, "Bits must be non zero"); + static_assert(Bits <= TypeBits, "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 { + private: + static_assert(std::is_unsigned::value, + "Storage must be unsigned"); + using C = Compressor; + using BP = BitPatterns; + + static constexpr size_t StorageBits = sizeof(StorageType) * CHAR_BIT; + static_assert(FirstBit <= StorageBits, "Data must fit in mask"); + static_assert(LastBit <= StorageBits, "Data must fit in mask"); + static constexpr StorageType Mask = BP::Umax << Offset; + + /// Checks `UserValue` is within bounds and packs it between `FirstBit` + /// and `LastBit` of `Packed` leaving the rest unchanged. + static void update(StorageType &Packed, IntegerType UserValue) { + const StorageType StorageValue = C::pack(UserValue, MaxValue); + Packed &= ~Mask; + Packed |= StorageValue << Offset; + } + + /// Interprets bits between `FirstBit` and `LastBit` of `Packed` as an + /// `IntegerType`. + static IntegerType extract(StorageType Packed) { + const StorageType StorageValue = (Packed & Mask) >> Offset; + return C::unpack(StorageValue); + } + + StorageType *StoragePtr = nullptr; + + public: + Impl(StorageType &StorageValue) : StoragePtr(&StorageValue) {} + + Impl(const Impl &) = delete; + Impl(Impl &&) = default; // needed to return the value + Impl &operator=(const Impl &) = delete; + Impl &operator=(Impl &&) = delete; + + StorageType isSet() const { return *StoragePtr & Mask; } + + operator UserType() const { + return static_cast(extract(*StoragePtr)); + } + + Impl &operator=(UserType UserValue) { + update(*StoragePtr, static_cast(UserValue)); + return *this; + } + }; +}; + +/// `Bitfield` deals with the following type: +/// - unsigned enums +/// - signed and unsigned integer +/// - `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 ResolveUnderlyingType { + using type = typename std::underlying_type::type; +}; +template struct ResolveUnderlyingType { + using type = T; +}; +template <> struct ResolveUnderlyingType { + /// 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 T, 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 + ? T(0) // coupled with static_assert below + : std::numeric_limits::max()> +struct Bitfield { + using Type = T; + using IntegerType = typename details::ResolveUnderlyingType::type; + using Properties = + typename details::BitfieldProperties(MaxValue)>; + + static_assert(!std::is_enum::value || MaxValue != T(0), + "Enum Bitfields must provide a MaxValue"); + static_assert(!std::is_enum::value || std::is_unsigned::value, + "Enum must be unsigned"); +}; + +template +auto bitfield(StorageType &StorageValue) { + using Impl = typename Bitfield::Properties::template Impl; + return Impl(StorageValue); +} + +/// 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::LastBit > PB::FirstBit && PB::LastBit > PA::FirstBit; +} + +} // namespace llvm + +#endif // LLVM_ADT_BITFIELDS_H 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; + bitfield(Storage) = true; + EXPECT_EQ(Storage, 0b00000001); + // ^ + EXPECT_EQ(bitfield(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; + bitfield(Storage) = SuitEnum::HEARTS; + EXPECT_EQ(Storage, 0b00000101); + // ^^ + EXPECT_EQ(bitfield(Storage), SuitEnum::HEARTS); + + // Store and retrieve a 5 bit value as unsigned. + using Value = Bitfield; + bitfield(Storage) = 10; + EXPECT_EQ(Storage, 0b01010101); + // ^^^^^ + EXPECT_EQ(bitfield(Storage), 10U); + + // Interpret the same 5 bit value as signed. + using SignedValue = Bitfield; + bitfield(Storage) = -2; + EXPECT_EQ(Storage, 0b11110101); + // ^^^^^ + EXPECT_EQ(bitfield(Storage), -2); + + // Ability to efficiently test if a field is non zero. + EXPECT_TRUE(bitfield(Storage).isSet()); + + // Alter Storage changes value. + Storage = 0; + EXPECT_EQ(bitfield(Storage), false); + EXPECT_EQ(bitfield(Storage), SuitEnum::CLUBS); + EXPECT_EQ(bitfield(Storage), 0U); + EXPECT_EQ(bitfield(Storage), 0); + + Storage = 255; + EXPECT_EQ(bitfield(Storage), true); + EXPECT_EQ(bitfield(Storage), SuitEnum::SPADES); + EXPECT_EQ(bitfield(Storage), 31U); + EXPECT_EQ(bitfield(Storage), -1); +} + +TEST(BitfieldsTest, FirstBit) { + uint8_t Storage = 0; + using FirstBit = Bitfield; + // Set true + bitfield(Storage) = true; + EXPECT_EQ(bitfield(Storage), true); + EXPECT_EQ(Storage, 0x1ULL); + // Set false + bitfield(Storage) = false; + EXPECT_EQ(bitfield(Storage), false); + EXPECT_EQ(Storage, 0x0ULL); +} + +TEST(BitfieldsTest, SecondBit) { + uint8_t Storage = 0; + using SecondBit = Bitfield; + // Set true + bitfield(Storage) = true; + EXPECT_EQ(bitfield(Storage), true); + EXPECT_EQ(Storage, 0x2ULL); + // Set false + bitfield(Storage) = false; + EXPECT_EQ(bitfield(Storage), false); + EXPECT_EQ(Storage, 0x0ULL); +} + +TEST(BitfieldsTest, LastBit) { + uint8_t Storage = 0; + using LastBit = Bitfield; + // Set true + bitfield(Storage) = true; + EXPECT_EQ(bitfield(Storage), true); + EXPECT_EQ(Storage, 0x80ULL); + // Set false + bitfield(Storage) = false; + EXPECT_EQ(bitfield(Storage), false); + EXPECT_EQ(Storage, 0x0ULL); +} + +TEST(BitfieldsTest, LastBitUint64) { + uint64_t Storage = 0; + using LastBit = Bitfield; + // Set true + bitfield(Storage) = true; + EXPECT_EQ(bitfield(Storage), true); + EXPECT_EQ(Storage, 0x8000000000000000ULL); + // Set false + bitfield(Storage) = false; + EXPECT_EQ(bitfield(Storage), false); + EXPECT_EQ(Storage, 0x0ULL); +} + +TEST(BitfieldsTest, Enum) { + enum Enum : unsigned { Zero = 0, Two = 2, LAST = Two }; + + uint8_t Storage = 0; + using OrderingField = Bitfield; + EXPECT_EQ(bitfield(Storage), Zero); + bitfield(Storage) = Two; + EXPECT_EQ(bitfield(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(bitfield(Storage), Enum::Zero); + bitfield(Storage) = Enum::Two; + EXPECT_EQ(bitfield(Storage), Enum::Two); + EXPECT_EQ(Storage, 0b00000100); + // value 2 in ^^ +} + +TEST(BitfieldsTest, OneBitSigned) { + uint8_t Storage = 0; + using SignedField = Bitfield; + EXPECT_EQ(bitfield(Storage), 0); + EXPECT_EQ(Storage, 0b00000000); + // value 0 in ^ + bitfield(Storage) = -1; + EXPECT_EQ(bitfield(Storage), -1); + EXPECT_EQ(Storage, 0b00000010); + // value 1 in ^ +} + +TEST(BitfieldsTest, TwoBitSigned) { + uint8_t Storage = 0; + using SignedField = Bitfield; + EXPECT_EQ(bitfield(Storage), 0); + EXPECT_EQ(Storage, 0b00000000); + // value 0 in ^^ + bitfield(Storage) = 1; + EXPECT_EQ(bitfield(Storage), 1); + EXPECT_EQ(Storage, 0b00000010); + // value 1 in ^^ + bitfield(Storage) = -1; + EXPECT_EQ(bitfield(Storage), -1); + EXPECT_EQ(Storage, 0b00000110); + // value -1 in ^^ + bitfield(Storage) = -2; + EXPECT_EQ(bitfield(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; + bitfield(Storage) = -1ULL; + EXPECT_EQ(bitfield(Storage), -1ULL); + bitfield(Storage) = 0ULL; + EXPECT_EQ(bitfield(Storage), 0ULL); +} + +TEST(BitfieldsTest, FullInt64) { + uint64_t Storage = 0; + using Value = Bitfield; + bitfield(Storage) = -1; + EXPECT_EQ(bitfield(Storage), -1); + bitfield(Storage) = 0; + EXPECT_EQ(bitfield(Storage), 0); +} + +#ifdef EXPECT_DEBUG_DEATH + +TEST(BitfieldsTest, ValueTooBigBool) { + uint64_t Storage = 0; + using A = Bitfield; + bitfield(Storage) = true; + bitfield(Storage) = false; + EXPECT_DEBUG_DEATH(bitfield(Storage) = 2, "value is too big"); +} + +TEST(BitfieldsTest, ValueTooBigInt) { + uint64_t Storage = 0; + using A = Bitfield; + bitfield(Storage) = 3; + EXPECT_DEBUG_DEATH(bitfield(Storage) = 4, "value is too big"); + EXPECT_DEBUG_DEATH(bitfield(Storage) = -1, "value is too big"); +} + +TEST(BitfieldsTest, ValueTooBigBounded) { + uint8_t Storage = 0; + using A = Bitfield; + bitfield(Storage) = 1; + bitfield(Storage) = 0; + bitfield(Storage) = -1; + bitfield(Storage) = -2; + EXPECT_DEBUG_DEATH(bitfield(Storage) = 2, "value is too big"); + EXPECT_DEBUG_DEATH(bitfield(Storage) = -3, "value is too small"); +} + +#endif + +} // namespace 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