diff --git a/.bazelrc b/.bazelrc index 3e964e4..c64b255 100644 --- a/.bazelrc +++ b/.bazelrc
@@ -86,7 +86,6 @@ # Remote build configuration for CI. build:remote-cache --remote_cache=https://storage.googleapis.com/absl-bazel-remote-cache -build:remote-cache --remote_timeout=1200 --bes_timeout=600s build:remote-cache --remote_download_minimal # cc_test puts Windows .pdb files in the pdb_file output group rather than # runfiles, so explicitly download symbolize_test.pdb when linking hits the @@ -100,7 +99,7 @@ test:remote-cache --build_tests_only build:remote-base --define=EXECUTOR=remote -build:remote-base --remote_timeout=1200 --bes_timeout=600s +build:remote-base --remote_grpc_service_config=ci/rbe_grpc_service_config.json build:remote-base --jobs=50 build:remote-base --remote_download_minimal # Retry up for up to 15 minutes under heavy load (exponential backoff).
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 95f19fd..59dea1e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml
@@ -17,8 +17,8 @@ on: # continuous runs schedule: - # Run every hour - - cron: "0 * * * *" + # Run every hour (staggered to avoid top-of-the-hour runner queue spikes) + - cron: "30 * * * *" # postsubmit runs push:
diff --git a/CMake/AbseilDll.cmake b/CMake/AbseilDll.cmake index 5b24d67..253898d 100644 --- a/CMake/AbseilDll.cmake +++ b/CMake/AbseilDll.cmake
@@ -158,6 +158,7 @@ "functional/internal/function_ref.h" "functional/overload.h" "hash/hash.h" + "hash/internal/canonical_hash.h" "hash/internal/city.cc" "hash/internal/city.h" "hash/internal/hash.cc" @@ -513,6 +514,7 @@ "random/internal/distribution_test_util.h" "random/internal/mock_helpers.h" "random/internal/mock_overload_set.h" + "random/internal/mock_validators.h" "random/mocking_bit_gen.h" "random/mock_distributions.h" "status/status_matchers.h"
diff --git a/absl/algorithm/container.h b/absl/algorithm/container.h index 1db7da7..123eb06 100644 --- a/absl/algorithm/container.h +++ b/absl/algorithm/container.h
@@ -52,6 +52,7 @@ #include <vector> #include "absl/algorithm/algorithm.h" +#include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/hardening.h" #include "absl/base/internal/iterator_traits.h" @@ -746,7 +747,9 @@ auto last2 = container_algorithm_internal::c_end(c2); using std::swap; - for (; first1 != last1 && first2 != last2; ++first1, (void)++first2) { + // SAFETY: Legacy buffer usage. + for (; first1 != last1 && first2 != last2; + ABSL_UNSAFE_BUFFERS(++first1), (void)ABSL_UNSAFE_BUFFERS(++first2)) { swap(*first1, *first2); } return first2; @@ -802,7 +805,10 @@ auto first2 = container_algorithm_internal::c_begin(input2); auto last2 = container_algorithm_internal::c_end(input2); std::decay_t<OutputIterator> out = std::forward<OutputIterator>(output); - for (; first1 != last1 && first2 != last2; ++first1, (void)++first2, ++out) { + // SAFETY: Legacy buffer usage. + for (; first1 != last1 && first2 != last2; + ABSL_UNSAFE_BUFFERS(++first1), (void)ABSL_UNSAFE_BUFFERS(++first2), + ABSL_UNSAFE_BUFFERS(++out)) { *out = binary_op(*first1, *first2); } return out;
diff --git a/absl/algorithm/container_test.cc b/absl/algorithm/container_test.cc index dda791b..92e38ea 100644 --- a/absl/algorithm/container_test.cc +++ b/absl/algorithm/container_test.cc
@@ -419,7 +419,7 @@ std::sort(v.begin(), v.end(), std::greater<int>()); int* i = absl::c_upper_bound(absl::MakeSpan(v), 1, std::greater<int>()); EXPECT_EQ(3, i - v.data()); - EXPECT_TRUE(i == v.data() + v.size()); + EXPECT_TRUE(i == std::next(v.data(), v.size())); } TEST_F(NonMutatingTest, EqualRange) { @@ -480,7 +480,7 @@ TEST_F(NonMutatingTest, MinElementTemporarySpan) { int* i = absl::c_min_element(absl::MakeSpan(vector_)); - ASSERT_TRUE(i != vector_.data() + vector_.size()); + ASSERT_TRUE(i != std::next(vector_.data(), vector_.size())); EXPECT_EQ(*i, 1); } @@ -493,7 +493,7 @@ TEST_F(NonMutatingTest, MinElementTemporarySpanWithPredicate) { int* i = absl::c_min_element(absl::MakeSpan(vector_), std::greater<int>()); - ASSERT_TRUE(i != vector_.data() + vector_.size()); + ASSERT_TRUE(i != std::next(vector_.data(), vector_.size())); EXPECT_EQ(*i, 3); } @@ -505,7 +505,7 @@ TEST_F(NonMutatingTest, MaxElementTemporarySpan) { int* i = absl::c_max_element(absl::MakeSpan(vector_)); - ASSERT_TRUE(i != vector_.data() + vector_.size()); + ASSERT_TRUE(i != std::next(vector_.data(), vector_.size())); EXPECT_EQ(*i, 3); } @@ -518,7 +518,7 @@ TEST_F(NonMutatingTest, MaxElementTemporarySpanWithPredicate) { int* i = absl::c_max_element(absl::MakeSpan(vector_), std::greater<int>()); - ASSERT_TRUE(i != vector_.data() + vector_.size()); + ASSERT_TRUE(i != std::next(vector_.data(), vector_.size())); EXPECT_EQ(*i, 1); } @@ -923,7 +923,6 @@ EXPECT_THAT(actual, ElementsAre(1, 2, 0, 0, 0)); } - bool IsHardened() { bool hardened = false; ABSL_HARDENING_ASSERT([&hardened]() { @@ -1167,7 +1166,6 @@ EXPECT_EQ(*actual[0], 1); } - TEST(MutatingTest, MoveToCArrayInvalidSize) { std::vector<int> input = {1, 2, 3}; int actual[2] = {0, 0}; @@ -1602,9 +1600,9 @@ TEST(MutatingTest, PartialSortTemporarySpan) { std::vector<int> sequence{5, 3, 42, 0}; - absl::c_partial_sort(absl::MakeSpan(sequence), sequence.data() + 2); + absl::c_partial_sort(absl::MakeSpan(sequence), std::next(sequence.data(), 2)); EXPECT_THAT(absl::MakeSpan(sequence).first(2), ElementsAre(0, 3)); - absl::c_partial_sort(absl::MakeSpan(sequence), sequence.data() + 2, + absl::c_partial_sort(absl::MakeSpan(sequence), std::next(sequence.data(), 2), std::greater<int>()); EXPECT_THAT(absl::MakeSpan(sequence).first(2), ElementsAre(42, 5)); } @@ -1869,7 +1867,7 @@ TEST(ConstexprTest, FindIf) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(absl::c_find_if(kArray, [](int x) { return x > 2; }) == - kArray.begin() + 2); + std::next(kArray.begin(), 2)); static_assert(absl::c_find_if(kArray, [](int x) { return x > 5; }) == kArray.end()); } @@ -1885,7 +1883,8 @@ TEST(ConstexprTest, FindEnd) { static constexpr std::array<int, 5> kHaystack = {1, 2, 3, 2, 3}; static constexpr std::array<int, 2> kNeedle = {2, 3}; - static_assert(absl::c_find_end(kHaystack, kNeedle) == kHaystack.begin() + 3); + static_assert(absl::c_find_end(kHaystack, kNeedle) == + std::next(kHaystack.begin(), 3)); } TEST(ConstexprTest, FindFirstOf) { @@ -1895,7 +1894,7 @@ TEST(ConstexprTest, AdjacentFind) { static constexpr std::array<int, 4> kArray = {1, 2, 2, 3}; - static_assert(absl::c_adjacent_find(kArray) == kArray.begin() + 1); + static_assert(absl::c_adjacent_find(kArray) == std::next(kArray.begin(), 1)); } TEST(ConstexprTest, AdjacentFindWithPredicate) { @@ -2010,14 +2009,14 @@ TEST(ConstexprTest, SearchN) { static constexpr std::array<int, 4> kArray = {1, 2, 2, 3}; static_assert(absl::c_search_n(kArray, 1, 1) == kArray.begin()); - static_assert(absl::c_search_n(kArray, 2, 2) == kArray.begin() + 1); + static_assert(absl::c_search_n(kArray, 2, 2) == std::next(kArray.begin(), 1)); static_assert(absl::c_search_n(kArray, 1, 4) == kArray.end()); } TEST(ConstexprTest, SearchNWithPredicate) { static constexpr std::array<int, 4> kArray = {1, 2, 2, 3}; static_assert(absl::c_search_n(kArray, 1, 1, std::not_equal_to<int>()) == - kArray.begin() + 1); + std::next(kArray.begin(), 1)); static_assert(absl::c_search_n(kArray, 2, 2, std::not_equal_to<int>()) == kArray.end()); static_assert(absl::c_search_n(kArray, 1, 4, std::not_equal_to<int>()) == @@ -2250,7 +2249,7 @@ static constexpr std::array kArray = {1, 2, 3}; static constexpr auto kArrayRotate = [] { std::array array = kArray; - absl::c_rotate(array, array.begin() + 1); + absl::c_rotate(array, std::next(array.begin(), 1)); return array; }(); static_assert(kArrayRotate == std::array{2, 3, 1}); @@ -2260,7 +2259,7 @@ static constexpr std::array kArray = {1, 2, 3}; static constexpr auto kArrayRotateCopy = [] { std::array<int, 3> array; - absl::c_rotate_copy(kArray, kArray.begin() + 1, array.begin()); + absl::c_rotate_copy(kArray, std::next(kArray.begin(), 1), array.begin()); return array; }(); static_assert(kArrayRotateCopy == std::array{2, 3, 1}); @@ -2344,7 +2343,7 @@ static constexpr std::array kArray = {3, 1, 4, 2}; static constexpr auto kArrayPartialSort = [] { std::array array = kArray; - absl::c_partial_sort(array, array.begin() + 2); + absl::c_partial_sort(array, std::next(array.begin(), 2)); return array; }(); static_assert(kArrayPartialSort[0] == 1); @@ -2355,7 +2354,7 @@ static constexpr std::array kArray = {3, 1, 4, 2}; static constexpr auto kArrayPartialSort = [] { std::array array = kArray; - absl::c_partial_sort(array, array.begin() + 2, std::greater<>()); + absl::c_partial_sort(array, std::next(array.begin(), 2), std::greater<>()); return array; }(); static_assert(kArrayPartialSort[0] == 4); @@ -2389,7 +2388,7 @@ static_assert(absl::c_is_sorted_until(kSortedArray) == kSortedArray.end()); static constexpr std::array kUnsortedArray = {1, 3, 2}; static_assert(absl::c_is_sorted_until(kUnsortedArray) == - kUnsortedArray.begin() + 2); + std::next(kUnsortedArray.begin(), 2)); } TEST(ConstexprTest, IsSortedUntilWithPredicate) { @@ -2398,14 +2397,14 @@ kSortedArray.end()); static constexpr std::array kUnsortedArray = {1, 3, 2}; static_assert(absl::c_is_sorted_until(kUnsortedArray, std::greater<>()) == - kUnsortedArray.begin() + 1); + std::next(kUnsortedArray.begin(), 1)); } TEST(ConstexprTest, NthElement) { static constexpr std::array kArray = {2, 1, 3, 4}; static constexpr auto kArrayNthElement = [] { std::array array = kArray; - absl::c_nth_element(array, array.begin() + 2); + absl::c_nth_element(array, std::next(array.begin(), 2)); return array; }(); static_assert(kArrayNthElement[2] == 3); @@ -2418,7 +2417,7 @@ static constexpr std::array kArray = {1, 2, 3, 4}; static constexpr auto kArrayNthElement = [] { std::array array = kArray; - absl::c_nth_element(array, array.begin() + 2, std::greater<>()); + absl::c_nth_element(array, std::next(array.begin(), 2), std::greater<>()); return array; }(); static_assert(kArrayNthElement[2] == 2); @@ -2433,42 +2432,42 @@ TEST(ConstexprTest, LowerBound) { static constexpr std::array kArray = {1, 2, 3, 4}; static constexpr auto kLowerBound = absl::c_lower_bound(kArray, 2); - static_assert(kLowerBound == kArray.begin() + 1); + static_assert(kLowerBound == std::next(kArray.begin(), 1)); } TEST(ConstexprTest, LowerBoundWithPredicate) { static constexpr std::array kArray = {4, 3, 2, 1}; static constexpr auto kLowerBound = absl::c_lower_bound(kArray, 2, std::greater<>()); - static_assert(kLowerBound == kArray.begin() + 2); + static_assert(kLowerBound == std::next(kArray.begin(), 2)); } TEST(ConstexprTest, UpperBound) { static constexpr std::array kArray = {1, 2, 3, 4}; static constexpr auto kUpperBound = absl::c_upper_bound(kArray, 2); - static_assert(kUpperBound == kArray.begin() + 2); + static_assert(kUpperBound == std::next(kArray.begin(), 2)); } TEST(ConstexprTest, UpperBoundWithPredicate) { static constexpr std::array kArray = {4, 3, 2, 1}; static constexpr auto kUpperBound = absl::c_upper_bound(kArray, 2, std::greater<>()); - static_assert(kUpperBound == kArray.begin() + 3); + static_assert(kUpperBound == std::next(kArray.begin(), 3)); } TEST(ConstexprTest, EqualRange) { static constexpr std::array kArray = {1, 2, 3, 4}; static constexpr auto kEqualRange = absl::c_equal_range(kArray, 2); - static_assert(kEqualRange.first == kArray.begin() + 1); - static_assert(kEqualRange.second == kArray.begin() + 2); + static_assert(kEqualRange.first == std::next(kArray.begin(), 1)); + static_assert(kEqualRange.second == std::next(kArray.begin(), 2)); } TEST(ConstexprTest, EqualRangeWithPredicate) { static constexpr std::array kArray = {4, 3, 2, 1}; static constexpr auto kEqualRange = absl::c_equal_range(kArray, 2, std::greater<>()); - static_assert(kEqualRange.first == kArray.begin() + 2); - static_assert(kEqualRange.second == kArray.begin() + 3); + static_assert(kEqualRange.first == std::next(kArray.begin(), 2)); + static_assert(kEqualRange.second == std::next(kArray.begin(), 3)); } TEST(ConstexprTest, BinarySearch) { @@ -2702,7 +2701,8 @@ static constexpr std::array kHeap = {4, 2, 3, 1}; static_assert(absl::c_is_heap_until(kHeap) == kHeap.end()); static constexpr std::array kNotHeap = {4, 2, 3, 5}; - static_assert(absl::c_is_heap_until(kNotHeap) == kNotHeap.begin() + 3); + static_assert(absl::c_is_heap_until(kNotHeap) == + std::next(kNotHeap.begin(), 3)); } TEST(ConstexprTest, IsHeapUntilWithPredicate) { @@ -2710,7 +2710,7 @@ static_assert(absl::c_is_heap_until(kHeap, std::greater<>()) == kHeap.end()); static constexpr std::array kNotHeap = {1, 2, 3, 0}; static_assert(absl::c_is_heap_until(kNotHeap, std::greater<>()) == - kNotHeap.begin() + 3); + std::next(kNotHeap.begin(), 3)); } TEST(ConstexprTest, LexicographicalCompare) {
diff --git a/absl/base/attributes.h b/absl/base/attributes.h index 6888f8d..32af1dd 100644 --- a/absl/base/attributes.h +++ b/absl/base/attributes.h
@@ -90,7 +90,7 @@ [[gnu::format(printf, string_index, first_to_check)]] #define ABSL_SCANF_ATTRIBUTE(string_index, first_to_check) \ [[gnu::format(scanf, string_index, first_to_check)]] -#elif ABSL_HAVE_ATTRIBUTE(format) || (defined(__GNUC__) && !defined(__clang__)) +#elif ABSL_HAVE_ATTRIBUTE(format) #define ABSL_PRINTF_ATTRIBUTE(string_index, first_to_check) \ __attribute__((__format__(__printf__, string_index, first_to_check))) #define ABSL_SCANF_ATTRIBUTE(string_index, first_to_check) \ @@ -108,8 +108,7 @@ // Note that guarantees are ultimately toolchain-dependent. For example, MSVC // will not inline any function by default, meaning at least /Ob1 or a higher // levels of optimization is necessary. -#if ABSL_HAVE_ATTRIBUTE(always_inline) || \ - (defined(__GNUC__) && !defined(__clang__)) +#if ABSL_HAVE_ATTRIBUTE(always_inline) #define ABSL_ATTRIBUTE_ALWAYS_INLINE __attribute__((always_inline)) #define ABSL_HAVE_ATTRIBUTE_ALWAYS_INLINE 1 #elif defined(_MSC_VER) && \ @@ -121,7 +120,7 @@ #define ABSL_ATTRIBUTE_ALWAYS_INLINE #endif -#if ABSL_HAVE_ATTRIBUTE(noinline) || (defined(__GNUC__) && !defined(__clang__)) +#if ABSL_HAVE_ATTRIBUTE(noinline) #define ABSL_ATTRIBUTE_NOINLINE __attribute__((noinline)) #define ABSL_HAVE_ATTRIBUTE_NOINLINE 1 #elif defined(_MSC_VER) && \ @@ -149,6 +148,61 @@ #define ABSL_HAVE_ATTRIBUTE_NO_TAIL_CALL 0 #endif +// ABSL_INTERNAL_MUSTTAIL +// +// Tells the compiler that a `return` statement must be compiled as a tail +// call, reusing the caller's stack frame rather than creating a new one. +// Compilation fails if the compiler cannot generate a tail call. +// +// MANDATORY USAGE REQUIREMENTS: +// * Functionally correct fallback: Code MUST be written with a functionally +// correct fallback when the attribute is unavailable +// (`!ABSL_INTERNAL_HAVE_MUSTTAIL`, where `ABSL_INTERNAL_MUSTTAIL` expands to +// nothing). Never rely on `ABSL_INTERNAL_MUSTTAIL` for program correctness +// (such as preventing unbounded stack growth in recursive cycles) unless +// explicitly gated on `#if ABSL_INTERNAL_HAVE_MUSTTAIL` with a non-recursive +// fallback. +// * Benchmark justification: The performance or code-size impact of using +// `ABSL_INTERNAL_MUSTTAIL` MUST be clearly demonstrated by benchmarks. +// * This macro is strictly for internal Abseil use and must not be exposed as a +// public Abseil API. +// +// Technical requirements and limitations: +// * Must be placed immediately before `return`, and the returned expression +// must be a function call (not wrapped in another expression or conversion). +// * The caller and callee must have compatible function signatures, including +// matching return types, parameter types, calling conventions, and implicit +// `this` arguments (a non-static member function can only tail-call another +// non-static member function of the same class). +// * No variables, temporaries, or by-value parameters with non-trivial +// destructors may be live at the `return` statement. +// * Arguments to the tail call must not reference local variables or by-value +// parameters in the caller's stack frame, whose lifetime ends before the +// callee runs. +// * If the caller is inlined into an outer function where the call is no +// longer in tail position, the compiler drops `musttail`. It is therefore +// only effective on out-of-line / non-inlined functions, not `inline` +// header functions or templates. +// * Only enabled on 64-bit x86 and AArch64, where Clang's backend support for +// `musttail` is reliable. Other targets (such as 32-bit x86/ARM, PowerPC, +// and WebAssembly) have incomplete backend tail-call support or compiler +// crashes even when `__has_cpp_attribute(clang::musttail)` is true (e.g., +// https://github.com/llvm/llvm-project/issues/53271). +// +// See: https://clang.llvm.org/docs/AttributeReference.html#musttail +#ifdef ABSL_INTERNAL_HAVE_MUSTTAIL +#error "ABSL_INTERNAL_HAVE_MUSTTAIL cannot be directly set." +#elif defined(ABSL_INTERNAL_MUSTTAIL) +#error "ABSL_INTERNAL_MUSTTAIL cannot be directly set." +#elif ABSL_HAVE_CPP_ATTRIBUTE(clang::musttail) && \ + (defined(__aarch64__) || defined(__x86_64__) || defined(_M_X64)) +#define ABSL_INTERNAL_HAVE_MUSTTAIL 1 +#define ABSL_INTERNAL_MUSTTAIL [[clang::musttail]] +#else +#define ABSL_INTERNAL_HAVE_MUSTTAIL 0 +#define ABSL_INTERNAL_MUSTTAIL +#endif + // ABSL_ATTRIBUTE_WEAK // // Tags a function as weak for the purposes of compilation and linking. @@ -157,8 +211,7 @@ // for further information. Weak attributes do not work across DLL boundary. // The MinGW compiler doesn't complain about the weak attribute until the link // step, presumably because Windows doesn't use ELF binaries. -#if (ABSL_HAVE_ATTRIBUTE(weak) || \ - (defined(__GNUC__) && !defined(__clang__))) && \ +#if ABSL_HAVE_ATTRIBUTE(weak) && \ (!defined(_WIN32) || \ (defined(__clang__) && __clang_major__ >= 9 && \ !defined(ABSL_BUILD_DLL) && !defined(ABSL_CONSUME_DLL))) && \ @@ -209,7 +262,7 @@ // // NOTE: The GCC nonnull attribute actually accepts a list of arguments, but // ABSL_ATTRIBUTE_NONNULL does not. -#if ABSL_HAVE_ATTRIBUTE(nonnull) || (defined(__GNUC__) && !defined(__clang__)) +#if ABSL_HAVE_ATTRIBUTE(nonnull) #define ABSL_ATTRIBUTE_NONNULL(arg_index) __attribute__((nonnull(arg_index))) #else #define ABSL_ATTRIBUTE_NONNULL(...) @@ -236,7 +289,11 @@ // https://gcc.gnu.org/gcc-4.8/changes.html #if defined(ABSL_HAVE_ADDRESS_SANITIZER) && \ ABSL_HAVE_ATTRIBUTE(no_sanitize_address) +#if ABSL_HAVE_CPP_ATTRIBUTE(gnu::no_sanitize_address) +#define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS [[gnu::no_sanitize_address]] +#else #define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS __attribute__((no_sanitize_address)) +#endif #elif defined(ABSL_HAVE_ADDRESS_SANITIZER) && defined(_MSC_VER) && \ _MSC_VER >= 1928 // https://docs.microsoft.com/en-us/cpp/cpp/no-sanitize-address @@ -246,8 +303,12 @@ // features to detect similar bugs with less CPU and memory overhead. // NOTE: GCC supports HWAddressSanitizer(hwasan) since 11. // https://gcc.gnu.org/gcc-11/changes.html +#if ABSL_HAVE_CPP_ATTRIBUTE(gnu::no_sanitize) +#define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS [[gnu::no_sanitize("hwaddress")]] +#else #define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS \ __attribute__((no_sanitize("hwaddress"))) +#endif #else #define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS #endif @@ -260,7 +321,9 @@ // attribute is similar to the ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS attribute // above, but deals with initialized-ness rather than addressability issues. // NOTE: MemorySanitizer(msan) is supported by Clang but not GCC. -#if ABSL_HAVE_ATTRIBUTE(no_sanitize_memory) +#if ABSL_HAVE_CPP_ATTRIBUTE(clang::no_sanitize_memory) +#define ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY [[clang::no_sanitize_memory]] +#elif ABSL_HAVE_ATTRIBUTE(no_sanitize_memory) #define ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory)) #else #define ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY @@ -271,7 +334,9 @@ // Tells the ThreadSanitizer to not instrument a given function. // NOTE: GCC supports ThreadSanitizer(tsan) since 4.8. // https://gcc.gnu.org/gcc-4.8/changes.html -#if ABSL_HAVE_ATTRIBUTE(no_sanitize_thread) +#if ABSL_HAVE_CPP_ATTRIBUTE(gnu::no_sanitize_thread) +#define ABSL_ATTRIBUTE_NO_SANITIZE_THREAD [[gnu::no_sanitize_thread]] +#elif ABSL_HAVE_ATTRIBUTE(no_sanitize_thread) #define ABSL_ATTRIBUTE_NO_SANITIZE_THREAD __attribute__((no_sanitize_thread)) #else #define ABSL_ATTRIBUTE_NO_SANITIZE_THREAD @@ -287,8 +352,12 @@ #define ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED \ __attribute__((no_sanitize_undefined)) #elif ABSL_HAVE_ATTRIBUTE(no_sanitize) +#if ABSL_HAVE_CPP_ATTRIBUTE(gnu::no_sanitize) +#define ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED [[gnu::no_sanitize("undefined")]] +#else #define ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED \ __attribute__((no_sanitize("undefined"))) +#endif #else #define ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED #endif @@ -298,9 +367,20 @@ // Tells the ControlFlowIntegrity sanitizer to not instrument a given function. // See https://clang.llvm.org/docs/ControlFlowIntegrity.html for details. #if ABSL_HAVE_CPP_ATTRIBUTE(gnu::no_sanitize) && defined(__llvm__) +#if defined(__clang__) && !defined(__apple_build_version__) && \ + __clang_major__ >= 16 +#define ABSL_ATTRIBUTE_NO_SANITIZE_CFI [[gnu::no_sanitize("cfi", "kcfi")]] +#else #define ABSL_ATTRIBUTE_NO_SANITIZE_CFI [[gnu::no_sanitize("cfi")]] +#endif #elif ABSL_HAVE_ATTRIBUTE(no_sanitize) && defined(__llvm__) +#if defined(__clang__) && !defined(__apple_build_version__) && \ + __clang_major__ >= 16 +#define ABSL_ATTRIBUTE_NO_SANITIZE_CFI \ + __attribute__((no_sanitize("cfi", "kcfi"))) +#else #define ABSL_ATTRIBUTE_NO_SANITIZE_CFI __attribute__((no_sanitize("cfi"))) +#endif #else #define ABSL_ATTRIBUTE_NO_SANITIZE_CFI #endif @@ -309,7 +389,9 @@ // // Tells the SafeStack to not instrument a given function. // See https://clang.llvm.org/docs/SafeStack.html for details. -#if ABSL_HAVE_ATTRIBUTE(no_sanitize) +#if ABSL_HAVE_CPP_ATTRIBUTE(gnu::no_sanitize) +#define ABSL_ATTRIBUTE_NO_SANITIZE_SAFESTACK [[gnu::no_sanitize("safe-stack")]] +#elif ABSL_HAVE_ATTRIBUTE(no_sanitize) #define ABSL_ATTRIBUTE_NO_SANITIZE_SAFESTACK \ __attribute__((no_sanitize("safe-stack"))) #else @@ -333,9 +415,8 @@ // a prerequisite. Labeled sections are not supported on Darwin/iOS. #ifdef ABSL_HAVE_ATTRIBUTE_SECTION #error ABSL_HAVE_ATTRIBUTE_SECTION cannot be directly set -#elif (ABSL_HAVE_ATTRIBUTE(section) || \ - (defined(__GNUC__) && !defined(__clang__))) && \ - !defined(__APPLE__) && ABSL_HAVE_ATTRIBUTE_WEAK +#elif ABSL_HAVE_ATTRIBUTE(section) && !defined(__APPLE__) && \ + ABSL_HAVE_ATTRIBUTE_WEAK #define ABSL_HAVE_ATTRIBUTE_SECTION 1 // ABSL_ATTRIBUTE_SECTION @@ -363,6 +444,8 @@ // indicating alignment. If data fall under different alignments then you might // get a compilation error indicating a `Section type conflict`. #define ABSL_ATTRIBUTE_SECTION_VARIABLE(name) +#elif ABSL_HAVE_CPP_ATTRIBUTE(gnu::section) +#define ABSL_ATTRIBUTE_SECTION_VARIABLE(name) [[gnu::section(#name)]] #else #define ABSL_ATTRIBUTE_SECTION_VARIABLE(name) __attribute__((section(#name))) #endif @@ -417,11 +500,14 @@ // ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC // // Support for aligning the stack on 32-bit x86. -#if ABSL_HAVE_ATTRIBUTE(force_align_arg_pointer) || \ - (defined(__GNUC__) && !defined(__clang__)) +#if ABSL_HAVE_ATTRIBUTE(force_align_arg_pointer) #if defined(__i386__) +#if ABSL_HAVE_CPP_ATTRIBUTE(gnu::force_align_arg_pointer) +#define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC [[gnu::force_align_arg_pointer]] +#else #define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC \ __attribute__((force_align_arg_pointer)) +#endif #define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (0) #elif defined(__x86_64__) #define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (1) @@ -478,7 +564,7 @@ // int foo() ABSL_ATTRIBUTE_HOT; #if defined(__cplusplus) && ABSL_HAVE_CPP_ATTRIBUTE(gnu::hot) #define ABSL_ATTRIBUTE_HOT [[gnu::hot]] -#elif ABSL_HAVE_ATTRIBUTE(hot) || (defined(__GNUC__) && !defined(__clang__)) +#elif ABSL_HAVE_ATTRIBUTE(hot) #define ABSL_ATTRIBUTE_HOT __attribute__((hot)) #else #define ABSL_ATTRIBUTE_HOT @@ -486,7 +572,7 @@ #if defined(__cplusplus) && ABSL_HAVE_CPP_ATTRIBUTE(gnu::cold) #define ABSL_ATTRIBUTE_COLD [[gnu::cold]] -#elif ABSL_HAVE_ATTRIBUTE(cold) || (defined(__GNUC__) && !defined(__clang__)) +#elif ABSL_HAVE_ATTRIBUTE(cold) #define ABSL_ATTRIBUTE_COLD __attribute__((cold)) #else #define ABSL_ATTRIBUTE_COLD @@ -616,7 +702,9 @@ // // Tells the compiler to use "initial-exec" mode for a thread-local variable. // See http://people.redhat.com/drepper/tls.pdf for the gory details. -#if ABSL_HAVE_ATTRIBUTE(tls_model) || (defined(__GNUC__) && !defined(__clang__)) +#if ABSL_HAVE_CPP_ATTRIBUTE(gnu::tls_model) +#define ABSL_ATTRIBUTE_INITIAL_EXEC [[gnu::tls_model("initial-exec")]] +#elif ABSL_HAVE_ATTRIBUTE(tls_model) #define ABSL_ATTRIBUTE_INITIAL_EXEC __attribute__((tls_model("initial-exec"))) #else #define ABSL_ATTRIBUTE_INITIAL_EXEC @@ -647,7 +735,7 @@ // natural alignment of structure members not annotated is preserved. Aligned // member accesses are faster than non-aligned member accesses even if the // targeted microprocessor supports non-aligned accesses. -#if ABSL_HAVE_ATTRIBUTE(packed) || (defined(__GNUC__) && !defined(__clang__)) +#if ABSL_HAVE_ATTRIBUTE(packed) #define ABSL_ATTRIBUTE_PACKED __attribute__((__packed__)) #else #define ABSL_ATTRIBUTE_PACKED @@ -659,7 +747,7 @@ // alignment boundary #if ABSL_HAVE_CPP_ATTRIBUTE(gnu::aligned) #define ABSL_ATTRIBUTE_FUNC_ALIGN(bytes) [[gnu::aligned(bytes)]] -#elif ABSL_HAVE_ATTRIBUTE(aligned) || (defined(__GNUC__) && !defined(__clang__)) +#elif ABSL_HAVE_ATTRIBUTE(aligned) #define ABSL_ATTRIBUTE_FUNC_ALIGN(bytes) __attribute__((aligned(bytes))) #else #define ABSL_ATTRIBUTE_FUNC_ALIGN(bytes) @@ -1079,8 +1167,6 @@ // https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html#index-uninitialized-variable-attribute #if ABSL_HAVE_CPP_ATTRIBUTE(clang::uninitialized) #define ABSL_ATTRIBUTE_UNINITIALIZED [[clang::uninitialized]] -#elif ABSL_HAVE_CPP_ATTRIBUTE(gnu::uninitialized) -#define ABSL_ATTRIBUTE_UNINITIALIZED [[gnu::uninitialized]] #elif ABSL_HAVE_ATTRIBUTE(uninitialized) #define ABSL_ATTRIBUTE_UNINITIALIZED __attribute__((uninitialized)) #else @@ -1155,7 +1241,7 @@ // // Note: When wrapping a multi-line statement, placing a semicolon after the // closing parenthesis may produce an extra semicolon warning. -#if defined(__clang__) +#if ABSL_HAVE_CPP_ATTRIBUTE(clang::unsafe_buffer_usage) #define ABSL_UNSAFE_BUFFERS(...) \ _Pragma("clang unsafe_buffer_usage begin") \ __VA_ARGS__ _Pragma("clang unsafe_buffer_usage end")
diff --git a/absl/base/attributes_test.cc b/absl/base/attributes_test.cc index e87b66e..deabd5d 100644 --- a/absl/base/attributes_test.cc +++ b/absl/base/attributes_test.cc
@@ -14,7 +14,9 @@ #include "absl/base/attributes.h" +#include <cstdint> #include <type_traits> +#include <utility> #include "gtest/gtest.h" #include "absl/base/config.h" @@ -72,4 +74,35 @@ EXPECT_EQ(buffer[1], 1); } +ABSL_ATTRIBUTE_NOINLINE void MustTailVoidCallee(int* out, int x) { *out = x; } + +ABSL_ATTRIBUTE_NOINLINE void MustTailVoidCaller(int* out, int x) { + ABSL_INTERNAL_MUSTTAIL return MustTailVoidCallee(out, x + 2); +} + +ABSL_ATTRIBUTE_NOINLINE int64_t MustTailCountdown(int64_t n, int64_t acc) { + if (n == 0) return acc; + ABSL_INTERNAL_MUSTTAIL return MustTailCountdown(n - 1, acc + n); +} + +TEST(Attributes, MustTail) { + int out = 0; + MustTailVoidCaller(&out, 10); + EXPECT_EQ(out, 12); + +#if ABSL_INTERNAL_HAVE_MUSTTAIL + // A 200,000-deep recursion would overflow the stack without tail-call. + constexpr int64_t kDepth = 200000; + EXPECT_EQ(MustTailCountdown(kDepth, 0), kDepth * (kDepth + 1) / 2); +#endif +} + +ABSL_ATTRIBUTE_NO_SANITIZE_CFI int NoSanitizeCfiCall(int (*fn)(int), int x) { + return fn(x); +} + +TEST(Attributes, NoSanitizeCfi) { + EXPECT_EQ(NoSanitizeCfiCall([](int x) { return x + 1; }, 41), 42); +} + } // namespace
diff --git a/absl/base/call_once.h b/absl/base/call_once.h index 58d5d23..4c8bdbd 100644 --- a/absl/base/call_once.h +++ b/absl/base/call_once.h
@@ -148,6 +148,11 @@ kOnceDone = 221, // Random Number }; +inline constexpr SpinLockWaitTransition kCallOnceTransitions[] = { + {kOnceInit, kOnceRunning, true}, + {kOnceRunning, kOnceWaiter, false}, + {kOnceDone, kOnceDone, true}}; + template <typename Callable, typename... Args> void CallOnceImpl(std::atomic<uint32_t>* absl_nonnull control, @@ -166,10 +171,6 @@ } } #endif // NDEBUG - static const base_internal::SpinLockWaitTransition trans[] = { - {kOnceInit, kOnceRunning, true}, - {kOnceRunning, kOnceWaiter, false}, - {kOnceDone, kOnceDone, true}}; // Must do this before potentially modifying control word's state. base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode); @@ -180,8 +181,9 @@ uint32_t old_control = kOnceInit; if (control->compare_exchange_strong(old_control, kOnceRunning, std::memory_order_relaxed) || - base_internal::SpinLockWait(control, static_cast<int>(std::size(trans)), - trans, scheduling_mode) == kOnceInit) { + base_internal::SpinLockWait( + control, static_cast<int>(std::size(kCallOnceTransitions)), + kCallOnceTransitions, scheduling_mode) == kOnceInit) { std::invoke(std::forward<Callable>(fn), std::forward<Args>(args)...); old_control = control->exchange(base_internal::kOnceDone, std::memory_order_release);
diff --git a/absl/base/internal/cpu_detect.cc b/absl/base/internal/cpu_detect.cc index 43b6c4b..e6858e3 100644 --- a/absl/base/internal/cpu_detect.cc +++ b/absl/base/internal/cpu_detect.cc
@@ -316,6 +316,14 @@ return CpuType::kUnknown; } break; + case 0x4e: + switch (part_number) { + case 0x010: + return CpuType::kNvidiaVera; + default: + return CpuType::kUnknown; + } + break; case 0xc0: switch (part_number) { case 0xac3:
diff --git a/absl/base/internal/cpu_detect.h b/absl/base/internal/cpu_detect.h index 06eb72a..1ce3eba 100644 --- a/absl/base/internal/cpu_detect.h +++ b/absl/base/internal/cpu_detect.h
@@ -54,6 +54,7 @@ kArmNeoverseN3, kArmNeoverseN4, kNvidiaGrace, + kNvidiaVera, }; // Returns the type of host CPU this code is running on. Returns kUnknown if
diff --git a/absl/base/internal/raw_logging.cc b/absl/base/internal/raw_logging.cc index f705a38..c076a14 100644 --- a/absl/base/internal/raw_logging.cc +++ b/absl/base/internal/raw_logging.cc
@@ -107,7 +107,6 @@ *buf += n; return result; } -#endif // ABSL_LOW_LEVEL_WRITE_SUPPORTED constexpr int kLogBufSize = 3000; @@ -136,6 +135,16 @@ DoRawLog(buf, buf_size, "[%s : %d] RAW: ", file, line); return true; } +#else // !ABSL_LOW_LEVEL_WRITE_SUPPORTED +// Nothing is formatted or written; the buffer only holds the NUL terminator +// the abort hook expects. +constexpr int kLogBufSize = 1; + +bool DefaultLogFilterAndPrefix(absl::LogSeverity, const char*, int, char**, + int*) { + return true; +} +#endif // ABSL_LOW_LEVEL_WRITE_SUPPORTED ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES absl::base_internal::AtomicHook<LogFilterAndPrefixHook> @@ -151,6 +160,7 @@ char buffer[kLogBufSize]; char* buf = buffer; int size = sizeof(buffer); + buffer[0] = '\0'; #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED bool enabled = true; #else @@ -164,7 +174,9 @@ } #endif - enabled = log_filter_and_prefix_hook(severity, file, line, &buf, &size); + if (enabled) { + enabled = log_filter_and_prefix_hook(severity, file, line, &buf, &size); + } const char* const prefix_end = buf; #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED @@ -180,7 +192,6 @@ #else static_cast<void>(format); static_cast<void>(ap); - static_cast<void>(enabled); #endif // Abort the process after logging a FATAL message, even if the output itself
diff --git a/absl/base/internal/raw_logging.h b/absl/base/internal/raw_logging.h index 9cc270b..19aef0b 100644 --- a/absl/base/internal/raw_logging.h +++ b/absl/base/internal/raw_logging.h
@@ -156,14 +156,18 @@ // Function type for a raw_log customization hook for suppressing messages // by severity, and for writing custom prefixes on non-suppressed messages. // -// The installed hook is called for every raw log invocation. The message will -// be logged to stderr only if the hook returns true. FATAL errors will cause -// the process to abort, even if writing to stderr is suppressed. The hook is -// also provided with an output buffer, where it can write a custom log message -// prefix. +// The installed hook is called for every raw log invocation when logging is +// enabled (for example, it is skipped when low-level stderr writes are +// unsupported or when the message is suppressed by ABSL_MIN_LOG_LEVEL). The +// message will be logged to stderr only if the hook returns true. FATAL +// errors will cause the process to abort, even if writing to stderr is +// suppressed. The hook is also provided with an output buffer, where it can +// write a custom log message prefix. // // The raw_log system does not allocate memory or grab locks. User-provided -// hooks must avoid these operations, and must not throw exceptions. +// hooks must avoid these operations, must not throw exceptions, and must not +// have side effects other than writing to 'buf' (and updating '*buf' and +// '*buf_size'). // // 'severity' is the severity level of the message being written. // 'file' and 'line' are the file and line number where the ABSL_RAW_LOG macro
diff --git a/absl/base/prefetch.h b/absl/base/prefetch.h index 482cde3..96ee28d 100644 --- a/absl/base/prefetch.h +++ b/absl/base/prefetch.h
@@ -117,7 +117,9 @@ // This function is similar to `PrefetchToLocalCache()` except that it // prefetches cachelines with an 'intent to modify' This typically includes // invalidating cache entries for this address in all other cache tiers, and an -// exclusive access intent. +// exclusive access intent. On targets where the compiler cannot assume a +// write-prefetch instruction (e.g. x86-64 without PRFCHW), this is equivalent +// to `PrefetchToLocalCache()`. // // Incorrect or gratuitous use of this function can degrade performance. As this // function can invalidate cached cachelines on other caches and computer cores, @@ -154,15 +156,7 @@ ABSL_ATTRIBUTE_ALWAYS_INLINE inline void PrefetchToLocalCacheForWrite( const void* addr) { - // [x86] gcc/clang don't generate PREFETCHW for __builtin_prefetch(.., 1) - // unless -march=broadwell or newer; this is not generally the default, so we - // manually emit prefetchw. PREFETCHW is recognized as a no-op on older Intel - // processors and has been present on AMD processors since the K6-2. -#if defined(__x86_64__) && !defined(__PRFCHW__) - asm("prefetchw %0" : : "m"(*reinterpret_cast<const char*>(addr))); -#else __builtin_prefetch(addr, 1, 3); -#endif } #elif defined(ABSL_INTERNAL_HAVE_SSE) @@ -183,12 +177,8 @@ const void* addr) { #if defined(_MM_HINT_ET0) _mm_prefetch(reinterpret_cast<const char*>(addr), _MM_HINT_ET0); -#elif !defined(_MSC_VER) && defined(__x86_64__) - // _MM_HINT_ET0 is not universally supported. As we commented further - // up, PREFETCHW is recognized as a no-op on older Intel processors - // and has been present on AMD processors since the K6-2. We have this - // disabled for MSVC compilers as this miscompiles on older MSVC compilers. - asm("prefetchw %0" : : "m"(*reinterpret_cast<const char*>(addr))); +#else + _mm_prefetch(reinterpret_cast<const char*>(addr), _MM_HINT_T0); #endif }
diff --git a/absl/container/BUILD.bazel b/absl/container/BUILD.bazel index 4bb6fec..fbf0d56 100644 --- a/absl/container/BUILD.bazel +++ b/absl/container/BUILD.bazel
@@ -297,6 +297,7 @@ ":unordered_map_members_test", ":unordered_map_modifiers_test", "//absl/base:config", + "//absl/hash", "//absl/log:check", "//absl/meta:type_traits", "@googletest//:gtest", @@ -340,6 +341,7 @@ ":unordered_set_members_test", ":unordered_set_modifiers_test", "//absl/base:config", + "//absl/base:core_headers", "//absl/hash", "//absl/log:check", "//absl/memory", @@ -383,6 +385,7 @@ ":unordered_map_members_test", ":unordered_map_modifiers_test", "//absl/base:config", + "//absl/hash", "@googletest//:gtest", "@googletest//:gtest_main", ], @@ -442,6 +445,7 @@ "//absl/base:config", "//absl/base:core_headers", "//absl/hash", + "//absl/hash:canonical_hash", "//absl/memory", "//absl/meta:type_traits", "//absl/utility", @@ -460,6 +464,7 @@ "//absl/base:config", "//absl/base:no_destructor", "//absl/functional:overload", + "//absl/hash", "//absl/meta:type_traits", "//absl/strings:string_view", "@googletest//:gtest",
diff --git a/absl/container/CMakeLists.txt b/absl/container/CMakeLists.txt index 903b308..2d234aa 100644 --- a/absl/container/CMakeLists.txt +++ b/absl/container/CMakeLists.txt
@@ -336,6 +336,7 @@ absl::check absl::config absl::flat_hash_map + absl::hash absl::hash_generator_testing absl::hash_policy_testing absl::test_allocator @@ -376,6 +377,7 @@ absl::check absl::config absl::container_memory + absl::core_headers absl::flat_hash_set absl::hash absl::hash_container_defaults @@ -418,6 +420,7 @@ ${ABSL_TEST_COPTS} DEPS absl::config + absl::hash absl::hash_policy_testing absl::node_hash_map absl::tracked @@ -489,6 +492,7 @@ COPTS ${ABSL_DEFAULT_COPTS} DEPS + absl::canonical_hash absl::config absl::core_headers absl::hash @@ -508,6 +512,7 @@ DEPS absl::config absl::container_memory + absl::hash absl::no_destructor absl::overload absl::string_view
diff --git a/absl/container/chunked_queue.h b/absl/container/chunked_queue.h index a027291..682ba2b 100644 --- a/absl/container/chunked_queue.h +++ b/absl/container/chunked_queue.h
@@ -66,8 +66,9 @@ // == block size customization // // chunked_queue allows customization of the block size for each block. By -// default the block size is set to 1 element and the size doubles for the next -// block until it reaches the default max block size, which is 128 elements. +// default the block size is set to 1 element and the size grows by 1.5x for the +// next block until it reaches the default max block size, which is 64 +// elements. // // = fixed size // @@ -86,12 +87,11 @@ // sizes for the blocks. Initially the queue starts with the min block size and // as it grows, the size of each block grows until it reaches the max block // size. -// New blocks are double the size of the tail block (so they at least -// double the size of the queue). +// New blocks are 1.5x the size of the tail block. // -// chunked_queue<T, 4, 64>: first block 4 elements, second block 8 elements, -// third block 16 elements, fourth block 32 elements, -// all other blocks 64 elements +// chunked_queue<T, 4, 16>: first block 4 elements, second block 6 elements, +// third block 9 elements, fourth block 13 elements, +// all other blocks 16 elements // // One can specify a min and max such that small queues will not waste memory // and large queues will not have too many blocks. @@ -127,7 +127,7 @@ class chunked_queue { public: static constexpr size_t kBlockSizeMin = (BLo == 0 && BHi == 0) ? 1 : BLo; - static constexpr size_t kBlockSizeMax = (BLo == 0 && BHi == 0) ? 128 : BHi; + static constexpr size_t kBlockSizeMax = (BLo == 0 && BHi == 0) ? 64 : BHi; private: static_assert(kBlockSizeMin > 0, "Min block size cannot be zero"); @@ -580,11 +580,16 @@ void AddTailBlock(); // Returns the capacity (in elements) to allocate for a new block adjacent to // `b` (`head_.block` when prepending or `tail_.block` when appending). Starts - // at `kBlockSizeMin` when `b` is null, otherwise doubles `b->size()` and - // clamps to `[kBlockSizeMin, kBlockSizeMax]`. + // at `kBlockSizeMin` when `b` is null, otherwise grows `b->size()` by 1.5x + // and clamps to `[kBlockSizeMin, kBlockSizeMax]`. size_t NewBlockSize(Block* b) { if (!b) return kBlockSizeMin; - return (std::min)(kBlockSizeMax, 2 * b->size()); + const size_t prev_size = b->size(); + // Ensure the block size grows by at least 1 when `prev_size == 1` (since + // `static_cast<size_t>(1.5 * 1)` truncates to 1). + const size_t new_size = + (std::max)(static_cast<size_t>(1.5 * prev_size), prev_size + 1); + return (std::min)(kBlockSizeMax, new_size); } T* AllocateBack();
diff --git a/absl/container/flat_hash_map.h b/absl/container/flat_hash_map.h index fa91949..a63bb85 100644 --- a/absl/container/flat_hash_map.h +++ b/absl/container/flat_hash_map.h
@@ -686,6 +686,7 @@ using DefaultHash = DefaultHashContainerHash<K>; using DefaultEq = DefaultHashContainerEq<K>; using DefaultAlloc = std::allocator<std::pair<const K, V>>; + using SlotEq = SlotEqFn<K, /*kDerefSlot=*/false>; template <class Allocator, class... Args> static void construct(Allocator* alloc, slot_type* slot, Args&&... args) { @@ -706,9 +707,9 @@ template <class Hash, bool kIsDefault, size_t kSeedShift> static constexpr HashSlotFn get_hash_slot_fn() { - return memory_internal::IsLayoutCompatible<K, V>::value - ? &TypeErasedApplyToSlotFn<Hash, K, kIsDefault, kSeedShift> - : nullptr; + static_assert(memory_internal::OffsetOf<std::pair<const K, V>>::kFirst == + 0); + return GetTypeErasedApplyToSlotFn<Hash, K, kIsDefault, kSeedShift>(); } static std::pair<const K, V>& element(slot_type* slot) { return slot->value; }
diff --git a/absl/container/flat_hash_map_test.cc b/absl/container/flat_hash_map_test.cc index 213cb70..6bf8dc3 100644 --- a/absl/container/flat_hash_map_test.cc +++ b/absl/container/flat_hash_map_test.cc
@@ -31,6 +31,7 @@ #include "absl/container/internal/unordered_map_lookup_test.h" #include "absl/container/internal/unordered_map_members_test.h" #include "absl/container/internal/unordered_map_modifiers_test.h" +#include "absl/hash/hash.h" #include "absl/log/check.h" #include "absl/meta/type_traits.h" @@ -400,9 +401,18 @@ TEST(FlatHashMap, RecursiveTypeCompiles) { struct RecursiveType { flat_hash_map<int, RecursiveType> m; + flat_hash_map<int, RecursiveType>::iterator it; + flat_hash_map<int, RecursiveType>::const_iterator cit; + void Erase(int key) { m.erase(key); } }; RecursiveType t; t.m[0] = RecursiveType{}; + t.it = t.m.begin(); + t.cit = t.m.cbegin(); + EXPECT_NE(t.it, t.m.end()); + EXPECT_NE(t.cit, t.m.cend()); + t.Erase(0); + EXPECT_TRUE(t.m.empty()); } TEST(FlatHashMap, FlatHashMapPolicyDestroyReturnsTrue) { @@ -416,6 +426,13 @@ std::allocator<char>>(nullptr, nullptr))())); } +TEST(FlatHashMap, NonStandardLayoutKeyAndValueUseTypeErasedSlotFns) { + using Policy = FlatHashMapPolicy<NonStandardLayout, NonStandardLayout>; + EXPECT_NE((Policy::get_hash_slot_fn<absl::Hash<NonStandardLayout>, + /*kIsDefault=*/true, /*kSeedShift=*/0>()), + nullptr); +} + struct InconsistentHashEqType { InconsistentHashEqType(int v1, int v2) : v1(v1), v2(v2) {} template <typename H>
diff --git a/absl/container/flat_hash_set.h b/absl/container/flat_hash_set.h index b0527b3..42e186c 100644 --- a/absl/container/flat_hash_set.h +++ b/absl/container/flat_hash_set.h
@@ -563,6 +563,7 @@ using DefaultHash = DefaultHashContainerHash<T>; using DefaultEq = DefaultHashContainerEq<T>; using DefaultAlloc = std::allocator<T>; + using SlotEq = SlotEqFn<T, /*kDerefSlot=*/false>; template <class Allocator, class... Args> static void construct(Allocator* alloc, slot_type* slot, Args&&... args) { @@ -591,7 +592,7 @@ template <class Hash, bool kIsAbsl, size_t kSeedShift> static constexpr HashSlotFn get_hash_slot_fn() { - return &TypeErasedApplyToSlotFn<Hash, T, kIsAbsl, kSeedShift>; + return GetTypeErasedApplyToSlotFn<Hash, T, kIsAbsl, kSeedShift>(); } }; } // namespace container_internal
diff --git a/absl/container/flat_hash_set_test.cc b/absl/container/flat_hash_set_test.cc index df448a1..2a17c7c 100644 --- a/absl/container/flat_hash_set_test.cc +++ b/absl/container/flat_hash_set_test.cc
@@ -24,6 +24,7 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" +#include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/container/hash_container_defaults.h" #include "absl/container/internal/container_memory.h" @@ -408,6 +409,65 @@ }; EXPECT_EQ((HashtableDebugAccess<flat_hash_set<size_t, Hash>>::kIsAbslHash), false); + + EXPECT_EQ((GetTypeErasedApplyToSlotFn<StringHash, std::string, true, 0>()), + (GetTypeErasedApplyToSlotFn<absl::Hash<std::string>, std::string, + true, 0>())); + EXPECT_EQ((GetTypeErasedApplyToSlotFn<StringHash, std::string, true, 0>()), + (GetTypeErasedApplyToSlotFn< + absl::TransparentHash<std::string, absl::string_view>, + std::string, true, 0>())); + EXPECT_EQ( + (GetTypeErasedApplyToSlotFn<StringHash, absl::string_view, true, 0>()), + (GetTypeErasedApplyToSlotFn<absl::Hash<absl::string_view>, + absl::string_view, true, 0>())); + EXPECT_EQ((GetTypeErasedApplyToSlotFn<BasicStringHash<wchar_t>, std::wstring, + true, 0>()), + (GetTypeErasedApplyToSlotFn<absl::Hash<std::wstring>, std::wstring, + true, 0>())); + EXPECT_EQ((GetTypeErasedApplyToSlotFn<HashEq<int*>::Hash, int*, true, 0>()), + (GetTypeErasedApplyToSlotFn<absl::Hash<int*>, int*, true, 0>())); +} + +// Small trivially copyable key with padding bytes between `a` and `b`. +struct KeyWithPadding { + uint8_t a; + uint32_t b; + + friend bool operator==(const KeyWithPadding& x, const KeyWithPadding& y) { + return x.a == y.a && x.b == y.b; + } + template <typename H> + friend H AbslHashValue(H h, const KeyWithPadding& k) { + return H::combine(std::move(h), k.a, k.b); + } +}; + +// Initializes the fields of `*k` without touching its padding bytes. Not +// inlined so that the compiler keeps the padding uninitialized. +ABSL_ATTRIBUTE_NOINLINE void InitKey(KeyWithPadding* k, uint8_t a, uint32_t b) { + k->a = a; + k->b = b; +} + +// Regression test: keys that are small and trivially copyable but not +// uniquely represented must not be passed by value through the type erased +// hashing path, otherwise MemorySanitizer reports a use of uninitialized value +// for the padding bytes. +TEST(FlatHashSet, SmallKeyWithUninitializedPadding) { + // Keys live in default initialized heap memory so that the padding bytes + // stay uninitialized (stack objects may be split into their fields by the + // optimizer, and `make_unique` would value initialize the array). + std::unique_ptr<KeyWithPadding[]> keys(new KeyWithPadding[100]); + for (uint32_t i = 0; i < 100; ++i) { + InitKey(&keys[i], static_cast<uint8_t>(i), i); + } + absl::flat_hash_set<KeyWithPadding> set; + for (uint32_t i = 0; i < 100; ++i) { + set.insert(keys[i]); + } + EXPECT_EQ(set.size(), 100); + EXPECT_TRUE(set.contains(keys[42])); } #if defined(__cpp_lib_containers_ranges) && \
diff --git a/absl/container/inlined_vector_test.cc b/absl/container/inlined_vector_test.cc index 8bed847..ce5a023 100644 --- a/absl/container/inlined_vector_test.cc +++ b/absl/container/inlined_vector_test.cc
@@ -1020,6 +1020,7 @@ TEST(StringVec, SelfMove) { const std::string s = "A quite long string to ensure heap."; + std::vector<std::string> copy; for (int len = 0; len < 20; len++) { SCOPED_TRACE(len); absl::InlinedVector<std::string, 8> v; @@ -1032,7 +1033,7 @@ // Ensure that the inlined vector is still in a valid state by copying it. // We don't expect specific contents since a self-move results in an // unspecified valid state. - std::vector<std::string> copy(v.begin(), v.end()); + copy.assign(v.begin(), v.end()); } }
diff --git a/absl/container/internal/btree.h b/absl/container/internal/btree.h index 55ff457..9d44751 100644 --- a/absl/container/internal/btree.h +++ b/absl/container/internal/btree.h
@@ -569,9 +569,9 @@ // // internal nodes. // btree_node *children[kNodeSlots + 1]; // - // This class is only constructed by EmptyNodeType. Normally, pointers to the - // layout above are allocated, cast to btree_node*, and de-allocated within - // the btree implementation. + // This class is never constructed. Pointers to the layout above are + // allocated, cast to btree_node*, and de-allocated within the btree + // implementation. Empty btrees point to a shared BtreeEmptyNode instead. ~btree_node() = default; btree_node(btree_node const &) = delete; btree_node &operator=(btree_node const &) = delete; @@ -1337,33 +1337,50 @@ int position_; }; +// We use a static empty node for the root/leftmost/rightmost of empty btrees +// in order to avoid branching in begin()/end(). The empty node only depends on +// the node's field_type and alignment (not on the full Params), so it is +// defined outside of btree in order to be shared between all btrees with +// compatible node headers. +template <typename FieldType, size_t Alignment> +struct alignas(Alignment) BtreeEmptyNode { + // Mirrors the header of btree_node's layout (see the comment in btree_node). + void *parent; +#ifdef ABSL_BTREE_ENABLE_GENERATIONS + uint32_t generation = 0; +#endif + FieldType position = 0; + FieldType start = 0; + FieldType finish = 0; + // max_count must be != kInternalNodeMaxCount (so that this node is regarded + // as a leaf node). max_count() is never called when the tree is empty. + FieldType max_count = 1; + + constexpr BtreeEmptyNode() : parent(this) {} +}; + +template <typename FieldType, size_t Alignment> +BtreeEmptyNode<FieldType, Alignment> *GetBtreeEmptyNode() { + static constexpr BtreeEmptyNode<FieldType, Alignment> empty_node; + return const_cast<BtreeEmptyNode<FieldType, Alignment> *>(&empty_node); +} + template <typename Params> class btree { using node_type = btree_node<Params>; using is_key_compare_to = typename Params::is_key_compare_to; using field_type = typename node_type::field_type; - // We use a static empty node for the root/leftmost/rightmost of empty btrees - // in order to avoid branching in begin()/end(). - struct EmptyNodeType : node_type { - using field_type = typename node_type::field_type; - node_type *parent; -#ifdef ABSL_BTREE_ENABLE_GENERATIONS - uint32_t generation = 0; -#endif - field_type position = 0; - field_type start = 0; - field_type finish = 0; - // max_count must be != kInternalNodeMaxCount (so that this node is regarded - // as a leaf node). max_count() is never called when the tree is empty. - field_type max_count = node_type::kInternalNodeMaxCount + 1; - - constexpr EmptyNodeType() : parent(this) {} - }; + // Round the alignment of the empty node up to max natural alignment so that + // btrees with different natural node alignments share the same node. + static constexpr size_t kEmptyNodeAlignment = + (std::max)(alignof(std::max_align_t), size_t{node_type::Alignment()}); static node_type *EmptyNode() { - alignas(node_type::Alignment()) static constexpr EmptyNodeType empty_node; - return const_cast<EmptyNodeType *>(&empty_node); + static_assert(node_type::kInternalNodeMaxCount != 1, + "The empty node must be regarded as a leaf node."); + return reinterpret_cast<node_type *>( + GetBtreeEmptyNode<field_type, kEmptyNodeAlignment>()); } enum : uint32_t {
diff --git a/absl/container/internal/btree_container.h b/absl/container/internal/btree_container.h index eb7dfd1..1b9e3e8 100644 --- a/absl/container/internal/btree_container.h +++ b/absl/container/internal/btree_container.h
@@ -46,9 +46,10 @@ // `key_arg<K>` evaluates to `K` when the functors are transparent and to // `key_type` otherwise. It permits template argument deduction on `K` for the // transparent case. + // TODO(ezb): we can also pass by value whenever beneficial. template <class K> using key_arg = - typename KeyArg<params_type::kIsKeyCompareTransparent>::template type< + typename KeyArg<params_type::kIsKeyCompareTransparent>::template Select< K, typename Tree::key_type>; public:
diff --git a/absl/container/internal/common.h b/absl/container/internal/common.h index 344c9fe..89e71b7 100644 --- a/absl/container/internal/common.h +++ b/absl/container/internal/common.h
@@ -80,20 +80,31 @@ : std::true_type {}; template <bool is_transparent> -struct KeyArg { - // Transparent. Forward `K`. - template <typename K, typename key_type> - using type = K; +struct KeyArg; + +template <> +struct KeyArg<true> { + // Transparent case: forward the user's argument type as-is (without + // converting to the key type). + template <typename Arg, typename Key> + using Select = Arg; + + // In the transparent case, the argument type is deduced, and we can't make + // pass-by-value vs. pass-by-reference be conditional on the type. + template <typename Arg, typename Key> + using SelectReadOnly = const Arg&; }; template <> struct KeyArg<false> { - // Not transparent. Always use `key_type`. - // TODO(ezb): use AddConstRefIfExpensiveToCopy for non-transparent key - // arguments. Also experiment with using it more widely within non-user-facing - // functions in raw_hash_set. - template <typename K, typename key_type> - using type = key_type; + // Non-transparent case: convert the user's argument to the key type first. + template <typename Arg, typename Key> + using Select = Key; + + template <typename Arg, typename Key> + using SelectReadOnly = type_traits_internal::AddConstRefIfExpensiveToCopy< + // Allows incomplete Key by making it a dependent type. + std::conditional_t<false, Arg, Key>>; }; // The node_handle concept from C++17.
diff --git a/absl/container/internal/container_memory.h b/absl/container/internal/container_memory.h index 8e0653a..e09b880 100644 --- a/absl/container/internal/container_memory.h +++ b/absl/container/internal/container_memory.h
@@ -19,6 +19,7 @@ #include <cstddef> #include <cstdint> #include <cstring> +#include <functional> #include <memory> #include <new> #include <tuple> @@ -28,6 +29,7 @@ #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/hash/hash.h" +#include "absl/hash/internal/canonical_hash.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" #include "absl/utility/utility.h" @@ -351,24 +353,25 @@ namespace memory_internal { -// If Pair is a standard-layout type, OffsetOf<Pair>::kFirst and -// OffsetOf<Pair>::kSecond are equivalent to offsetof(Pair, first) and -// offsetof(Pair, second) respectively. Otherwise they are -1. -// -// The purpose of OffsetOf is to avoid calling offsetof() on non-standard-layout -// type, which is non-portable. -template <class Pair, class = std::true_type> -struct OffsetOf { - static constexpr size_t kFirst = static_cast<size_t>(-1); - static constexpr size_t kSecond = static_cast<size_t>(-1); -}; +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Winvalid-offsetof" +#endif +// OffsetOf<Pair>::kFirst and OffsetOf<Pair>::kSecond are equivalent to +// offsetof(Pair, first) and offsetof(Pair, second) respectively. `offsetof` on +// a non-standard-layout type is conditionally-supported, but all the compilers +// we care about support it for non-static data members. template <class Pair> -struct OffsetOf<Pair, typename std::is_standard_layout<Pair>::type> { +struct OffsetOf { static constexpr size_t kFirst = offsetof(Pair, first); static constexpr size_t kSecond = offsetof(Pair, second); }; +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + template <class K, class V> struct IsLayoutCompatible { private: @@ -592,22 +595,38 @@ size_t seed; }; -// No arguments function hash function for a specific key. -template <class Hash, class Key, bool kIsAbsl, size_t kSeedShift> +using EncodedHashKey = absl::hash_internal::EncodedHashKey; +using HashForKeyFn = absl::hash_internal::HashForKeyFn; + +// No arguments hash function for a specific key. +// If `kUseCanonical` is true, `Hash` must hash `Key` identically to +// `absl::Hash<Key>`, and `CanonicalHashKey` is used so that `get_hash_fn()` is +// shared across key types with the same canonical hasher. +template <class Hash, class Key, bool kIsAbsl, size_t kSeedShift, + bool kUseCanonical> struct HashKey { - size_t operator()(size_t seed) const { - return HashElement<Hash, kIsAbsl, kSeedShift>{hash, seed}(key); + static size_t GetHash(EncodedHashKey data, size_t seed) { + const auto& self = *data.ToPtr<HashKey>(); + return HashElement<Hash, kIsAbsl, kSeedShift>{self.hash, seed}(self.key); } - // Static version of the above to pass to type erased functions. - static size_t GetHash(void* data, size_t seed) { - return (*static_cast<const HashKey*>(data))(seed); - } + // `data()` and `get_hash_fn()` are passed to type erased functions. + EncodedHashKey data() const { return EncodedHashKey::FromPtr(this); } + static constexpr HashForKeyFn get_hash_fn() { return &GetHash; } + ABSL_ATTRIBUTE_NO_UNIQUE_ADDRESS type_traits_internal::AddConstRefIfExpensiveToCopy<Hash> hash; type_traits_internal::AddConstRefIfExpensiveToCopy<Key> key; }; +template <class Hash, class Key, bool kIsAbsl, size_t kSeedShift> +struct HashKey<Hash, Key, kIsAbsl, kSeedShift, /*kUseCanonical=*/true> + : absl::hash_internal::CanonicalHashKey<Key> { + static_assert(kIsAbsl, "kUseCanonical requires kIsAbsl"); + HashKey(const Hash&, const absl::remove_cvref_t<Key>& k) + : absl::hash_internal::CanonicalHashKey<Key>(k) {} +}; + // Variadic arguments equality function that ignore the rest of the arguments. // Useful for usage with policy traits. template <class K1, class KeyEqual> @@ -621,6 +640,25 @@ type_traits_internal::AddConstRefIfExpensiveToCopy<KeyEqual> eq; }; +// Type-erased slot equality functor with the key at offset 0 of `slot` (or +// `*slot` if `kDerefSlot` is true). +template <class SlotKey, bool kDerefSlot> +struct SlotEqFn { + using SlotKeyType = const SlotKey; + + template <class Eq, class SearchKey> + bool operator()(const Eq& eq, const void* slot, const SearchKey& key) const { + if constexpr (kDerefSlot) { + const void* node; + // Copy the pointer to avoid strict aliasing issues. + std::memcpy(&node, slot, sizeof(node)); + slot = node; + } + return EqualElement<SearchKey, Eq>{key, + eq}(*static_cast<const SlotKey*>(slot)); + } +}; + // Type erased function for computing hash of the slot. using HashSlotFn = size_t (*)(const void* hash_fn, void* slot, size_t seed); @@ -633,6 +671,27 @@ *f, seed}(*static_cast<const T*>(slot)); } +// Type erased function to apply `CanonicalHasher` to data inside of the `slot`. +template <class CanonicalHasher> +size_t TypeErasedApplyAbslHashToSlotFn(const void*, void* slot, size_t seed) { + using T = typename CanonicalHasher::KeyType; + return absl::hash_internal::HashWithSeed().hash( + CanonicalHasher(), *static_cast<const T*>(slot), seed); +} + +template <class Fn, class T, bool kIsAbsl, size_t kSeedShift> +constexpr HashSlotFn GetTypeErasedApplyToSlotFn() { + using NonConstT = std::remove_const_t<T>; + // Use the canonical `absl::Hash<NonConstT>` implementation when `Fn` is + // `absl::Hash<NonConstT>` or a transparent hasher (such as `StringHash`) + // that hashes `NonConstT` identically. + if constexpr (kIsAbsl && std::is_invocable_v<Fn, const NonConstT&>) { + return &TypeErasedApplyAbslHashToSlotFn< + decltype(absl::hash_internal::CanonicalHasher<NonConstT>())>; + } + return &TypeErasedApplyToSlotFn<Fn, NonConstT, kIsAbsl, kSeedShift>; +} + // Type erased function to apply `Fn` to data inside of the `*slot_ptr`. // The data is expected to have type `T`. template <class Fn, class T, bool kIsAbsl, size_t kSeedShift> @@ -644,12 +703,35 @@ // NodeHashMapPolicy::get_hash_slot_fn(). In that case, slot_ptr has type // `std::pair<const T, mapped_type>**`, which is not safe to dereference as // `const T**`. Note that it is safe to dereference `slot` afterwards because - // `IsLayoutCompatible` guarantees that `std::pair<const T, mapped_type>` is - // standard-layout. + // `std::pair<const T, mapped_type>::first` is at offset 0. std::memcpy(&slot, slot_ptr, sizeof(slot)); return HashElement<Fn, kIsAbsl, kSeedShift>{*f, seed}(*slot); } +// Type erased function to apply `CanonicalHasher` to data inside of the +// `*slot_ptr`. +template <class CanonicalHasher> +size_t TypeErasedDerefAndApplyAbslHashToSlotFn(const void*, void* slot_ptr, + size_t seed) { + using T = typename CanonicalHasher::KeyType; + const T* slot; + // See comment in `TypeErasedDerefAndApplyToSlotFn`. + std::memcpy(&slot, slot_ptr, sizeof(slot)); + return absl::hash_internal::HashWithSeed().hash(CanonicalHasher(), *slot, + seed); +} + +template <class Fn, class T, bool kIsAbsl, size_t kSeedShift> +constexpr HashSlotFn GetTypeErasedDerefAndApplyToSlotFn() { + using NonConstT = std::remove_const_t<T>; + // See comment in `GetTypeErasedApplyToSlotFn`. + if constexpr (kIsAbsl && std::is_invocable_v<Fn, const NonConstT&>) { + return &TypeErasedDerefAndApplyAbslHashToSlotFn< + decltype(absl::hash_internal::CanonicalHasher<NonConstT>())>; + } + return &TypeErasedDerefAndApplyToSlotFn<Fn, NonConstT, kIsAbsl, kSeedShift>; +} + } // namespace container_internal ABSL_NAMESPACE_END } // namespace absl
diff --git a/absl/container/internal/container_memory_test.cc b/absl/container/internal/container_memory_test.cc index f6fdd5c..619a749 100644 --- a/absl/container/internal/container_memory_test.cc +++ b/absl/container/internal/container_memory_test.cc
@@ -17,6 +17,7 @@ #include <cstddef> #include <cstdint> #include <cstring> +#include <functional> #include <map> #include <memory> #include <string> @@ -31,6 +32,7 @@ #include "absl/base/no_destructor.h" #include "absl/container/internal/test_instance_tracker.h" #include "absl/functional/overload.h" +#include "absl/hash/hash.h" #include "absl/meta/type_traits.h" #include "absl/strings/string_view.h" @@ -329,6 +331,27 @@ fn, seed)(x))); } +TEST(ApplyTest, GetTypeErasedApplyToSlotFnCanonicalizesTypes) { + enum class MyEnum : uint32_t { kOne = 1, kTwo = 2 }; + HashSlotFn fn = GetTypeErasedApplyToSlotFn<absl::Hash<int32_t>, int32_t, + /*kIsAbsl=*/true, 0>(); + EXPECT_EQ(fn, (GetTypeErasedApplyToSlotFn<absl::Hash<uint32_t>, uint32_t, + /*kIsAbsl=*/true, 0>())); + EXPECT_EQ(fn, (GetTypeErasedApplyToSlotFn<absl::Hash<MyEnum>, MyEnum, + /*kIsAbsl=*/true, 0>())); + EXPECT_EQ(fn, + (GetTypeErasedApplyToSlotFn<absl::TransparentHash<int32_t, int64_t>, + int32_t, + /*kIsAbsl=*/true, 0>())); + EXPECT_NE(fn, (GetTypeErasedApplyToSlotFn<absl::Hash<int32_t>, int32_t, + /*kIsAbsl=*/false, 0>())); + MyEnum c = MyEnum::kTwo; + size_t seed = 100; + EXPECT_EQ(fn(nullptr, &c, seed), + (HashElement<absl::Hash<MyEnum>, /*kIsAbsl=*/true, 0>( + absl::Hash<MyEnum>{}, seed)(c))); +} + TEST(ApplyTest, TypeErasedDerefAndApplyToSlotFn) { size_t x = 7; size_t seed = 100; @@ -342,6 +365,77 @@ fn, seed)(x))); } +TEST(ApplyTest, GetTypeErasedDerefAndApplyToSlotFnCanonicalizesTypes) { + enum class MyEnum : uint32_t { kOne = 1, kTwo = 2 }; + HashSlotFn fn = + GetTypeErasedDerefAndApplyToSlotFn<absl::Hash<int32_t>, int32_t, + /*kIsAbsl=*/true, 0>(); + EXPECT_EQ(fn, + (GetTypeErasedDerefAndApplyToSlotFn<absl::Hash<uint32_t>, uint32_t, + /*kIsAbsl=*/true, 0>())); + EXPECT_EQ(fn, (GetTypeErasedDerefAndApplyToSlotFn<absl::Hash<MyEnum>, MyEnum, + /*kIsAbsl=*/true, 0>())); + EXPECT_EQ(fn, (GetTypeErasedDerefAndApplyToSlotFn< + absl::TransparentHash<int32_t, int64_t>, int32_t, + /*kIsAbsl=*/true, 0>())); + EXPECT_NE(fn, + (GetTypeErasedDerefAndApplyToSlotFn<absl::Hash<int32_t>, int32_t, + /*kIsAbsl=*/false, 0>())); + MyEnum c = MyEnum::kTwo; + MyEnum* c_ptr = &c; + size_t seed = 100; + EXPECT_EQ(fn(nullptr, &c_ptr, seed), + (HashElement<absl::Hash<MyEnum>, /*kIsAbsl=*/true, 0>( + absl::Hash<MyEnum>{}, seed)(c))); +} + +TEST(HashKeyTest, NonCanonicalUsesHasher) { + auto hash = [](int32_t v) { return static_cast<size_t>(v + 42); }; + using HashKeyCustom = HashKey<decltype(hash), int32_t, /*kIsAbsl=*/false, + /*kSeedShift=*/0, /*kUseCanonical=*/false>; + int32_t a = 1; + size_t seed = 100; + HashKeyCustom hk{hash, a}; + EXPECT_EQ(hk.data().ToPtr<HashKeyCustom>(), &hk); + EXPECT_EQ(HashKeyCustom::get_hash_fn()(hk.data(), seed), + (HashElement<decltype(hash), /*kIsAbsl=*/false, 0>(hash, seed)(a))); +} + +TEST(EqSlotFnTest, SlotEqFnWorks) { + auto test_eq = [](auto eq) { + std::string key = "a"; + SlotEqFn<std::string, /*kDerefSlot=*/false> eq_slot; + static_assert(std::is_empty_v<decltype(eq_slot)>); + static_assert( + std::is_same_v<typename decltype(eq_slot)::SlotKeyType, + const std::string>); + std::string slot_match = "a"; + std::string slot_mismatch = "b"; + EXPECT_TRUE(eq_slot(eq, &slot_match, key)); + EXPECT_FALSE(eq_slot(eq, &slot_mismatch, key)); + + SlotEqFn<std::string, /*kDerefSlot=*/true> eq_deref; + static_assert(std::is_empty_v<decltype(eq_deref)>); + static_assert( + std::is_same_v<typename decltype(eq_deref)::SlotKeyType, + const std::string>); + std::string* slot_match_ptr = &slot_match; + std::string* slot_mismatch_ptr = &slot_mismatch; + EXPECT_TRUE(eq_deref(eq, &slot_match_ptr, key)); + EXPECT_FALSE(eq_deref(eq, &slot_mismatch_ptr, key)); + }; + + test_eq(std::equal_to<std::string>{}); + + struct StatefulEq { + int dummy = 0; + bool operator()(const std::string& lhs, const std::string& rhs) const { + return lhs == rhs; + } + }; + test_eq(StatefulEq{1}); +} + TEST(HashElement, DefaultHash) { size_t x = 7; size_t seed = 100;
diff --git a/absl/container/internal/hash_policy_traits.h b/absl/container/internal/hash_policy_traits.h index 0d3939d..3ea4f9b 100644 --- a/absl/container/internal/hash_policy_traits.h +++ b/absl/container/internal/hash_policy_traits.h
@@ -30,6 +30,19 @@ ABSL_NAMESPACE_BEGIN namespace container_internal { +// Avoid comparing function addresses with nullptr during constant evaluation, +// which GCC rejects with UBSan enabled. +// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71962 +template <HashSlotFn kPolicyFn, HashSlotFn kFallbackFn> +struct HashSlotFnSelector { + static constexpr HashSlotFn kValue = kPolicyFn; +}; + +template <HashSlotFn kFallbackFn> +struct HashSlotFnSelector<nullptr, kFallbackFn> { + static constexpr HashSlotFn kValue = kFallbackFn; +}; + // Defines how slots are initialized/destroyed/moved. template <class Policy, class = void> struct hash_policy_traits : common_policy_traits<Policy> { @@ -67,6 +80,30 @@ struct ConstantIteratorsImpl<P, std::void_t<typename P::constant_iterators>> : P::constant_iterators {}; + // Fallback slot equality functor using `Policy::apply` for custom layouts. + struct EqKeyNonTypeErased { + using SlotKeyType = const key_type; + + template <class Eq, class SearchKey> + bool operator()(const Eq& eq, const void* slot, + const SearchKey& key) const { + return Policy::apply( + EqualElement<SearchKey, Eq>{key, eq}, + hash_policy_traits::element( + static_cast<slot_type*>(const_cast<void*>(slot)))); + } + }; + + template <class P = Policy, class = void> + struct SlotEqImpl { + using type = EqKeyNonTypeErased; + }; + + template <class P> + struct SlotEqImpl<P, std::void_t<typename P::SlotEq>> { + using type = typename P::SlotEq; + }; + public: // The actual object stored in the hash table. using slot_type = typename Policy::slot_type; @@ -86,6 +123,11 @@ // Defaults to false if not provided by the policy. using constant_iterators = ConstantIteratorsImpl<>; + // Functor type for comparing keys with a slot. + // TODO(b/575748507): Require `SlotEq` for all policies and remove + // `SlotEqImpl` and `EqKeyNonTypeErased`. + using SlotEq = typename SlotEqImpl<>::type; + // Returns the amount of memory owned by `slot`, exclusive of `sizeof(*slot)`. // // If `slot` is nullptr, returns the constant amount of memory owned by any @@ -149,21 +191,10 @@ template <class Hash, bool kIsAbsl, size_t kSeedShift> static constexpr HashSlotFn get_hash_slot_fn() { -// get_hash_slot_fn may return nullptr to signal that non type erased function -// should be used. GCC warns against comparing function address with nullptr. -#if defined(__GNUC__) && !defined(__clang__) -#pragma GCC diagnostic push -// silent error: the address of * will never be NULL [-Werror=address] -#pragma GCC diagnostic ignored "-Waddress" -#endif - return Policy::template get_hash_slot_fn<Hash, kIsAbsl, kSeedShift>() == - nullptr - ? &hash_slot_fn_non_type_erased<Hash, kIsAbsl, kSeedShift> - : Policy::template get_hash_slot_fn<Hash, kIsAbsl, - kSeedShift>(); -#if defined(__GNUC__) && !defined(__clang__) -#pragma GCC diagnostic pop -#endif + // A null policy function selects the non-type-erased fallback. + return HashSlotFnSelector< + Policy::template get_hash_slot_fn<Hash, kIsAbsl, kSeedShift>(), + &hash_slot_fn_non_type_erased<Hash, kIsAbsl, kSeedShift>>::kValue; } private:
diff --git a/absl/container/internal/hash_policy_traits_test.cc b/absl/container/internal/hash_policy_traits_test.cc index ebe8074..0646923 100644 --- a/absl/container/internal/hash_policy_traits_test.cc +++ b/absl/container/internal/hash_policy_traits_test.cc
@@ -121,7 +121,7 @@ Hash hasher; Slot value = 7; - auto* fn = hash_policy_traits<PolicyNoHashFn>::get_hash_slot_fn< + constexpr auto* fn = hash_policy_traits<PolicyNoHashFn>::get_hash_slot_fn< Hash, /*kIsAbsl=*/false, /*kSeedShift=*/6>(); EXPECT_NE(fn, nullptr); EXPECT_EQ(fn(&hasher, &value, 100), @@ -136,7 +136,7 @@ Hash hasher; Slot value = 7; - auto* fn = hash_policy_traits<PolicyCustomHashFn>::get_hash_slot_fn< + constexpr auto* fn = hash_policy_traits<PolicyCustomHashFn>::get_hash_slot_fn< Hash, /*kIsAbsl=*/false, /*kSeedShift=*/6>(); EXPECT_EQ(fn, (PolicyCustomHashFn::get_hash_slot_fn<Hash, /*kIsAbsl=*/false,
diff --git a/absl/container/internal/hashtablez_sampler.h b/absl/container/internal/hashtablez_sampler.h index e54c62e..540205e 100644 --- a/absl/container/internal/hashtablez_sampler.h +++ b/absl/container/internal/hashtablez_sampler.h
@@ -76,8 +76,7 @@ // blocking for any readers that are currently sampling the object. void PrepareForSampling(int64_t stride, size_t inline_element_size_value, size_t key_size, size_t value_size, - uint16_t soo_capacity_value) - ABSL_EXCLUSIVE_LOCKS_REQUIRED(init_mu); + uint16_t soo_capacity_value); // These fields are mutated by the various Record* APIs and need to be // thread-safe.
diff --git a/absl/container/internal/raw_hash_map.h b/absl/container/internal/raw_hash_map.h index 746cb6e..b85accf 100644 --- a/absl/container/internal/raw_hash_map.h +++ b/absl/container/internal/raw_hash_map.h
@@ -63,11 +63,18 @@ using Hash = typename raw_hash_map::raw_hash_set::hasher; using Eq = typename raw_hash_map::raw_hash_set::key_equal; using Alloc = typename raw_hash_map::raw_hash_set::allocator_type; + using KeyArgImpl = + KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>; template <class K> using key_arg = - typename KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>:: - template type<K, typename Policy::key_type>; + typename KeyArgImpl::template Select<K, typename Policy::key_type>; + template <class K> + using const_key_arg = + typename KeyArgImpl::template SelectReadOnly< + K, typename Policy::key_type>; + template <class K> + using KeyParam = typename raw_hash_map::raw_hash_set::template KeyParam<K>; // NOTE: The mess here is to shorten the code for the (very repetitive) // function overloads, and to allow the lifetime-bound overloads to dispatch @@ -301,7 +308,7 @@ } template <class K = key_type, class P = Policy> - MappedReference<P> at(const key_arg<K>& key) ABSL_ATTRIBUTE_LIFETIME_BOUND { + MappedReference<P> at(const_key_arg<K> key) ABSL_ATTRIBUTE_LIFETIME_BOUND { auto it = this->find(key); if (this->unchecked_equals(it, this->end())) { ThrowStdOutOfRange("absl::container_internal::raw_hash_map<>::at"); @@ -310,7 +317,7 @@ } template <class K = key_type, class P = Policy> - MappedConstReference<P> at(const key_arg<K>& key) const + MappedConstReference<P> at(const_key_arg<K> key) const ABSL_ATTRIBUTE_LIFETIME_BOUND { auto it = this->find(key); if (this->unchecked_equals(it, this->end())) { @@ -365,7 +372,7 @@ template <class K, class V> std::pair<iterator, bool> insert_or_assign_impl(K&& k, V&& v) ABSL_ATTRIBUTE_LIFETIME_BOUND { - auto res = this->find_or_prepare_insert(k); + auto res = this->template find_or_prepare_insert<KeyParam<K>>(k); if (res.second) { this->emplace_at(res.first, std::forward<K>(k), std::forward<V>(v)); } else { @@ -377,7 +384,7 @@ template <class K = key_type, class... Args> std::pair<iterator, bool> try_emplace_impl(K&& k, Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND { - auto res = this->find_or_prepare_insert(k); + auto res = this->template find_or_prepare_insert<KeyParam<K>>(k); if (res.second) { // Try to avoid using std::tuple since that slows compilation. // (example: https://godbolt.org/z/nefW93T6K)
diff --git a/absl/container/internal/raw_hash_set.cc b/absl/container/internal/raw_hash_set.cc index 0fb3f83..bd36659 100644 --- a/absl/container/internal/raw_hash_set.cc +++ b/absl/container/internal/raw_hash_set.cc
@@ -1149,7 +1149,7 @@ ABSL_ATTRIBUTE_COLD ABSL_ATTRIBUTE_NOINLINE void ReportSingleElementTableGrowthToInfozAndForceSample( CommonFields& common, const AllocPolicy& __restrict policy, - void* hasher, HashForKeyFn get_hash) { + EncodedHashKey hasher, HashForKeyFn get_hash) { HashtablezInfoHandle infoz = ForcedTrySample(policy); common.generate_new_seed(/*has_infoz=*/true); ReportGrowthToInfozImpl(common, infoz, get_hash(hasher, common.seed().seed()), @@ -1170,7 +1170,8 @@ // `common` is first and `get_hash` is third to match argument order in callers. ABSL_ATTRIBUTE_COLD ABSL_ATTRIBUTE_NOINLINE void ReportInsertMissToInfozAndComputeHash(CommonFields& common, size_t probe_length, - void* hasher, HashForKeyFn get_hash) { + EncodedHashKey hasher, + HashForKeyFn get_hash) { common.infoz().RecordInsertMiss(get_hash(hasher, common.seed().seed()), probe_length); } @@ -1904,7 +1905,7 @@ void* Grow1To3AndPrepareInsert(CommonFields& common, const PolicyFunctions& __restrict policy, - void* hasher, HashForKeyFn get_hash, + EncodedHashKey hasher, HashForKeyFn get_hash, bool has_infoz, void* new_slots) { // TODO(b/413062340): Refactor to reuse more code with // GrowSooTableToNextCapacityAndPrepareInsert. @@ -2077,7 +2078,7 @@ void* PrepareInsertSmallNonSoo(CommonFields& common, const PolicyFunctions& __restrict policy, - void* hasher, HashForKeyFn get_hash) { + EncodedHashKey hasher, HashForKeyFn get_hash) { ABSL_SWISSTABLE_ASSERT(common.is_small()); ABSL_SWISSTABLE_ASSERT(!policy.alloc_policy->soo_enabled); const bool is_empty = common.empty_when_small(); @@ -2238,7 +2239,7 @@ ABSL_ATTRIBUTE_NOINLINE void* GrowEmptySooTableToNextCapacityForceSamplingAndPrepareInsert( CommonFields& common, const AllocPolicy& __restrict policy, - void* hasher, HashForKeyFn get_hash) { + EncodedHashKey hasher, HashForKeyFn get_hash) { const size_t kNewCapacity = NextCapacity(SooCapacity()); ResizeEmptyNonAllocatedTableImpl(common, policy, kNewCapacity, /*blocked_element_count=*/0, @@ -2340,7 +2341,7 @@ template <size_t SooSlotMemcpySize, bool TransferUsesMemcpy> void* GrowSooTableToNextCapacityAndPrepareInsert( CommonFields& common, const PolicyFunctions& __restrict policy, - void* hasher, HashForKeyFn get_hash, bool force_sampling) { + EncodedHashKey hasher, HashForKeyFn get_hash, bool force_sampling) { AssertSoo(common, *policy.alloc_policy); if (ABSL_PREDICT_FALSE(force_sampling)) { // The table is empty, it is only used for forced sampling of SOO tables. @@ -2627,7 +2628,7 @@ void* PrepareInsertLargeGenerationsEnabled( CommonFields& common, const PolicyFunctions& __restrict policy, size_t hash, Group::NonIterableBitMaskType mask_empty, size_t target_group_offset, - absl::FunctionRef<size_t(size_t)> recompute_hash) { + EncodedHashKey hasher, HashForKeyFn recompute_hash) { // NOLINTNEXTLINE(misc-static-assert) ABSL_SWISSTABLE_ASSERT(SwisstableGenerationsEnabled()); const size_t cap = common.capacity(); @@ -2637,7 +2638,7 @@ if (growth_left > 0 && common.should_rehash_for_bug_detection_on_insert()) { // Move to a different heap allocation in order to detect bugs. ResizeAllocatedTableWithSeedChange(common, policy, cap); - hash = recompute_hash(common.seed().seed()); + hash = recompute_hash(hasher, common.seed().seed()); FindInfo target_group; std::tie(target_group, mask_empty) = find_first_non_full_group(common, hash); @@ -2675,17 +2676,19 @@ // We need to instantiate ALL possible template combinations because we define // the function in the cc file. template void* GrowSooTableToNextCapacityAndPrepareInsert<0, false>( - CommonFields&, const PolicyFunctions&, void*, HashForKeyFn, bool); + CommonFields&, const PolicyFunctions&, EncodedHashKey, HashForKeyFn, bool); template void* GrowSooTableToNextCapacityAndPrepareInsert< OptimalMemcpySizeForSooSlotTransfer(1), true>(CommonFields&, - const PolicyFunctions&, void*, - HashForKeyFn, bool); + const PolicyFunctions&, + EncodedHashKey, HashForKeyFn, + bool); static_assert(VerifyOptimalMemcpySizeForSooSlotTransferRange(2, 3)); template void* GrowSooTableToNextCapacityAndPrepareInsert< OptimalMemcpySizeForSooSlotTransfer(3), true>(CommonFields&, - const PolicyFunctions&, void*, - HashForKeyFn, bool); + const PolicyFunctions&, + EncodedHashKey, HashForKeyFn, + bool); #if UINTPTR_MAX == UINT32_MAX static_assert(MaxSooSlotSize() == 4); @@ -2694,8 +2697,9 @@ static_assert(VerifyOptimalMemcpySizeForSooSlotTransferRange(4, 8)); template void* GrowSooTableToNextCapacityAndPrepareInsert< OptimalMemcpySizeForSooSlotTransfer(8), true>(CommonFields&, - const PolicyFunctions&, void*, - HashForKeyFn, bool); + const PolicyFunctions&, + EncodedHashKey, HashForKeyFn, + bool); static_assert(MaxSooSlotSize() == 8); #endif
diff --git a/absl/container/internal/raw_hash_set.h b/absl/container/internal/raw_hash_set.h index 1d2875f..a59d09b 100644 --- a/absl/container/internal/raw_hash_set.h +++ b/absl/container/internal/raw_hash_set.h
@@ -1395,12 +1395,15 @@ // Note: we can't use `slots()` because Qt defines `slots` as a macro. // Note: we take `ctrl` as a parameter so that raw_hash_set can benefit from // the separate storage assumption. - void* slot_array(ctrl_t* ctrl, size_t capacity) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE void* slot_array(ctrl_t* ctrl, + size_t capacity) const { ABSL_SWISSTABLE_ASSERT(ctrl == this->control()); ABSL_ASSUME(capacity > kMaxSmallCapacity); return ctrl + NumControlBytesForLargeTable(capacity); } - void* slot_array(size_t cap) const { return slot_array(control(), cap); } + ABSL_ATTRIBUTE_ALWAYS_INLINE void* slot_array(size_t cap) const { + return slot_array(control(), cap); + } // Returns pointer to the single slot of a table with capacity 1. void* single_non_soo_slot() const { ABSL_SWISSTABLE_ASSERT(capacity() == 1); @@ -1417,7 +1420,8 @@ } void set_full_soo() { AssertInSooMode(); - inline_data_.set_size(1); + ABSL_SWISSTABLE_ASSERT(empty()); + inline_data_.increment_size(); } void increment_size() { ABSL_SWISSTABLE_ASSERT(size() < capacity()); @@ -1865,6 +1869,98 @@ } } +// Base class for iterators that stores type-erased control and slot pointers +// and implements operations that do not depend on the slot type. +// Slot-size-dependent operations (increment, skip_empty_or_deleted) are member +// function templates rather than a derived class template so that instantiating +// raw_hash_set::iterator does not evaluate sizeof(slot_type) when the value +// type is incomplete (b/299109480). +class HashSetIteratorBase : private HashSetIteratorGenerationInfo { + friend class raw_hash_set_base; + + public: + // We use DefaultIterSlot() for default-constructed iterators so that + // they can be distinguished from end iterators, which have nullptr slot_. + HashSetIteratorBase() : slot_(DefaultIterSlot()) {} + + protected: + HashSetIteratorBase(ctrl_t* ctrl, void* slot, + const GenerationType* generation_ptr) + : HashSetIteratorGenerationInfo(generation_ptr), + ctrl_(ctrl), + slot_(slot) { + // This assumption helps the compiler know that any non-end iterator is + // not equal to any end iterator. + ABSL_ASSUME(slot != nullptr); + } + // For end() iterators. + explicit HashSetIteratorBase(const GenerationType* generation_ptr) + : HashSetIteratorGenerationInfo(generation_ptr), slot_(nullptr) {} + + void assert_is_full(const char* operation) const { + AssertIsFull(ctrl_, slot_, generation(), generation_ptr(), operation); + } + void* deref_slot() const { + assert_is_full("operator*()"); + return slot_; + } + void* arrow_slot() const { + assert_is_full("operator->"); + return slot_; + } + + template <size_t kSlotSize> + ABSL_ATTRIBUTE_ALWAYS_INLINE void increment() { + assert_is_full("operator++"); + ++ctrl_; + slot_ = static_cast<char*>(slot_) + kSlotSize; + skip_empty_or_deleted<kSlotSize>(); + if (ABSL_PREDICT_FALSE(*ctrl_ == ctrl_t::kSentinel)) slot_ = nullptr; + } + + // Fixes up `ctrl_` to point to a full or sentinel by advancing `ctrl_` and + // `slot_` until they reach one. + template <size_t kSlotSize> + ABSL_ATTRIBUTE_ALWAYS_INLINE void skip_empty_or_deleted() { + while (IsEmptyOrDeleted(*ctrl_)) { + ++ctrl_; + slot_ = static_cast<char*>(slot_) + kSlotSize; + } + } + + bool equals(const HashSetIteratorBase& b) const { + if constexpr (SwisstableDebugEnabled()) { + AssertIsValidForComparison(ctrl_, slot_, generation(), generation_ptr()); + AssertIsValidForComparison(b.ctrl_, b.slot_, b.generation(), + b.generation_ptr()); + AssertSameContainer(ctrl_, b.ctrl_, slot_, b.slot_, generation_ptr(), + b.generation_ptr()); + } + return unchecked_equals(b); + } + + // An equality check which skips ABSL Hardening iterator invalidation + // checks. + // Should be used when the lifetimes of the iterators are well-enough + // understood to prove that they cannot be invalid. + // Note: `b` is passed by reference because `HashSetIteratorBase` has an + // anonymous union member (`ctrl_`), which causes Clang to lower by-value + // copies as `memcpy` that affects compiler inlining decisions. + ABSL_ATTRIBUTE_ALWAYS_INLINE bool unchecked_equals( + const HashSetIteratorBase& b) const { + return slot_ == b.slot_; + } + + ctrl_t* control() const { return ctrl_; } + + // To avoid uninitialized member warnings, put ctrl_ in an anonymous union. + // The member is not initialized on singleton and end iterators. + union { + ctrl_t* ctrl_; + }; + void* slot_; +}; + struct FindInfo { size_t offset; size_t probe_length; @@ -1938,7 +2034,7 @@ constexpr size_t kProbedElementIndexSentinel = ~size_t{}; -// Implementation detail of transfer_unprobed_elements_to_next_capacity_fn. +// Implementation detail of TransferUnprobedElementsToNextCapacity. // Tries to find the new index for an element with `hash` for growth to the next // capacity. // Returns kProbedElementIndexSentinel if element was probed in the table before @@ -2103,6 +2199,10 @@ }; }; +// Transfers the contents of `count` slots from src_slot to dst_slot. +using TransferNFn = void (*)(void* set, void* dst_slot, void* src_slot, + size_t count); + // PolicyFunctions bundles together some information for a particular // raw_hash_set<T, ...> instantiation. This information is passed to // type-erased functions that want to do small amounts of type-specific @@ -2118,7 +2218,7 @@ // Transfers the contents of `count` slots from src_slot to dst_slot. // We use ability to transfer several slots in single group table growth. - void (*transfer_n)(void* set, void* dst_slot, void* src_slot, size_t count); + TransferNFn transfer_n; const AllocPolicy* alloc_policy; @@ -2142,6 +2242,25 @@ const void* hash_fn(const CommonFields& common) const { return reinterpret_cast<const char*>(&common) + hasher_offset; } + + // Returns the `PolicyFunctions` instance for tables with trivially + // relocatable slots. All function pointers are independent of the + // `raw_hash_set` type, so the instance is shared across all `raw_hash_set` + // instantiations with the same slot size, hasher offset, type erased slot + // hash function and `AllocPolicy` (which is itself shared for the default + // allocator). + template <uint32_t kSlotSize, uint32_t kHasherOffset, HashSlotFn kHashSlot, + const AllocPolicy* kAllocPolicy> + static constexpr const PolicyFunctions& GetRelocatableRef() { + return P<kSlotSize, kHasherOffset, kHashSlot, kAllocPolicy>::kP; + } + + private: + // Short name is used to minimize the mangled name length of static variables + // and reduce linker input size. + template <uint32_t kSlotSize, uint32_t kHasherOffset, HashSlotFn kHashSlot, + const AllocPolicy* kAllocPolicy> + struct P; }; using DestroySlotFn = void (*)(void* set, void* slot); @@ -2293,24 +2412,24 @@ return 8; } -using HashForKeyFn = size_t (*)(void* hasher, size_t seed); - // Resizes SOO table to the NextCapacity(SooCapacity()) and prepares insert for // the given new_hash. Returns the new slot. // All possible template combinations are defined in cc file to improve // compilation time. template <size_t SooSlotMemcpySize, bool TransferUsesMemcpy> -void* GrowSooTableToNextCapacityAndPrepareInsert( - CommonFields& common, const PolicyFunctions& policy, void* hasher, - HashForKeyFn get_hash, bool force_sampling); +void* GrowSooTableToNextCapacityAndPrepareInsert(CommonFields& common, + const PolicyFunctions& policy, + EncodedHashKey hasher, + HashForKeyFn get_hash, + bool force_sampling); // PrepareInsert for small tables (is_small()==true). // Returns the new slot. // Hash is only computed if the table is sampled or grew to large size // (is_small()==false). void* PrepareInsertSmallNonSoo(CommonFields& common, - const PolicyFunctions& policy, void* hasher, - HashForKeyFn get_hash); + const PolicyFunctions& policy, + EncodedHashKey hasher, HashForKeyFn get_hash); // Resizes table with allocated slots and change the table seed. // Tables with SOO enabled must have capacity > policy.soo_capacity. @@ -2382,6 +2501,99 @@ memcpy(dst, src, SizeOfSlot * count); } +// Implementation of +// `PolicyFunctions::transfer_unprobed_elements_to_next_capacity`. +// `Traits` describes the slot layout and operations: +// static constexpr size_t kSlotSize; +// // Returns the hash of the slot. +// static size_t HashSlot(CommonFields& common, void* slot, size_t seed); +// // Transfers `src_slot` into `dst_slot`. +// static void TransferSlot(CommonFields& common, void* dst_slot, +// void* src_slot); +// See `RelocatableSlotTransferTraits` (shared across tables with trivially +// relocatable slots) and `raw_hash_set::TransferTraits`. +template <class Traits> +void TransferUnprobedElementsToNextCapacity( + CommonFields& __restrict common, const ctrl_t* old_ctrl, + void* probed_storage, void* __restrict old_slots, size_t old_capacity, + void (*encode_probed_element)(void* probed_storage, size_t hash, + size_t source_offset)) { + constexpr size_t kSlotSize = Traits::kSlotSize; + ABSL_ASSUME(old_capacity + 1 >= Group::kWidth); + ABSL_ASSUME((old_capacity + 1) % Group::kWidth == 0); + const size_t new_capacity = NextCapacity(old_capacity); + ABSL_ASSUME(new_capacity > kMaxSmallCapacity); + ABSL_SWISSTABLE_ASSERT(common.capacity() == new_capacity); + + const size_t seed = common.seed().seed(); + ctrl_t* new_ctrl = common.control(); + char* new_slots = static_cast<char*>(common.slot_array(new_capacity)); + char* old_slots_ptr = static_cast<char*>(old_slots); + + for (size_t group_index = 0; group_index < old_capacity; + group_index += Group::kWidth) { + GroupFullEmptyOrDeleted old_g(old_ctrl + group_index); + std::memset(new_ctrl + group_index, static_cast<int8_t>(ctrl_t::kEmpty), + Group::kWidth); + std::memset(new_ctrl + group_index + old_capacity + 1, + static_cast<int8_t>(ctrl_t::kEmpty), Group::kWidth); + // TODO(b/382423690): try to type erase everything outside of the loop. + // We will share a lot of code in expense of one function call per group. + for (auto in_fixed_group_index : old_g.MaskFull()) { + size_t old_index = group_index + in_fixed_group_index; + char* old_slot = old_slots_ptr + old_index * kSlotSize; + // TODO(b/382423690): try to avoid entire hash calculation since we need + // only one new bit of h1. + size_t hash = Traits::HashSlot(common, old_slot, seed); + size_t new_index = TryFindNewIndexWithoutProbing( + hash, old_index, old_capacity, new_capacity); + // Note that encode_probed_element is allowed to use old_ctrl buffer + // till and included the old_index. + if (ABSL_PREDICT_FALSE(new_index == kProbedElementIndexSentinel)) { + encode_probed_element(probed_storage, hash, old_index); + continue; + } + ABSL_SWISSTABLE_ASSERT((new_index & old_capacity) <= old_index); + ABSL_SWISSTABLE_ASSERT(IsEmpty(new_ctrl[new_index])); + new_ctrl[new_index] = static_cast<ctrl_t>(H2(hash)); + char* new_slot = new_slots + new_index * kSlotSize; + SanitizerUnpoisonMemoryRegion(new_slot, kSlotSize); + Traits::TransferSlot(common, new_slot, old_slot); + SanitizerPoisonMemoryRegion(old_slot, kSlotSize); + } + } +} + +// `Traits` for `TransferUnprobedElementsToNextCapacity` for trivially +// relocatable slots. Slots are transferred with memcpy and hashed with the type +// erased `kHashSlot`, so the same instantiation is shared by all tables with +// the same slot size, hasher offset and type erased slot hash function. +template <size_t kSize, uint32_t kHasherOffset, HashSlotFn kHashSlot> +struct RelocatableSlotTransferTraits { + static constexpr size_t kSlotSize = kSize; + static size_t HashSlot(CommonFields& common, void* slot, size_t seed) { + return kHashSlot(reinterpret_cast<const char*>(&common) + kHasherOffset, + slot, seed); + } + static void TransferSlot(CommonFields&, void* dst_slot, void* src_slot) { + std::memcpy(dst_slot, src_slot, kSlotSize); + } +}; + +template <uint32_t kSlotSize, uint32_t kHasherOffset, HashSlotFn kHashSlot, + const AllocPolicy* kAllocPolicy> +struct PolicyFunctions::P { + static constexpr PolicyFunctions kP = { + kSlotSize, + kHasherOffset, + kHashSlot, + &TransferNRelocatable<kSlotSize>, + kAllocPolicy, + &TransferUnprobedElementsToNextCapacity< + RelocatableSlotTransferTraits<kSlotSize, kHasherOffset, kHashSlot>>, + }; +}; + // Given the hash of a value not currently in the table and the first group with // an empty slot in the probe sequence, finds a viable slot to insert it at. // @@ -2409,7 +2621,7 @@ void* PrepareInsertLargeGenerationsEnabled( CommonFields& common, const PolicyFunctions& policy, size_t hash, Group::NonIterableBitMaskType mask_empty, size_t target_group_offset, - absl::FunctionRef<size_t(size_t)> recompute_hash); + EncodedHashKey hasher, HashForKeyFn recompute_hash); template <typename Policy, typename Hash, typename Eq, typename Alloc> struct InstantiateRawHashSet { @@ -2439,6 +2651,265 @@ T, std::enable_if_t<!static_cast<bool>(Dummy), Alloc>>::value, AddConstRefIfExpensiveToMove<T>, std::add_rvalue_reference<T>>::type; +// Base class of raw_hash_set for operations that only depend on CommonFields. +// +// Note: kSooEnabled/kSlotSize are function template parameters to support +// incomplete `mapped_type`s (b/299109480). +class raw_hash_set_base { + template <class Container, typename Enabler> + friend struct absl::container_internal::hashtable_debug_internal:: + HashtableDebugAccess; + friend struct absl::container_internal::HashtableFreeFunctionsAccess; + friend struct RawHashSetTestOnlyAccess; + + public: + using size_type = size_t; + using difference_type = ptrdiff_t; + + bool empty() const { + AssertNotDebugCapacity(); + return common().empty(); + } + size_t bucket_count() const { return common().capacity(); } + float load_factor() const { + const size_t cap = common().capacity(); + return cap ? static_cast<float>(common().size()) / static_cast<float>(cap) + : 0.0f; + } + float max_load_factor() const { return 1.0f; } + void max_load_factor(float) { + // Does nothing. + } + + protected: + // `raw_hash_set` stores `common_` at offset 0 for standard-layout while + // `raw_hash_set_base` accesses `CommonFields` by casting `this`. + CommonFields& common() { return *reinterpret_cast<CommonFields*>(this); } + const CommonFields& common() const { + return *reinterpret_cast<const CommonFields*>(this); + } + + // For use when the capacity is potentially invalid we return + // HashtableCapacity directly. + HashtableCapacity maybe_invalid_capacity() const { + return common().maybe_invalid_capacity(); + } + + bool is_small() const { return common().is_small(); } + bool empty_when_small() const { return common().empty_when_small(); } + + // Asserts that the capacity is not a sentinel invalid value. + void AssertNotDebugCapacity() const { common().AssertNotDebugCapacity(); } + + template <bool kIsDefaultAlloc> + ctrl_t* control() const { + ctrl_t* ctrl = common().control(); + if constexpr (kIsDefaultAlloc) { + // Assume that the control bytes don't alias `this`. Example benefit: when + // a caller mutates an element via an iterator returned by find(), the + // compiler can now prove that the store to the slot does not clobber + // CommonFields metadata (size, capacity, etc.). + // Example of benefitting user code: + // if (auto it = m.find(k1); it != m.end()) it->second = v; + // if (auto it = m.find(k2); it != m.end()) it->second = v; + // With this assumption, the second lookup avoids reloading capacity. + // Note: for custom allocators, `this` may be part of the same allocation + // as the control bytes so we cannot make this assumption. + // Note: we could move this assumption into CommonFields::control() + // if we template the type-erased functions on whether the allocator is + // default or not, but it adds a lot of complexity, and we can avoid + // reloads in raw_hash_set.cc functions in other ways. + ABSL_SWISSTABLE_ASSUME_SEPARATE_STORAGE(ctrl, this); + } + return ctrl; + } + + template <bool kIsDefaultAlloc> + ABSL_ATTRIBUTE_ALWAYS_INLINE void* slot_array(size_t capacity) const { + // Note: we don't use common().slot_array(capacity) here because it misses + // the separate storage assumption in control(). + return common().slot_array(control<kIsDefaultAlloc>(), capacity); + } + + // Prefetch the heap-allocated memory region to resolve potential TLB and + // cache misses. This is intended to overlap with execution of calculating the + // hash for a key. + template <bool kIsDefaultAlloc> + void prefetch_heap_block() const { + ABSL_SWISSTABLE_ASSERT(!is_small()); +#if ABSL_HAVE_BUILTIN(__builtin_prefetch) || defined(__GNUC__) + __builtin_prefetch(control<kIsDefaultAlloc>(), 0, 1); +#endif + } + + // Whether this table is in SOO mode or non-SOO mode. + template <bool kSooEnabled> + bool is_soo() const { + static_assert(SooCapacity() == kMaxSmallCapacity); + return kSooEnabled && maybe_invalid_capacity().is_small(); + } + template <bool kSooEnabled> + bool is_full_soo() const { + return is_soo<kSooEnabled>() && !empty_when_small(); + } + + template <size_t kKeySize, size_t kSlotSize, bool kSooEnabled> + size_t capacity() const { + const size_t cap = common().capacity(); + // Compiler complains when using functions in ASSUME so use local variables. + [[maybe_unused]] const bool kIsValid = IsValidCapacity(cap); + [[maybe_unused]] constexpr size_t kDefaultCapacity = + kSooEnabled ? SooCapacity() : 0; + [[maybe_unused]] const size_t kMaxValidCapacity = + SizeToCapacity(container_internal::MaxValidSize(kKeySize, kSlotSize)); + ABSL_ASSUME(kIsValid || cap == 0); + ABSL_ASSUME(cap >= kDefaultCapacity); + ABSL_ASSUME(cap <= kMaxValidCapacity); + return cap; + } + + template <bool kSooEnabled, bool kIsDefaultAlloc> + void* single_slot() { + ABSL_SWISSTABLE_ASSERT(is_small()); + // Note: we don't use common().single_non_soo_slot() here because it misses + // the separate storage assumption in control(). + ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN( + kSooEnabled ? common().soo_data() : control<kIsDefaultAlloc>()); + } + template <bool kSooEnabled, bool kIsDefaultAlloc> + const void* single_slot() const { + return const_cast<raw_hash_set_base*>(this) + ->single_slot<kSooEnabled, kIsDefaultAlloc>(); + } + + // Erases, but does not destroy, the value pointed to by `it`. + // + // This merely updates the pertinent control byte. This can be used in + // conjunction with Policy::transfer to move the object to another slot. + template <bool kSooEnabled, size_t kSlotSize, bool kIsDefaultAlloc> + void erase_meta_only(const HashSetIteratorBase& it) { + if (is_small()) { + erase_meta_only_small<kSooEnabled, kSlotSize>(); + return; + } + erase_meta_only_large<kSlotSize, kIsDefaultAlloc>(it); + } + template <bool kSooEnabled, size_t kSlotSize> + void erase_meta_only_small() { + EraseMetaOnlySmall(common(), kSooEnabled, kSlotSize); + } + template <size_t kSlotSize, bool kIsDefaultAlloc> + void erase_meta_only_large(const HashSetIteratorBase& it) { + using SlotBytes = char[kSlotSize]; + const size_t cap = common().capacity(); + const auto* slot_ptr = + static_cast<const SlotBytes*>(slot_array<kIsDefaultAlloc>(cap)); + // `it` can be non-iterable iterator, so we can't use it.control(). + const size_t index = + static_cast<size_t>(static_cast<const SlotBytes*>(it.slot_) - slot_ptr); + EraseMetaOnlyLarge(common(), index, kSlotSize); + } + + template <class Hash, class KeyType> + static constexpr bool IsAbslHash() { + // Strip `const` so const slot key types match non-const `absl::Hash<K>`. + using NonConstKey = std::remove_const_t<KeyType>; + return std::is_same_v<Hash, absl::Hash<NonConstKey>> || + (!HasAbslContainerHash<NonConstKey>::value && + std::is_same_v<Hash, typename absl::container_internal::HashEq< + NonConstKey>::Hash>) || + // Note: this is useful (in addition to the above case) for cases of + // `absl_container_hash = + // DefaultHashContainerHash<absl::string_view>`. + std::is_same_v<Hash, absl::container_internal::StringHash> || + // TODO(b/384509507): resolve `no header providing + // "absl::hash_internal::TransparentHash" is directly included`. + // Maybe we should make "internal/hash.h" be a separate library. + is_instance_of<Hash, absl::hash_internal::TransparentHash>::value; + } + + // Hashing parameters shared by `raw_hash_set` and the type-erased + // `find_or_prepare_insert_large`. + template <class Hash, class SlotKey> + struct HashParams { + static constexpr bool kIsAbsl = IsAbslHash<Hash, SlotKey>(); + // For non-default hashers the seed is xor'ed with the hash value rather + // than being used as a seed for the hash function. Because we require + // random iteration order for small tables, the seed must have entropy in + // its low bits. For default absl::Hash, the pre-shifted `data_ & kSeedMask` + // value can be passed directly without a right shift. + static constexpr size_t kSeedShift = + kIsAbsl ? 0 : HashtableInlineData::kSeedShift; + // When `kIsAbsl` is true, `Hash` hashes `SlotKey` identically to + // `absl::Hash<SlotKey>` (see `GetTypeErasedApplyToSlotFn`), but may convert + // other lookup keys first (e.g. `const char*` for `StringHash`). + template <class K> + using HashKeyFor = + HashKey<Hash, absl::remove_cvref_t<K>, kIsAbsl, kSeedShift, + /*kUseCanonical=*/kIsAbsl && + std::is_same_v<absl::remove_cvref_t<K>, + absl::remove_cvref_t<SlotKey>>>; + }; + + // `policy` is a runtime argument so that tables that differ only in other + // policy functions share one instantiation. + template <class Key, size_t kSlotSize, bool kIsDefaultAlloc, bool kSooEnabled, + class Hash, size_t kHasherOffset, class Eq, size_t kEqOffset, + class SlotEq> + std::pair<void*, bool> find_or_prepare_insert_large( + const PolicyFunctions& policy, Key key) { + using SlotKeyType = typename SlotEq::SlotKeyType; + using Params = HashParams<Hash, SlotKeyType>; + + prefetch_heap_block<kIsDefaultAlloc>(); + const Hash& hash_ref = *reinterpret_cast<const Hash*>( + reinterpret_cast<const char*>(this) + kHasherOffset); + const Eq& eq_ref = *reinterpret_cast<const Eq*>( + reinterpret_cast<const char*>(this) + kEqOffset); + const size_t hash = HashElement<Hash, Params::kIsAbsl, Params::kSeedShift>{ + hash_ref, common().seed().seed()}(key); + const size_t cap = capacity<sizeof(SlotKeyType), kSlotSize, kSooEnabled>(); + auto seq = probe(ProbeCapacity{cap}, hash); + const h2_t h2 = H2(hash); + const ctrl_t* ctrl = control<kIsDefaultAlloc>(); + using SlotBytes = char[kSlotSize]; + auto* slot_array = + static_cast<SlotBytes*>(this->slot_array<kIsDefaultAlloc>(cap)); + while (true) { + // Loading the group before slot prefetch decreases critical path latency. + Group g{ctrl + seq.offset()}; +#ifndef ABSL_HAVE_MEMORY_SANITIZER + absl::PrefetchToLocalCache(slot_array + seq.offset()); +#endif + // Predict one iteration (common case for insert-hit). + if (auto match = g.Match(h2); ABSL_PREDICT_TRUE(match)) { + do { + void* slot = slot_array + seq.offset(*match); + if (ABSL_PREDICT_TRUE(SlotEq{}(eq_ref, slot, key))) + return {slot, false}; + } while (ABSL_PREDICT_FALSE(++match)); + } + auto mask_empty = g.MaskEmpty(); + if (ABSL_PREDICT_TRUE(mask_empty)) { + size_t target_group_offset = seq.offset(); + void* slot; + if constexpr (SwisstableGenerationsEnabled()) { + using Hasher = typename Params::template HashKeyFor<Key>; + Hasher hash_key{hash_ref, key}; + slot = PrepareInsertLargeGenerationsEnabled( + common(), policy, hash, mask_empty, target_group_offset, + hash_key.data(), Hasher::get_hash_fn()); + } else { + slot = PrepareInsertLarge(common(), policy, hash, mask_empty, + target_group_offset); + } + return {slot, true}; + } + seq.next(); + } + } +}; + // A SwissTable. // // Policy: a policy defines how to perform different operations on @@ -2471,7 +2942,7 @@ // This is the third element in `Params...` if it exists, or // Policy::DefaultAlloc otherwise. template <class Policy, class... Params> -class raw_hash_set { +class raw_hash_set : public raw_hash_set_base { using PolicyTraits = hash_policy_traits<Policy>; using Hash = GetFromListOr<typename Policy::DefaultHash, 0, Params...>; using Eq = GetFromListOr<typename Policy::DefaultEq, 1, Params...>; @@ -2490,8 +2961,6 @@ using init_type = typename PolicyTraits::init_type; using key_type = typename PolicyTraits::key_type; using allocator_type = Alloc; - using size_type = size_t; - using difference_type = ptrdiff_t; using hasher = Hash; using key_equal = Eq; using policy_type = Policy; @@ -2505,33 +2974,20 @@ private: // Alias used for heterogeneous lookup functions. - // `key_arg<K>` evaluates to `K` when the functors are transparent and to - // `key_type` otherwise. It permits template argument deduction on `K` for the - // transparent case. + // `const_key_arg<K>` evaluates to `const K&` when the functors are + // transparent and to `AddConstRefIfExpensiveToCopy<key_type>` otherwise. It + // permits template argument deduction on `K` for the transparent case. template <class K> - using key_arg = typename KeyArgImpl::template type<K, key_type>; + using const_key_arg = + typename KeyArgImpl::template SelectReadOnly<K, key_type>; using slot_type = typename PolicyTraits::slot_type; - constexpr static bool kIsAbslHash = - std::is_same_v<hasher, absl::Hash<key_type>> || - (!HasAbslContainerHash<key_type>::value && - std::is_same_v<hasher, typename absl::container_internal::HashEq< - key_type>::Hash>) || - // Note: this is useful (in addition to the above case) for cases of - // `absl_container_hash = DefaultHashContainerHash<absl::string_view>`. - std::is_same_v<hasher, absl::container_internal::StringHash> || - // TODO(b/384509507): resolve `no header providing - // "absl::hash_internal::TransparentHash" is directly included`. - // Maybe we should make "internal/hash.h" be a separate library. - is_instance_of<hasher, absl::hash_internal::TransparentHash>::value; - // For non-default hashers the seed is xor'ed with the hash value rather than - // being used as a seed for the hash function. Because we require random - // iteration order for small tables, the seed must have entropy in its low - // bits. For default absl::Hash, the pre-shifted `data_ & kSeedMask` value can - // be passed directly without a right shift. - constexpr static size_t kSeedShift = - kIsAbslHash ? 0 : HashtableInlineData::kSeedShift; + using HashParams = raw_hash_set_base::HashParams<hasher, key_type>; + constexpr static bool kIsAbslHash = HashParams::kIsAbsl; + constexpr static size_t kSeedShift = HashParams::kSeedShift; + template <class K> + using HashKeyFor = typename HashParams::template HashKeyFor<K>; constexpr static bool SooEnabled() { return FitsInSooSlot(sizeof(slot_type), alignof(slot_type)); @@ -2556,16 +3012,6 @@ return SizeToCapacity(MaxValidSize()); } - // Whether this table is in SOO mode or non-SOO mode. - bool is_soo() const { - static_assert(SooCapacity() == kMaxSmallCapacity); - return SooEnabled() && maybe_invalid_capacity().is_small(); - } - bool is_full_soo() const { return is_soo() && !empty_when_small(); } - - bool is_small() const { return common().is_small(); } - bool empty_when_small() const { return common().empty_when_small(); } - // Give an early error when key_type is not hashable/eq. auto KeyTypeCanBeHashed(const Hash& h, const key_type& k) -> decltype(h(k)); auto KeyTypeCanBeEq(const Eq& eq, const key_type& k) -> decltype(eq(k, k)); @@ -2643,7 +3089,8 @@ static_assert(std::is_same_v<const_pointer, const value_type*>, "Allocators with custom pointer types are not supported"); - class iterator : private HashSetIteratorGenerationInfo { + class iterator : private HashSetIteratorBase { + using Base = HashSetIteratorBase; friend class raw_hash_set; friend struct HashtableFreeFunctionsAccess; @@ -2656,29 +3103,21 @@ using pointer = std::remove_reference_t<reference>*; using difference_type = typename raw_hash_set::difference_type; - // We use DefaultIterSlot() for default-constructed iterators so that - // they can be distinguished from end iterators, which have nullptr slot_. - iterator() : slot_(static_cast<slot_type*>(DefaultIterSlot())) {} + iterator() = default; // PRECONDITION: not an end() iterator. reference operator*() const { - assert_is_full("operator*()"); - return unchecked_deref(); + return PolicyTraits::element(to_slot(this->deref_slot())); } // PRECONDITION: not an end() iterator. pointer operator->() const { - assert_is_full("operator->"); - return &operator*(); + return &PolicyTraits::element(to_slot(this->arrow_slot())); } // PRECONDITION: not an end() iterator. - iterator& operator++() { - assert_is_full("operator++"); - ++ctrl_; - ++slot_; - skip_empty_or_deleted(); - if (ABSL_PREDICT_FALSE(*ctrl_ == ctrl_t::kSentinel)) slot_ = nullptr; + ABSL_ATTRIBUTE_ALWAYS_INLINE iterator& operator++() { + this->increment<sizeof(slot_type)>(); return *this; } // PRECONDITION: not an end() iterator. @@ -2689,66 +3128,24 @@ } friend bool operator==(const iterator& a, const iterator& b) { - if constexpr (SwisstableDebugEnabled()) { - AssertIsValidForComparison(a.ctrl_, a.slot_, a.generation(), - a.generation_ptr()); - AssertIsValidForComparison(b.ctrl_, b.slot_, b.generation(), - b.generation_ptr()); - AssertSameContainer(a.ctrl_, b.ctrl_, a.slot_, b.slot_, - a.generation_ptr(), b.generation_ptr()); - } - return a.unchecked_equals(b); + return a.equals(b); } friend bool operator!=(const iterator& a, const iterator& b) { return !(a == b); } private: - iterator(ctrl_t* ctrl, slot_type* slot, - const GenerationType* generation_ptr) - : HashSetIteratorGenerationInfo(generation_ptr), - ctrl_(ctrl), - slot_(slot) { - // This assumption helps the compiler know that any non-end iterator is - // not equal to any end iterator. - ABSL_ASSUME(slot != nullptr); - } - // For end() iterators. - explicit iterator(const GenerationType* generation_ptr) - : HashSetIteratorGenerationInfo(generation_ptr), slot_(nullptr) {} - - void assert_is_full(const char* operation) const { - AssertIsFull(ctrl_, slot_, generation(), generation_ptr(), operation); - } - - // Fixes up `ctrl_` to point to a full or sentinel by advancing `ctrl_` and - // `slot_` until they reach one. - void skip_empty_or_deleted() { - while (IsEmptyOrDeleted(*ctrl_)) { - ++ctrl_; - ++slot_; - } - } - - // An equality check which skips ABSL Hardening iterator invalidation - // checks. - // Should be used when the lifetimes of the iterators are well-enough - // understood to prove that they cannot be invalid. - bool unchecked_equals(const iterator& b) const { return slot_ == b.slot(); } + using Base::Base; // Dereferences the iterator without ABSL Hardening iterator invalidation // checks. - reference unchecked_deref() const { return PolicyTraits::element(slot_); } + ABSL_ATTRIBUTE_ALWAYS_INLINE reference unchecked_deref() const { + return PolicyTraits::element(slot()); + } - ctrl_t* control() const { return ctrl_; } - slot_type* slot() const { return slot_; } - - // To avoid uninitialized member warnings, put ctrl_ in an anonymous union. - // The member is not initialized on singleton and end iterators. - union { - ctrl_t* ctrl_; - }; - slot_type* slot_; + ABSL_ATTRIBUTE_ALWAYS_INLINE slot_type* slot() const { + return to_slot(this->slot_); + } }; class const_iterator { @@ -2771,7 +3168,7 @@ reference operator*() const { return *inner_; } pointer operator->() const { return inner_.operator->(); } - const_iterator& operator++() { + ABSL_ATTRIBUTE_ALWAYS_INLINE const_iterator& operator++() { ++inner_; return *this; } @@ -2785,16 +3182,16 @@ } private: - const_iterator(const ctrl_t* ctrl, const slot_type* slot, - const GenerationType* gen) - : inner_(const_cast<ctrl_t*>(ctrl), const_cast<slot_type*>(slot), gen) { - } - bool unchecked_equals(const const_iterator& b) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE bool unchecked_equals( + const const_iterator& b) const { return inner_.unchecked_equals(b.inner_); } - reference unchecked_deref() const { return inner_.unchecked_deref(); } - ctrl_t* control() const { return inner_.control(); } - slot_type* slot() const { return inner_.slot(); } + ABSL_ATTRIBUTE_ALWAYS_INLINE reference unchecked_deref() const { + return inner_.unchecked_deref(); + } + ABSL_ATTRIBUTE_ALWAYS_INLINE slot_type* slot() const { + return inner_.slot(); + } iterator inner_; }; @@ -3033,7 +3430,7 @@ if (is_small()) return single_iterator(); iterator it = {control(), slot_array(capacity()), common().generation_ptr()}; - it.skip_empty_or_deleted(); + it.template skip_empty_or_deleted<sizeof(slot_type)>(); ABSL_SWISSTABLE_ASSERT(IsFull(*it.control())); return it; } @@ -3053,7 +3450,6 @@ } const_iterator cend() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return end(); } - bool empty() const { return !size(); } size_t size() const { AssertNotDebugCapacity(); const size_t size = common().size(); @@ -3062,15 +3458,8 @@ return size; } size_t capacity() const { - const size_t cap = common().capacity(); - // Compiler complains when using functions in ASSUME so use local variables. - [[maybe_unused]] const bool kIsValid = IsValidCapacity(cap); - [[maybe_unused]] const size_t kDefaultCapacity = DefaultCapacity(); - [[maybe_unused]] const size_t kMaxValidCapacity = MaxValidCapacity(); - ABSL_ASSUME(kIsValid || cap == 0); - ABSL_ASSUME(cap >= kDefaultCapacity); - ABSL_ASSUME(cap <= kMaxValidCapacity); - return cap; + return raw_hash_set_base::capacity<sizeof(key_type), sizeof(slot_type), + SooEnabled()>(); } size_t max_size() const { return MaxValidSize(); } @@ -3313,9 +3702,9 @@ }; template <class K = key_type, class F> - iterator lazy_emplace(const key_arg<K>& key, + iterator lazy_emplace(const_key_arg<K> key, F&& f) ABSL_ATTRIBUTE_LIFETIME_BOUND { - auto res = find_or_prepare_insert(key); + auto res = find_or_prepare_insert<KeyParam<const_key_arg<K>>>(key); if (res.second) { slot_type* slot = res.first; allocator_type alloc(char_alloc_ref()); @@ -3335,7 +3724,7 @@ // // Uses "abc" directly without copying it into std::string. // s.erase("abc"); template <class K = key_type> - size_type erase(const key_arg<K>& key) { + size_type erase(const_key_arg<K> key) { auto it = find(key); if (it.unchecked_equals(end())) return 0; erase(it); @@ -3355,7 +3744,7 @@ AssertNotDebugCapacity(); it.assert_is_full("erase()"); destroy(it.slot()); - erase_meta_only(it); + erase_meta_only<SooEnabled(), sizeof(slot_type), kIsDefaultAlloc>(it); } // TODO(b/515666499): Type erase entire function or begin/end case. @@ -3368,7 +3757,7 @@ if (first == last) return last.inner_; if (is_small()) { destroy(single_slot()); - erase_meta_only_small(); + erase_meta_only_small<SooEnabled(), sizeof(slot_type)>(); return end(); } if (first == begin() && last == end()) { @@ -3406,12 +3795,14 @@ if (src.is_small()) { if (src.empty_when_small()) return; if (insert_slot(src.single_slot())) - src.erase_meta_only_small(); + src.template erase_meta_only_small<SooEnabled(), sizeof(slot_type)>(); return; } for (auto it = src.begin(), e = src.end(); it != e;) { auto next = std::next(it); - if (insert_slot(it.slot())) src.erase_meta_only_large(it); + if (insert_slot(it.slot())) + src.template erase_meta_only_large<sizeof(slot_type), + kIsDefaultAlloc>(it); it = next; } } @@ -3429,13 +3820,14 @@ position.inner_.assert_is_full("extract()"); allocator_type alloc(char_alloc_ref()); auto node = CommonAccess::Transfer<node_type>(alloc, position.slot()); - erase_meta_only(position); + erase_meta_only<SooEnabled(), sizeof(slot_type), kIsDefaultAlloc>( + position.inner_); return node; } template <class K = key_type, std::enable_if_t<!std::is_same_v<K, iterator>, int> = 0> - node_type extract(const key_arg<K>& key) { + node_type extract(const_key_arg<K> key) { auto it = find(key); return it.unchecked_equals(end()) ? node_type() : extract(const_iterator{it}); @@ -3475,7 +3867,7 @@ // // Uses "abc" directly without copying it into std::string. // s.count("abc"); template <class K = key_type> - size_t count(const key_arg<K>& key) const { + size_t count(const_key_arg<K> key) const { return contains(key) ? 1 : 0; } @@ -3485,12 +3877,11 @@ // NOTE: This is a very low level operation and should not be used without // specific benchmarks indicating its importance. template <class K = key_type> - void prefetch([[maybe_unused]] const key_arg<K>& key) const { - if (capacity() == DefaultCapacity()) return; + void prefetch([[maybe_unused]] const_key_arg<K> key) const { + if (is_small()) return; // Avoid probing if we won't be able to prefetch the addresses received. #ifdef ABSL_HAVE_PREFETCH prefetch_heap_block(); - if (is_small()) return; auto seq = probe(common(), hash_of(key)); PrefetchToLocalCache(control() + seq.offset()); PrefetchToLocalCache(slot_array(capacity()) + seq.offset()); @@ -3499,33 +3890,32 @@ template <class K = key_type> ABSL_DEPRECATE_AND_INLINE() - iterator find(const key_arg<K>& key, - size_t) ABSL_ATTRIBUTE_LIFETIME_BOUND { + iterator find(const_key_arg<K> key, size_t) ABSL_ATTRIBUTE_LIFETIME_BOUND { return find(key); } // The API of find() has one extension: the type of the key argument doesn't // have to be key_type. This is so called heterogeneous key support. template <class K = key_type> - iterator find(const key_arg<K>& key) ABSL_ATTRIBUTE_LIFETIME_BOUND { - AssertOnFind(key); - if (is_small()) return find_small(key); - return find_large<FindLargeKey<key_arg<K>>>(key); + iterator find(const_key_arg<K> key) ABSL_ATTRIBUTE_LIFETIME_BOUND { + AssertOnFind<KeyParam<const_key_arg<K>>>(key); + if (is_small()) return find_small<KeyParam<const_key_arg<K>>>(key); + return find_large<FindLargeKey<const_key_arg<K>>>(key); } template <class K = key_type> ABSL_DEPRECATE_AND_INLINE() - const_iterator find(const key_arg<K>& key, - size_t) const ABSL_ATTRIBUTE_LIFETIME_BOUND { + const_iterator + find(const_key_arg<K> key, size_t) const ABSL_ATTRIBUTE_LIFETIME_BOUND { return find(key); } template <class K = key_type> - const_iterator find(const key_arg<K>& key) const + const_iterator find(const_key_arg<K> key) const ABSL_ATTRIBUTE_LIFETIME_BOUND { return const_cast<raw_hash_set*>(this)->find(key); } template <class K = key_type> - bool contains(const key_arg<K>& key) const { + bool contains(const_key_arg<K> key) const { // Here neither the iterator returned by `find()` nor `end()` can be invalid // outside of potential thread-safety issues. // `find()`'s return value is constructed, used, and then destructed @@ -3534,7 +3924,7 @@ } template <class K = key_type> - std::pair<iterator, iterator> equal_range(const key_arg<K>& key) + std::pair<iterator, iterator> equal_range(const_key_arg<K> key) ABSL_ATTRIBUTE_LIFETIME_BOUND { auto it = find(key); if (!it.unchecked_equals(end())) return {it, std::next(it)}; @@ -3542,21 +3932,12 @@ } template <class K = key_type> std::pair<const_iterator, const_iterator> equal_range( - const key_arg<K>& key) const ABSL_ATTRIBUTE_LIFETIME_BOUND { + const_key_arg<K> key) const ABSL_ATTRIBUTE_LIFETIME_BOUND { auto it = find(key); if (!it.unchecked_equals(end())) return {it, std::next(it)}; return {it, it}; } - size_t bucket_count() const { return capacity(); } - float load_factor() const { - return capacity() ? static_cast<double>(size()) / capacity() : 0.0; - } - float max_load_factor() const { return 1.0f; } - void max_load_factor(float) { - // Does nothing. - } - hasher hash_function() const { return hash_ref(); } key_equal key_eq() const { return eq_ref(); } allocator_type get_allocator() const { @@ -3620,7 +4001,7 @@ struct EmplaceDecomposable { template <class K, class... Args> std::pair<iterator, bool> operator()(const K& key, Args&&... args) const { - auto res = s.find_or_prepare_insert(key); + auto res = s.find_or_prepare_insert<KeyParam<K>>(key); if (res.second) { s.emplace_at(res.first, std::forward<Args>(args)...); } @@ -3633,7 +4014,7 @@ struct InsertSlot { template <class K, class... Args> std::pair<iterator, bool> operator()(const K& key, Args&&...) && { - auto res = s.find_or_prepare_insert(key); + auto res = s.find_or_prepare_insert<KeyParam<K>>(key); if (res.second) { s.transfer(res.first, &slot); } else if (do_destroy) { @@ -3666,8 +4047,10 @@ // TODO(b/289225379): consider having a helper class that has the impls for // SOO functionality. template <class K> - ABSL_ATTRIBUTE_ALWAYS_INLINE iterator find_small(const K& key) { - return empty_when_small() || !equal_to(key, single_slot()) + ABSL_ATTRIBUTE_ALWAYS_INLINE iterator + find_small(absl::type_identity_t<K> key) { + static_assert(std::is_same_v<K, KeyParam<K>>); + return empty_when_small() || !equal_to<K>(key, single_slot()) ? end() : single_iterator(); } @@ -3693,7 +4076,7 @@ if (auto match = g.Match(h2); ABSL_PREDICT_TRUE(match)) { do { const size_t offset = seq.offset(*match); - if (ABSL_PREDICT_TRUE(equal_to(key, slot_array + offset))) + if (ABSL_PREDICT_TRUE(equal_to<K>(key, slot_array + offset))) return iterator_at_ptr(ctrl + offset, slot_array + offset); } while (ABSL_PREDICT_FALSE(++match)); } @@ -3764,33 +4147,13 @@ } } - // Erases, but does not destroy, the value pointed to by `it`. - // - // This merely updates the pertinent control byte. This can be used in - // conjunction with Policy::transfer to move the object to another place. - void erase_meta_only(const_iterator it) { - if (is_small()) { - erase_meta_only_small(); - return; - } - erase_meta_only_large(it); - } - void erase_meta_only_small() { - EraseMetaOnlySmall(common(), SooEnabled(), sizeof(slot_type)); - } - void erase_meta_only_large(const_iterator it) { - EraseMetaOnlyLarge(common(), - // `it` can be non-iterable iterator, so we can't use - // it.control(). - static_cast<size_t>(it.slot() - slot_array(capacity())), - sizeof(slot_type)); - } - template <class K> - ABSL_ATTRIBUTE_ALWAYS_INLINE bool equal_to(const K& key, + ABSL_ATTRIBUTE_ALWAYS_INLINE bool equal_to(absl::type_identity_t<K> key, slot_type* slot) const { - return PolicyTraits::apply(EqualElement<K, key_equal>{key, eq_ref()}, - PolicyTraits::element(slot)); + static_assert(std::is_same_v<K, KeyParam<K>>); + return PolicyTraits::apply( + EqualElement<absl::remove_cvref_t<K>, key_equal>{key, eq_ref()}, + PolicyTraits::element(slot)); } template <class K> ABSL_ATTRIBUTE_ALWAYS_INLINE size_t hash_of(const K& key) const { @@ -3911,7 +4274,8 @@ template <class K> ABSL_ATTRIBUTE_ALWAYS_INLINE std::pair<slot_type*, bool> - find_or_prepare_insert_soo(const K& key) { + find_or_prepare_insert_soo(absl::type_identity_t<K> key) { + static_assert(std::is_same_v<K, KeyParam<K>>); bool force_sampling; slot_type* slot = single_slot(); if (empty_when_small()) { @@ -3920,39 +4284,41 @@ return {slot, true}; } force_sampling = true; - } else if (equal_to(key, slot)) { + } else if (equal_to<K>(key, slot)) { return {slot, false}; } else { force_sampling = false; } constexpr bool kUseMemcpy = PolicyTraits::transfer_uses_memcpy() && SooEnabled(); - using Hasher = HashKey<hasher, K, kIsAbslHash, kSeedShift>; + using Hasher = HashKeyFor<K>; Hasher hash_key{hash_ref(), key}; slot = to_slot( GrowSooTableToNextCapacityAndPrepareInsert< kUseMemcpy ? OptimalMemcpySizeForSooSlotTransfer(sizeof(slot_type)) : 0, - kUseMemcpy>(common(), GetPolicyFunctions(), &hash_key, - &Hasher::GetHash, force_sampling)); + kUseMemcpy>(common(), GetPolicyFunctions(), hash_key.data(), + Hasher::get_hash_fn(), force_sampling)); return {slot, true}; } template <class K> ABSL_ATTRIBUTE_ALWAYS_INLINE std::pair<slot_type*, bool> - find_or_prepare_insert_small(const K& key) { + find_or_prepare_insert_small(absl::type_identity_t<K> key) { + static_assert(std::is_same_v<K, KeyParam<K>>); if constexpr (SooEnabled()) { - return find_or_prepare_insert_soo(key); + return find_or_prepare_insert_soo<K>(key); } if (!empty_when_small()) { - if (equal_to(key, single_slot())) { + if (equal_to<K>(key, single_slot())) { return {single_slot(), false}; } } - using Hasher = HashKey<hasher, K, kIsAbslHash, kSeedShift>; + using Hasher = HashKeyFor<K>; Hasher hash_key{hash_ref(), key}; return {to_slot(PrepareInsertSmallNonSoo(common(), GetPolicyFunctions(), - &hash_key, &Hasher::GetHash)), + hash_key.data(), + Hasher::get_hash_fn())), true}; } @@ -3960,42 +4326,11 @@ std::pair<slot_type*, bool> find_or_prepare_insert_large( absl::type_identity_t<K> key) { static_assert(std::is_same_v<K, FindLargeKey<K>>); - prefetch_heap_block(); - const size_t hash = hash_of(key); - const size_t cap = capacity(); - auto seq = probe(ProbeCapacity{cap}, hash); - const h2_t h2 = H2(hash); - const ctrl_t* ctrl = control(); - slot_type* slot_array = this->slot_array(cap); - while (true) { - // Loading the group before slot prefetch decreases critical path latency. - Group g{ctrl + seq.offset()}; -#ifndef ABSL_HAVE_MEMORY_SANITIZER - absl::PrefetchToLocalCache(slot_array + seq.offset()); -#endif - // Predict one iteration (common case for insert-hit). - if (auto match = g.Match(h2); ABSL_PREDICT_TRUE(match)) { - do { - slot_type* slot = slot_array + seq.offset(*match); - if (ABSL_PREDICT_TRUE(equal_to(key, slot))) return {slot, false}; - } while (ABSL_PREDICT_FALSE(++match)); - } - auto mask_empty = g.MaskEmpty(); - if (ABSL_PREDICT_TRUE(mask_empty)) { - size_t target_group_offset = seq.offset(); - void* slot = - SwisstableGenerationsEnabled() - ? PrepareInsertLargeGenerationsEnabled( - common(), GetPolicyFunctions(), hash, mask_empty, - target_group_offset, - HashKey<hasher, absl::remove_cvref_t<K>, kIsAbslHash, - kSeedShift>{hash_ref(), key}) - : PrepareInsertLarge(common(), GetPolicyFunctions(), hash, - mask_empty, target_group_offset); - return {to_slot(slot), true}; - } - seq.next(); - } + auto [slot, inserted] = raw_hash_set_base::find_or_prepare_insert_large< + K, sizeof(slot_type), kIsDefaultAlloc, SooEnabled(), hasher, + HasherOffset(), key_equal, EqOffset(), typename PolicyTraits::SlotEq>( + GetPolicyFunctions(), key); + return {to_slot(slot), inserted}; } template <class InputIt> @@ -4004,35 +4339,41 @@ } protected: + template <class K> + using KeyParam = type_traits_internal::AddConstRefIfExpensiveToCopy< + absl::remove_cvref_t<K>>; + // Asserts for correctness that we run on find/find_or_prepare_insert. template <class K> - void AssertOnFind([[maybe_unused]] const K& key) { - AssertHashEqConsistent(key); + void AssertOnFind([[maybe_unused]] absl::type_identity_t<K> key) { + static_assert(std::is_same_v<K, KeyParam<K>>); + AssertHashEqConsistent<K>(key); AssertNotDebugCapacity(); } - // Asserts that the capacity is not a sentinel invalid value. - void AssertNotDebugCapacity() const { common().AssertNotDebugCapacity(); } - template <class K> static bool equal_to_key_fn(void* set, const void* key, void* slot) { - return static_cast<const raw_hash_set*>(set)->equal_to( - *static_cast<const K*>(key), to_slot(slot)); + static_assert(std::is_same_v<K, KeyParam<K>>); + return static_cast<const raw_hash_set*>(set)->equal_to<K>( + *static_cast<const absl::remove_cvref_t<K>*>(key), to_slot(slot)); } // Asserts that hash and equal functors provided by the user are consistent, // meaning that `eq(k1, k2)` implies `hash(k1)==hash(k2)`. template <class K> - void AssertHashEqConsistent(const K& key) { + void AssertHashEqConsistent(absl::type_identity_t<K> key) { + static_assert(std::is_same_v<K, KeyParam<K>>); // If the hash/eq functors are known to be consistent, then skip - // validation. + // validation. This improves debug performance, but also is important for + // correctness of the *ConversionCount tests, which fail if we call hash/eq + // on the lookup keys extra times (which triggers additional conversions). constexpr bool kIsStringAbslHashEq = std::is_same_v<hasher, absl::container_internal::StringHash> && std::is_same_v<key_equal, absl::container_internal::StringEq>; constexpr bool kIsScalarAbslHashEq = std::is_scalar_v<key_type> && - std::is_same_v<hasher, absl::Hash<key_type>> && - std::is_same_v<key_equal, std::equal_to<key_type>>; + std::is_same_v<hasher, typename HashEq<key_type>::Hash> && + std::is_same_v<key_equal, typename HashEq<key_type>::Eq>; if constexpr (kIsDebug && !kIsStringAbslHashEq && !kIsScalarAbslHashEq) { if (empty()) return; AssertHashEqConsistentImpl(common(), &hash_ref(), get_hash_slot_fn(), @@ -4045,9 +4386,11 @@ // where the value can be inserted into, with the control byte already set to // `key`'s H2. Returns a bool indicating whether an insertion can take place. template <class K> - std::pair<slot_type*, bool> find_or_prepare_insert(const K& key) { - AssertOnFind(key); - return is_small() ? find_or_prepare_insert_small(key) + std::pair<slot_type*, bool> find_or_prepare_insert( + absl::type_identity_t<K> key) { + static_assert(std::is_same_v<K, KeyParam<K>>); + AssertOnFind<K>(key); + return is_small() ? find_or_prepare_insert_small<K>(key) : find_or_prepare_insert_large<FindLargeKey<K>>(key); } @@ -4090,28 +4433,22 @@ } return {InsertIteratorControl(), slot, common().generation_ptr()}; } - iterator iterator_at(size_t i) ABSL_ATTRIBUTE_LIFETIME_BOUND { - return {control() + i, slot_array() + i, common().generation_ptr()}; - } - const_iterator iterator_at(size_t i) const ABSL_ATTRIBUTE_LIFETIME_BOUND { - return const_cast<raw_hash_set*>(this)->iterator_at(i); - } iterator iterator_at_ptr(ctrl_t* ctrl, void* slot) ABSL_ATTRIBUTE_LIFETIME_BOUND { - return {ctrl, to_slot(slot), common().generation_ptr()}; + return {ctrl, slot, common().generation_ptr()}; } // For use in raw_hash_map and friend functions. - static typename iterator::reference unchecked_deref(iterator it) { + ABSL_ATTRIBUTE_ALWAYS_INLINE static decltype(auto) unchecked_deref( + iterator it) { return it.unchecked_deref(); } - static const_reference unchecked_deref(const_iterator it) { + ABSL_ATTRIBUTE_ALWAYS_INLINE static const_reference unchecked_deref( + const_iterator it) { return it.unchecked_deref(); } - static bool unchecked_equals(iterator a, iterator b) { - return a.unchecked_equals(b); - } - static bool unchecked_equals(const_iterator a, const_iterator b) { + template <class Iter> + ABSL_ATTRIBUTE_ALWAYS_INLINE static bool unchecked_equals(Iter a, Iter b) { return a.unchecked_equals(b); } @@ -4120,65 +4457,45 @@ // For string-like keys, we convert to string_view when calling find*_large() // operations to (a) avoid repeatedly (i) branching on SSO or (ii) calling - // strlen(), (b) share code between the string-like types. Note that we don't - // pass FindLargeKey to find*_small() to avoid unnecessarily constructing - // string_view for small empty tables. Note: we use type_identity_t and - // static_asserts to ensure that the key type in find*_large is FindLargeKey. - // (type_identity_t ensures that the template argument is not deduced and must - // be specified explicitly.) - template <class K> - using FindLargeKey = - type_traits_internal::AddConstRefIfExpensiveToCopy<std::conditional_t< - std::is_same_v<hasher, absl::container_internal::StringHash> && - std::is_same_v<key_equal, absl::container_internal::StringEq> && - std::is_convertible_v<const absl::remove_cvref_t<K>&, - absl::string_view>, - absl::string_view, absl::remove_cvref_t<K>>>; + // strlen(), (b) share code between the string-like types. For pointer keys, + // we similarly convert to `const T*` to share code between `T*`, `const T*`, + // and derived-pointer lookups. Note that we avoid passing FindLargeKey to + // find*_small() to avoid unnecessarily constructing string_view for small + // empty tables. Note: we use type_identity_t and static_asserts to ensure + // that the key type in find*_large is FindLargeKey. (type_identity_t ensures + // that the template argument is not deduced and must be specified + // explicitly.) + template <class K, class RemoveCvrefK = absl::remove_cvref_t<K>, + bool IsStringHashEqAndConvertibleToStringView = + std::is_same_v<hasher, absl::container_internal::StringHash> && + std::is_same_v<key_equal, absl::container_internal::StringEq> && + std::is_convertible_v<const RemoveCvrefK&, absl::string_view>, + class Ptr = std::remove_pointer_t<key_type>*, + class ConstPtr = const std::remove_pointer_t<key_type>*, + bool IsPointerHashEqAndConvertibleToPtr = + std::is_pointer_v<key_type> && + std::is_same_v<hasher, typename HashEq<Ptr>::Hash> && + std::is_same_v<key_equal, typename HashEq<Ptr>::Eq> && + std::is_convertible_v<const RemoveCvrefK&, ConstPtr>> + using FindLargeKey = KeyParam<std::conditional_t< + IsStringHashEqAndConvertibleToStringView, absl::string_view, + std::conditional_t<IsPointerHashEqAndConvertibleToPtr, ConstPtr, + RemoveCvrefK>>>; - // Prefetch the heap-allocated memory region to resolve potential TLB and - // cache misses. This is intended to overlap with execution of calculating the - // hash for a key. + bool is_soo() const { return raw_hash_set_base::is_soo<SooEnabled()>(); } + bool is_full_soo() const { + return raw_hash_set_base::is_full_soo<SooEnabled()>(); + } void prefetch_heap_block() const { - ABSL_SWISSTABLE_ASSERT(!is_soo()); -#if ABSL_HAVE_BUILTIN(__builtin_prefetch) || defined(__GNUC__) - __builtin_prefetch(control(), 0, 1); -#endif + raw_hash_set_base::prefetch_heap_block<kIsDefaultAlloc>(); } - CommonFields& common() { return common_; } - const CommonFields& common() const { return common_; } - - // For use when the capacity is potentially invalid we return - // HashtableCapacity directly. - HashtableCapacity maybe_invalid_capacity() const { - return common().maybe_invalid_capacity(); - } ctrl_t* control() const { ABSL_SWISSTABLE_ASSERT(!is_soo()); - ctrl_t* ctrl = common().control(); - if constexpr (kIsDefaultAlloc) { - // Assume that the control bytes don't alias `this`. Example benefit: when - // a caller mutates an element via an iterator returned by find(), the - // compiler can now prove that the store to the slot does not clobber - // CommonFields metadata (size, capacity, etc.). - // Example of benefitting user code: - // if (auto it = m.find(k1); it != m.end()) it->second = v; - // if (auto it = m.find(k2); it != m.end()) it->second = v; - // With this assumption, the second lookup avoids reloading capacity. - // Note: for custom allocators, `this` may be part of the same allocation - // as the control bytes so we cannot make this assumption. - // Note: we could move this assumption into CommonFields::control() - // if we template the type-erased functions on whether the allocator is - // default or not, but it adds a lot of complexity, and we can avoid - // reloads in raw_hash_set.cc functions in other ways. - ABSL_SWISSTABLE_ASSUME_SEPARATE_STORAGE(ctrl, this); - } - return ctrl; + return raw_hash_set_base::control<kIsDefaultAlloc>(); } - slot_type* slot_array(size_t capacity) const { - // Note: we don't use common().slot_array(capacity) here because it misses - // the separate storage assumption in raw_hash_set::control(). - return static_cast<slot_type*>(common().slot_array(control(), capacity)); + ABSL_ATTRIBUTE_ALWAYS_INLINE slot_type* slot_array(size_t capacity) const { + return to_slot(raw_hash_set_base::slot_array<kIsDefaultAlloc>(capacity)); } slot_type* soo_slot() { ABSL_SWISSTABLE_ASSERT(is_soo()); @@ -4190,31 +4507,18 @@ const_cast<raw_hash_set*>(this)->soo_slot()); } slot_type* single_slot() { - ABSL_SWISSTABLE_ASSERT(is_small()); - // Note: we don't use common().single_non_soo_slot() here because it misses - // the separate storage assumption in raw_hash_set::control(). - return SooEnabled() ? soo_slot() : to_slot(control()); + return to_slot( + raw_hash_set_base::single_slot<SooEnabled(), kIsDefaultAlloc>()); } const slot_type* single_slot() const { return const_cast<raw_hash_set*>(this)->single_slot(); } - void decrement_small_size() { - ABSL_SWISSTABLE_ASSERT(is_small()); - SooEnabled() ? common().set_empty_soo() : common().decrement_size(); - if (!SooEnabled()) { - SanitizerPoisonObject(single_slot()); - } - } iterator single_iterator() { return {SooControl(), single_slot(), common().generation_ptr()}; } const_iterator single_iterator() const { return const_cast<raw_hash_set*>(this)->single_iterator(); } - HashtablezInfoHandle infoz() { - ABSL_SWISSTABLE_ASSERT(!is_soo()); - return common().infoz(); - } hasher& hash_ref() { return hash_; } const hasher& hash_ref() const { return hash_; } @@ -4235,9 +4539,15 @@ #pragma GCC diagnostic ignored "-Winvalid-offsetof" #endif static constexpr size_t HasherOffset() { + static_assert(offsetof(raw_hash_set, common_) == 0); return offsetof(raw_hash_set, hash_) - offsetof(raw_hash_set, common_); } + static constexpr size_t EqOffset() { + static_assert(offsetof(raw_hash_set, common_) == 0); + return offsetof(raw_hash_set, eq_) - offsetof(raw_hash_set, common_); + } static constexpr size_t AllocOffset() { + static_assert(offsetof(raw_hash_set, common_) == 0); return offsetof(raw_hash_set, alloc_) - offsetof(raw_hash_set, common_); } #if defined(__GNUC__) || defined(__clang__) @@ -4278,59 +4588,6 @@ : &raw_hash_set::destroy_slot_fn_impl; } - // TODO(b/382423690): Try to type erase entire function or at least type erase - // by GetKey + Hash for memcpyable types. - // TODO(b/382423690): Try to type erase for big slots: sizeof(slot_type) > 16. - static void transfer_unprobed_elements_to_next_capacity_fn( - CommonFields& __restrict common, const ctrl_t* old_ctrl, - void* probed_storage, void* __restrict old_slots, size_t old_capacity, - void (*encode_probed_element)(void* probed_storage, size_t hash, - size_t source_offset)) { - ABSL_ASSUME(old_capacity + 1 >= Group::kWidth); - ABSL_ASSUME((old_capacity + 1) % Group::kWidth == 0); - const size_t new_capacity = NextCapacity(old_capacity); - ABSL_ASSUME(new_capacity > kMaxSmallCapacity); - ABSL_SWISSTABLE_ASSERT(common.capacity() == new_capacity); - - auto* set = reinterpret_cast<raw_hash_set*>(&common); - slot_type* old_slots_ptr = to_slot(old_slots); - ctrl_t* new_ctrl = common.control(); - slot_type* new_slots = set->slot_array(new_capacity); - - for (size_t group_index = 0; group_index < old_capacity; - group_index += Group::kWidth) { - GroupFullEmptyOrDeleted old_g(old_ctrl + group_index); - std::memset(new_ctrl + group_index, static_cast<int8_t>(ctrl_t::kEmpty), - Group::kWidth); - std::memset(new_ctrl + group_index + old_capacity + 1, - static_cast<int8_t>(ctrl_t::kEmpty), Group::kWidth); - // TODO(b/382423690): try to type erase everything outside of the loop. - // We will share a lot of code in expense of one function call per group. - for (auto in_fixed_group_index : old_g.MaskFull()) { - size_t old_index = group_index + in_fixed_group_index; - slot_type* old_slot = old_slots_ptr + old_index; - // TODO(b/382423690): try to avoid entire hash calculation since we need - // only one new bit of h1. - size_t hash = set->hash_of(old_slot); - size_t new_index = TryFindNewIndexWithoutProbing( - hash, old_index, old_capacity, new_capacity); - // Note that encode_probed_element is allowed to use old_ctrl buffer - // till and included the old_index. - if (ABSL_PREDICT_FALSE(new_index == kProbedElementIndexSentinel)) { - encode_probed_element(probed_storage, hash, old_index); - continue; - } - ABSL_SWISSTABLE_ASSERT((new_index & old_capacity) <= old_index); - ABSL_SWISSTABLE_ASSERT(IsEmpty(new_ctrl[new_index])); - new_ctrl[new_index] = static_cast<ctrl_t>(H2(hash)); - auto* new_slot = new_slots + new_index; - SanitizerUnpoisonMemoryRegion(new_slot, sizeof(slot_type)); - set->transfer(new_slot, old_slot); - SanitizerPoisonMemoryRegion(old_slot, sizeof(slot_type)); - } - } - } - static constexpr DeallocBackingArrayFn get_dealloc_backing_array_fn() { return &DeallocateBackingArray<BackingArrayAlignment(alignof(slot_type)), CharAlloc>; @@ -4351,6 +4608,12 @@ } } + static constexpr bool HasSharedAllocPolicy() { + return BackingArrayAlignment(alignof(slot_type)) == + kStandardBackingArrayAlignment && + kIsDefaultAlloc; + } + static constexpr const AllocPolicy& GetAllocPolicy() { static_assert(sizeof(slot_type) <= (std::numeric_limits<uint32_t>::max)(), "Slot size is too large. Use std::unique_ptr for value type " @@ -4364,9 +4627,7 @@ size_t{(std::numeric_limits<uint16_t>::max)()}); static_assert(AllocOffset() <= size_t{(std::numeric_limits<uint32_t>::max)()}); - if constexpr (BackingArrayAlignment(alignof(slot_type)) == - kStandardBackingArrayAlignment && - kIsDefaultAlloc) { + if constexpr (HasSharedAllocPolicy()) { return AllocPolicy::GetNormalRef< static_cast<uint32_t>(sizeof(slot_type)), static_cast<uint16_t>(alignof(slot_type)), @@ -4377,19 +4638,51 @@ } } + // `Traits` for `TransferUnprobedElementsToNextCapacity` for slots that are + // not trivially relocatable. + struct TransferTraits { + static constexpr size_t kSlotSize = sizeof(slot_type); + static size_t HashSlot(CommonFields& common, void* slot, size_t) { + return reinterpret_cast<raw_hash_set&>(common).hash_of(to_slot(slot)); + } + static void TransferSlot(CommonFields& common, void* dst_slot, + void* src_slot) { + reinterpret_cast<raw_hash_set&>(common).transfer(to_slot(dst_slot), + to_slot(src_slot)); + } + }; + static const PolicyFunctions& GetPolicyFunctions() { static_assert(HasherOffset() <= size_t{(std::numeric_limits<uint32_t>::max)()}); - static constexpr PolicyFunctions value = { - static_cast<uint32_t>(sizeof(slot_type)), - static_cast<uint32_t>(HasherOffset()), - get_hash_slot_fn(), - PolicyTraits::transfer_uses_memcpy() - ? TransferNRelocatable<sizeof(slot_type)> - : &raw_hash_set::transfer_n_slots_fn, - &GetAllocPolicy(), - &raw_hash_set::transfer_unprobed_elements_to_next_capacity_fn}; - return value; + if constexpr (PolicyTraits::transfer_uses_memcpy() && + HasSharedAllocPolicy()) { + // All function pointers and `AllocPolicy` are independent of the + // `raw_hash_set` type, so the instance is shared with other tables with + // the same slot size, hasher offset, slot hash function and + // `AllocPolicy`. + return PolicyFunctions::GetRelocatableRef< + static_cast<uint32_t>(sizeof(slot_type)), + static_cast<uint32_t>(HasherOffset()), get_hash_slot_fn(), + &GetAllocPolicy()>(); + } else { + using Traits = std::conditional_t< + PolicyTraits::transfer_uses_memcpy(), + RelocatableSlotTransferTraits< + sizeof(slot_type), static_cast<uint32_t>(HasherOffset()), + get_hash_slot_fn()>, + TransferTraits>; + static constexpr PolicyFunctions value = { + static_cast<uint32_t>(sizeof(slot_type)), + static_cast<uint32_t>(HasherOffset()), + get_hash_slot_fn(), + PolicyTraits::transfer_uses_memcpy() + ? &TransferNRelocatable<sizeof(slot_type)> + : &raw_hash_set::transfer_n_slots_fn, + &GetAllocPolicy(), + &TransferUnprobedElementsToNextCapacity<Traits>}; + return value; + } } // `common_` must be the first member: type erased functions cast @@ -4423,7 +4716,8 @@ return 0; } c->destroy(it.slot()); - c->erase_meta_only_small(); + c->template erase_meta_only_small<Set::SooEnabled(), + sizeof(typename Set::slot_type)>(); return 1; } [[maybe_unused]] const size_t original_size_for_assert = c->size(); @@ -4491,11 +4785,12 @@ struct HashtableDebugAccess<Set, std::void_t<typename Set::raw_hash_set>> { using Traits = typename Set::PolicyTraits; using Slot = typename Traits::slot_type; + using KeyParam = + typename Set::raw_hash_set::template KeyParam<typename Set::key_type>; constexpr static bool kIsAbslHash = Set::kIsAbslHash; - static size_t GetNumProbes(const Set& set, - const typename Set::key_type& key) { + static size_t GetNumProbes(const Set& set, KeyParam key) { if (set.is_small()) return 0; size_t num_probes = 0; const size_t hash = set.hash_of(key); @@ -4505,7 +4800,8 @@ while (true) { container_internal::Group g{ctrl + seq.offset()}; for (uint32_t i : g.Match(h2)) { - if (set.equal_to(key, set.slot_array(set.capacity()) + seq.offset(i))) + if (set.template equal_to<KeyParam>( + key, set.slot_array(set.capacity()) + seq.offset(i))) return num_probes; ++num_probes; } @@ -4538,18 +4834,14 @@ // Extern template instantiations reduce binary size and linker input size. // Function definition is in raw_hash_set.cc. extern template void* GrowSooTableToNextCapacityAndPrepareInsert<0, false>( - CommonFields&, const PolicyFunctions&, void*, HashForKeyFn, - bool); + CommonFields&, const PolicyFunctions&, EncodedHashKey, HashForKeyFn, bool); extern template void* GrowSooTableToNextCapacityAndPrepareInsert<1, true>( - CommonFields&, const PolicyFunctions&, void*, HashForKeyFn, - bool); + CommonFields&, const PolicyFunctions&, EncodedHashKey, HashForKeyFn, bool); extern template void* GrowSooTableToNextCapacityAndPrepareInsert<4, true>( - CommonFields&, const PolicyFunctions&, void*, HashForKeyFn, - bool); + CommonFields&, const PolicyFunctions&, EncodedHashKey, HashForKeyFn, bool); #if UINTPTR_MAX == UINT64_MAX extern template void* GrowSooTableToNextCapacityAndPrepareInsert<8, true>( - CommonFields&, const PolicyFunctions&, void*, HashForKeyFn, - bool); + CommonFields&, const PolicyFunctions&, EncodedHashKey, HashForKeyFn, bool); #endif extern template void
diff --git a/absl/container/internal/raw_hash_set_test.cc b/absl/container/internal/raw_hash_set_test.cc index 91fb65f..a62adf5 100644 --- a/absl/container/internal/raw_hash_set_test.cc +++ b/absl/container/internal/raw_hash_set_test.cc
@@ -91,6 +91,10 @@ static size_t CountTombstones(const C& c) { return c.common().TombstonesCount(); } + template <typename C> + static const PolicyFunctions& GetPolicyFunctions() { + return C::GetPolicyFunctions(); + } }; namespace { @@ -1391,6 +1395,39 @@ std::equal_to<absl::string_view>, std::allocator<int>>)); } +TEST(Table, StandardLayout) { + struct StatelessHash { + size_t operator()(absl::string_view) const { return 0; } + }; + struct StatefulHash : StatelessHash { + uint64_t dummy; + }; + + // CommonFields is not standard-layout when generations are enabled because + // both CommonFields and its base class CommonFieldsGenerationInfoEnabled + // have non-static data members. + // TODO(b/556853247): Consider using composition with + // ABSL_ATTRIBUTE_NO_UNIQUE_ADDRESS instead of inheritance for + // CommonFieldsGenerationInfo to satisfy standard layout in ASan/MSan as well. + const bool expected = !SwisstableGenerationsEnabled(); + EXPECT_EQ(std::is_standard_layout_v<CommonFields>, expected); + EXPECT_EQ(std::is_standard_layout_v<raw_hash_set<IntPolicy>>, expected); + EXPECT_EQ( + (std::is_standard_layout_v< + raw_hash_set<StringPolicy, StatelessHash, + std::equal_to<absl::string_view>, std::allocator<int>>>), + expected); + EXPECT_EQ( + (std::is_standard_layout_v< + raw_hash_set<StringPolicy, StatefulHash, + std::equal_to<absl::string_view>, std::allocator<int>>>), + expected); + EXPECT_EQ(std::is_standard_layout_v<IntTable>, expected); + EXPECT_EQ(std::is_standard_layout_v<SooIntTable>, expected); + EXPECT_EQ(std::is_standard_layout_v<NonSooIntTable>, expected); + EXPECT_EQ(std::is_standard_layout_v<ChangingSizeAllocIntTable>, expected); +} + TEST(InstantiateRawHashSetTest, VerifyTypes) { using P = ValuePolicy<int>; using DA = typename P::DefaultHash; @@ -2839,17 +2876,20 @@ } } +extern const char kLazyEmplaceKey[]; + TEST(Table, LazyEmplace) { StringTable t; bool called = false; - auto it = t.lazy_emplace("abc", [&](const StringTable::constructor& f) { - called = true; - f("abc", "ABC"); - }); + auto it = + t.lazy_emplace(kLazyEmplaceKey, [&](const StringTable::constructor& f) { + called = true; + f("abc", "ABC"); + }); EXPECT_TRUE(called); EXPECT_THAT(*it, Pair("abc", "ABC")); called = false; - it = t.lazy_emplace("abc", [&](const StringTable::constructor& f) { + it = t.lazy_emplace(kLazyEmplaceKey, [&](const StringTable::constructor& f) { called = true; f("abc", "DEF"); }); @@ -2857,6 +2897,8 @@ EXPECT_THAT(*it, Pair("abc", "ABC")); } +const char kLazyEmplaceKey[] = "abc"; + int decompose_constructed; int decompose_copy_constructed; int decompose_copy_assigned; @@ -4276,7 +4318,7 @@ } std::vector<const HashtablezInfo*> infos = SampleSooMutation([](SooInt32Table& t) { - for (int i = 0; i < 10; ++i) { + for ([[maybe_unused]] int i = 0; i < 10; ++i) { t.insert(1); t.erase(1); } @@ -4329,7 +4371,7 @@ CHECK_LT(sizeof(void*), 8) << "missing SOO coverage"; GTEST_SKIP() << "not SOO on this platform"; } - std::vector<const HashtablezInfo*> infos = + [[maybe_unused]] std::vector<const HashtablezInfo*> infos = SampleSooMutation([](SooInt32Table& t) { t.insert(1); t.erase(1); @@ -4349,7 +4391,7 @@ CHECK_LT(sizeof(void*), 8) << "missing SOO coverage"; GTEST_SKIP() << "not SOO on this platform"; } - std::vector<const HashtablezInfo*> infos = + [[maybe_unused]] std::vector<const HashtablezInfo*> infos = SampleSooMutation([](SooInt32Table& t) { t.insert(1); t.erase(1); @@ -5493,6 +5535,137 @@ EXPECT_EQ(t.capacity(), kTargetCapacity); } +TEST(Table, PointerConversionCount) { + DisableSampling(); + + struct Base {}; + struct Derived : Base {}; + + struct ConvertibleToPtr { + explicit ConvertibleToPtr(Derived* v) : value(v) {} + ConvertibleToPtr(const ConvertibleToPtr&) = delete; + ConvertibleToPtr& operator=(const ConvertibleToPtr&) = delete; + + operator Derived*() const { + ++num_conversions; + return value; + } + + Derived* value; + mutable int num_conversions = 0; + }; + + Derived a, b, c, z; + absl::flat_hash_set<const Base*> t; + + // Empty table: no conversion to pointer. + { + ConvertibleToPtr k{&a}; + EXPECT_EQ(t.find(k), t.end()); + EXPECT_EQ(k.num_conversions, 0); + } + + // Single-element table: 1 conversion to pointer. + t.insert(&a); + { + ConvertibleToPtr k{&a}; + EXPECT_NE(t.find(k), t.end()); + EXPECT_EQ(k.num_conversions, 1); + } + { + ConvertibleToPtr k{&b}; + EXPECT_EQ(t.find(k), t.end()); + EXPECT_EQ(k.num_conversions, 1); + } + + // Many-element table: 1 conversion to pointer (would be 2 on hits without + // FindLargeKey canonicalization). + t.insert(&b); + t.insert(&c); + ASSERT_FALSE(RawHashSetTestOnlyAccess::GetCommon(t).is_small()); + { + ConvertibleToPtr k{&a}; + EXPECT_NE(t.find(k), t.end()); + EXPECT_EQ(k.num_conversions, 1); + } + { + ConvertibleToPtr k{&z}; + EXPECT_EQ(t.find(k), t.end()); + EXPECT_EQ(k.num_conversions, 1); + } + { + ConvertibleToPtr k{&a}; + EXPECT_FALSE(t.emplace(k).second); + EXPECT_EQ(k.num_conversions, 1); + } +} + +enum class EnumPtr : uintptr_t {}; +enum class Enum64 : int64_t {}; + +template <class Table> +const PolicyFunctions* GetPolicyFunctionsPtr() { + return &RawHashSetTestOnlyAccess::GetPolicyFunctions<Table>(); +} + +TEST(Table, PolicyFunctionsAreSharedForRelocatableSlots) { + // Tables with the same slot layout and type erased slot hash function share + // a single `PolicyFunctions` instance. Use pointer-sized integers so that + // `alignof(slot_type) <= alignof(size_t)` and `sizeof(EnumPtr) == + // sizeof(const void*)` on both 32-bit and 64-bit platforms. + const PolicyFunctions* intptr_pair_policy = + GetPolicyFunctionsPtr<absl::flat_hash_map<intptr_t, intptr_t>>(); + EXPECT_EQ(intptr_pair_policy, + (GetPolicyFunctionsPtr<absl::flat_hash_map<uintptr_t, EnumPtr>>())); + EXPECT_EQ( + intptr_pair_policy, + (GetPolicyFunctionsPtr<absl::flat_hash_map<EnumPtr, const void*>>())); + EXPECT_EQ( + intptr_pair_policy, + (GetPolicyFunctionsPtr<absl::flat_hash_map<const void*, intptr_t>>())); + + // Different slot size. + EXPECT_NE(intptr_pair_policy, + (GetPolicyFunctionsPtr<absl::flat_hash_map<int8_t, int8_t>>())); + // Same slot size, but different slot hash function. + EXPECT_NE(intptr_pair_policy, + GetPolicyFunctionsPtr<absl::flat_hash_set<absl::string_view>>()); + // Custom allocators have a distinct `AllocPolicy`, so `PolicyFunctions` is + // not shared, but the transfer function is still shared. + using CustomAllocTable = absl::flat_hash_map< + intptr_t, intptr_t, absl::Hash<intptr_t>, std::equal_to<intptr_t>, + CountingAllocator<std::pair<const intptr_t, intptr_t>>>; + EXPECT_NE(intptr_pair_policy, GetPolicyFunctionsPtr<CustomAllocTable>()); + EXPECT_EQ(intptr_pair_policy->transfer_unprobed_elements_to_next_capacity, + GetPolicyFunctionsPtr<CustomAllocTable>() + ->transfer_unprobed_elements_to_next_capacity); +} + +TEST(Table, GrowthWithSharedPolicyFunctions) { + // Exercise the shared transfer function across the growth paths from SOO up + // to a few resizes, including probed elements, for a few layouts. + const auto test = [](auto table) { + constexpr int kCount = 25; + using T = decltype(table); + using V = typename T::key_type; + for (int i = 0; i < kCount; ++i) { + table.insert(static_cast<V>(i)); + ASSERT_EQ(table.size(), static_cast<size_t>(i + 1)); + } + for (int i = 0; i < kCount; ++i) { + ASSERT_TRUE(table.contains(static_cast<V>(i))) << i; + } + ASSERT_FALSE(table.contains(static_cast<V>(kCount))); + }; + test(absl::flat_hash_set<int8_t>()); + test(absl::flat_hash_set<int16_t>()); + test(absl::flat_hash_set<int32_t>()); + test(absl::flat_hash_set<int64_t>()); + test(absl::flat_hash_set<Enum64>()); + // Non-canonical hasher that forces probing on every growth. + test(absl::flat_hash_set<int32_t, ZeroHash>()); +} + } // namespace } // namespace container_internal ABSL_NAMESPACE_END
diff --git a/absl/container/linked_hash_map.h b/absl/container/linked_hash_map.h index 60d53d3..b89e433 100644 --- a/absl/container/linked_hash_map.h +++ b/absl/container/linked_hash_map.h
@@ -73,7 +73,7 @@ private: template <class K> - using key_arg = typename KeyArgImpl::template type<K, key_type>; + using key_arg = typename KeyArgImpl::template Select<K, key_type>; using ListType = std::list<value_type, Alloc>;
diff --git a/absl/container/linked_hash_set.h b/absl/container/linked_hash_set.h index 18bee87..b1c0024 100644 --- a/absl/container/linked_hash_set.h +++ b/absl/container/linked_hash_set.h
@@ -67,7 +67,7 @@ private: template <class K> - using key_arg = typename KeyArgImpl::template type<K, key_type>; + using key_arg = typename KeyArgImpl::template Select<K, key_type>; using ListType = std::list<key_type, Alloc>;
diff --git a/absl/container/node_hash_map.h b/absl/container/node_hash_map.h index 28acb74..3512a1c 100644 --- a/absl/container/node_hash_map.h +++ b/absl/container/node_hash_map.h
@@ -646,6 +646,7 @@ using DefaultHash = DefaultHashContainerHash<Key>; using DefaultEq = DefaultHashContainerEq<Key>; using DefaultAlloc = std::allocator<std::pair<const Key, Value>>; + using SlotEq = SlotEqFn<Key, /*kDerefSlot=*/true>; template <class Allocator, class... Args> static value_type* new_element(Allocator* alloc, Args&&... args) { @@ -684,10 +685,8 @@ template <class Hash, bool kIsAbsl, size_t kSeedShift> static constexpr HashSlotFn get_hash_slot_fn() { - return memory_internal::IsLayoutCompatible<Key, Value>::value - ? &TypeErasedDerefAndApplyToSlotFn<Hash, Key, kIsAbsl, - kSeedShift> - : nullptr; + static_assert(memory_internal::OffsetOf<value_type>::kFirst == 0); + return GetTypeErasedDerefAndApplyToSlotFn<Hash, Key, kIsAbsl, kSeedShift>(); } }; } // namespace container_internal
diff --git a/absl/container/node_hash_map_test.cc b/absl/container/node_hash_map_test.cc index 476b12f..ee7af0a 100644 --- a/absl/container/node_hash_map_test.cc +++ b/absl/container/node_hash_map_test.cc
@@ -31,6 +31,7 @@ #include "absl/container/internal/unordered_map_lookup_test.h" #include "absl/container/internal/unordered_map_members_test.h" #include "absl/container/internal/unordered_map_modifiers_test.h" +#include "absl/hash/hash.h" #if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L #include <ranges> // NOLINT(build/c++20) @@ -77,7 +78,6 @@ ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(1, t.num_copies()); - const std::string ca("a"); m.emplace(a, t); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(1, t.num_copies()); @@ -346,6 +346,13 @@ t.m[0] = RecursiveType{}; } +TEST(NodeHashMap, NonStandardLayoutValueUsesTypeErasedSlotFns) { + using Policy = NodeHashMapPolicy<int, NonStandardLayout>; + EXPECT_NE((Policy::get_hash_slot_fn<absl::Hash<int>, /*kIsAbsl=*/true, + /*kSeedShift=*/0>()), + nullptr); +} + #if defined(__cpp_lib_containers_ranges) && \ __cpp_lib_containers_ranges >= 202202L TEST(NodeHashMap, FromRange) {
diff --git a/absl/container/node_hash_set.h b/absl/container/node_hash_set.h index 7265029..e211e33 100644 --- a/absl/container/node_hash_set.h +++ b/absl/container/node_hash_set.h
@@ -552,6 +552,7 @@ using DefaultHash = DefaultHashContainerHash<T>; using DefaultEq = DefaultHashContainerEq<T>; using DefaultAlloc = std::allocator<T>; + using SlotEq = SlotEqFn<T, /*kDerefSlot=*/true>; template <class Allocator, class... Args> static T* new_element(Allocator* alloc, Args&&... args) { @@ -585,7 +586,7 @@ template <class Hash, bool kIsAbsl, size_t kSeedShift> static constexpr HashSlotFn get_hash_slot_fn() { - return &TypeErasedDerefAndApplyToSlotFn<Hash, T, kIsAbsl, kSeedShift>; + return GetTypeErasedDerefAndApplyToSlotFn<Hash, T, kIsAbsl, kSeedShift>(); } }; } // namespace container_internal
diff --git a/absl/crc/internal/crc.cc b/absl/crc/internal/crc.cc index 6041c43..1d26628 100644 --- a/absl/crc/internal/crc.cc +++ b/absl/crc/internal/crc.cc
@@ -440,14 +440,9 @@ } #ifndef NDEBUG -ABSL_ATTRIBUTE_WEAK +ABSL_ATTRIBUTE_WEAK void DebugReportNonTemporalStore() {} +ABSL_ATTRIBUTE_WEAK void DebugReportStoreFence() {} #endif -void DebugReportNonTemporalStore() {} - -#ifndef NDEBUG -ABSL_ATTRIBUTE_WEAK -#endif -void DebugReportStoreFence() {} } // namespace crc_internal ABSL_NAMESPACE_END
diff --git a/absl/crc/internal/crc.h b/absl/crc/internal/crc.h index 5f9306c..d2fb11b 100644 --- a/absl/crc/internal/crc.h +++ b/absl/crc/internal/crc.h
@@ -85,8 +85,21 @@ }; // Bookkeeping hooks called by non-temporal store functions and // NonTemporalStoreFence(), for use in tests. +// +// In debug builds (!defined(NDEBUG)), these are declared out-of-line and +// defined as weak symbols in crc.cc so crc_memcpy_test.cc can override them to +// verify non-temporal store fencing. In optimized builds (NDEBUG), they must be +// defined inline here so the compiler eliminates the call within the same +// translation unit without needing LTO; otherwise, an external call following a +// non-temporal store causes the compiler's x86-fence-nontemporal-stores pass to +// insert an sfence after every store. +#ifndef NDEBUG void DebugReportNonTemporalStore(); void DebugReportStoreFence(); +#else +inline void DebugReportNonTemporalStore() {} +inline void DebugReportStoreFence() {} +#endif } // namespace crc_internal ABSL_NAMESPACE_END
diff --git a/absl/crc/internal/crc_memcpy_x86_arm_combined.cc b/absl/crc/internal/crc_memcpy_x86_arm_combined.cc index dac0446..f2fdb4b 100644 --- a/absl/crc/internal/crc_memcpy_x86_arm_combined.cc +++ b/absl/crc/internal/crc_memcpy_x86_arm_combined.cc
@@ -423,6 +423,7 @@ case CpuType::kArmNeoverseV1: case CpuType::kArmNeoverseV2: case CpuType::kNvidiaGrace: + case CpuType::kNvidiaVera: return { /*.temporal=*/new AcceleratedCrcMemcpyEngine<3, 0>(), /*.non_temporal=*/new CrcNonTemporalMemcpyEngine(),
diff --git a/absl/crc/internal/crc_x86_arm_combined.cc b/absl/crc/internal/crc_x86_arm_combined.cc index 0d1dfdc..5fe704f 100644 --- a/absl/crc/internal/crc_x86_arm_combined.cc +++ b/absl/crc/internal/crc_x86_arm_combined.cc
@@ -61,7 +61,7 @@ CRC32AcceleratedX86ARMCombined() {} ~CRC32AcceleratedX86ARMCombined() override {} void ExtendByZeroes(uint32_t* crc, size_t length) const override; - uint32_t ComputeZeroConstant(size_t length) const; + static uint32_t ComputeZeroConstant(size_t length); private: CRC32AcceleratedX86ARMCombined(const CRC32AcceleratedX86ARMCombined&) = @@ -164,8 +164,7 @@ // manually disable bounds checking. [[clang::no_sanitize("array-bounds")]] #endif -uint32_t CRC32AcceleratedX86ARMCombined::ComputeZeroConstant( - size_t length) const { +uint32_t CRC32AcceleratedX86ARMCombined::ComputeZeroConstant(size_t length) { length >>= kNumDroppedBits; int index = absl::countr_zero(length); @@ -277,7 +276,7 @@ // PCLMULQDQ Instruction" // https://www.intel.com/content/dam/www/public/us/en/documents/white-papers/fast-crc-computation-generic-polynomials-pclmulqdq-paper.pdf // We are applying it to CRC32C polynomial. - ABSL_ATTRIBUTE_ALWAYS_INLINE V128 Pclmul16Bytes(V128* partialCRC) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE static V128 Pclmul16Bytes(V128* partialCRC) { V128 loopMultiplicands = V128_Load(reinterpret_cast<const V128*>(kFoldAcross512Bits)); V128 tmp = V128_PMulHi(*partialCRC, loopMultiplicands); @@ -287,8 +286,8 @@ #if defined(ABSL_CRC_INTERNAL_HAVE_ARM_SIMD) template <bool kUseEor3 = false> - ABSL_ATTRIBUTE_ALWAYS_INLINE void Xor16BytesNeonPclmul( - V128 data, V128 tmp, V128* partialCRC) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE static void Xor16BytesNeonPclmul( + V128 data, V128 tmp, V128* partialCRC) { *partialCRC = V128_Xor3<kUseEor3>(tmp, *partialCRC, data); } @@ -296,8 +295,8 @@ // into a single value, that represents crc checksum of all the processed // bytes. template <bool kUseEor3 = false> - ABSL_ATTRIBUTE_ALWAYS_INLINE uint64_t - FinalizeNeonPclmulStream(V128* partialCRC) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t FinalizeNeonPclmulStream( + V128* partialCRC) { V128 partialCRC1 = partialCRC[0]; V128 partialCRC2 = partialCRC[1]; V128 partialCRC3 = partialCRC[2]; @@ -331,21 +330,22 @@ return crc; } - ABSL_ATTRIBUTE_ALWAYS_INLINE void Xor16BytesPclmul(V128, V128, V128*) const {} + ABSL_ATTRIBUTE_ALWAYS_INLINE static void Xor16BytesPclmul(V128, V128, + V128*) {} - ABSL_ATTRIBUTE_ALWAYS_INLINE uint64_t FinalizePclmulStream(V128*) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t FinalizePclmulStream(V128*) { return 0; } #else - ABSL_ATTRIBUTE_ALWAYS_INLINE void Xor16BytesPclmul(V128 data, V128 tmp, - V128* partialCRC) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE static void Xor16BytesPclmul( + V128 data, V128 tmp, V128* partialCRC) { *partialCRC = V128_Xor(V128_Xor(tmp, *partialCRC), data); } // Reduce partialCRC produced by Pclmul16Bytes and Xor16BytesPclmul into a // single value, that represents crc checksum of all the processed bytes. - ABSL_ATTRIBUTE_ALWAYS_INLINE uint64_t - FinalizePclmulStream(V128* partialCRC) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t FinalizePclmulStream( + V128* partialCRC) { V128 partialCRC1 = partialCRC[0]; V128 partialCRC2 = partialCRC[1]; V128 partialCRC3 = partialCRC[2]; @@ -383,26 +383,26 @@ } template <bool kUseEor3 = false> - ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE void - Xor16BytesNeonPclmul(V128, V128, V128*) const {} + ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE static void + Xor16BytesNeonPclmul(V128, V128, V128*) {} template <bool kUseEor3 = false> - ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE uint64_t - FinalizeNeonPclmulStream(V128*) const { + ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t + FinalizeNeonPclmulStream(V128*) { return 0; } #endif // Update crc with 8 bytes of data from p. - ABSL_ATTRIBUTE_ALWAYS_INLINE uint64_t Process8BytesCRC(const uint8_t* p, - uint64_t crc) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t Process8BytesCRC( + const uint8_t* p, uint64_t crc) { return CRC32_u64(static_cast<uint32_t>(crc), absl::little_endian::Load64(p)); } // Update crc with 16 bytes of data from p. - ABSL_ATTRIBUTE_ALWAYS_INLINE uint64_t Process16BytesCRC(const uint8_t* p, - uint64_t crc) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t Process16BytesCRC( + const uint8_t* p, uint64_t crc) { crc = Process8BytesCRC(p, crc); crc = Process8BytesCRC(p + 8, crc); return crc; @@ -418,8 +418,8 @@ // with new and default flags or use inline asm. // The code below is the same as FinalizePclmulStream, but with // PCLMUL and XOR operating on 2 values in a vector at the same time. - ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE uint64_t - FinalizeVpclmulStream(V256* partialCRC) const { + ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t + FinalizeVpclmulStream(V256* partialCRC) { uint64_t crc = 0; uint64_t low64, high64; __asm__( @@ -449,8 +449,8 @@ return crc; } - ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE V256 - Pclmul32BytesVpclmul(V256* partialCRC) const { + ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE static V256 + Pclmul32BytesVpclmul(V256* partialCRC) { V256 loopMultiplicands = V256_Broadcast128(reinterpret_cast<const V128*>(kFoldAcross512Bits)); V256 tmp; @@ -462,8 +462,8 @@ return tmp; } - ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE void - Xor32BytesVpclmul(const uint8_t* p, V256 tmp, V256* partialCRC) const { + ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE static void + Xor32BytesVpclmul(const uint8_t* p, V256 tmp, V256* partialCRC) { V256 v = V256_LoadU(p); __asm__ volatile( "vpxor %2, %0, %0 \n" @@ -473,16 +473,16 @@ } #else template <typename T = V256> - ABSL_ATTRIBUTE_ALWAYS_INLINE T Pclmul32BytesVpclmul(T*) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE static T Pclmul32BytesVpclmul(T*) { static_assert(sizeof(T) == 0, "Vector PCLMUL not supported"); return T{}; } template <typename T = V256> - ABSL_ATTRIBUTE_ALWAYS_INLINE void Xor32BytesVpclmul(const uint8_t*, T, - T*) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE static void Xor32BytesVpclmul(const uint8_t*, T, + T*) { static_assert(sizeof(T) == 0, "Vector PCLMUL not supported"); } - ABSL_ATTRIBUTE_ALWAYS_INLINE uint64_t FinalizeVpclmulStream(V256*) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t FinalizeVpclmulStream(V256*) { return 0; } #endif // defined(ABSL_CRC_INTERNAL_HAVE_X86_SIMD) && (defined(__AVX__) || @@ -515,8 +515,6 @@ // instruction, and up to kMaxStreams blocks computed with PCLMULQDQ, which // are combined in the end. static constexpr size_t kMaxStreams = 3; - // When copying, at most kMaxCopyStreams streams are used in total. - static constexpr size_t kMaxCopyStreams = 2; // On AArch64, full-cache-line stores engage hardware write-streaming, and // software destination prefetches force unnecessary DRAM reads. #if defined(__aarch64__) @@ -532,16 +530,28 @@ class CRC32AcceleratedX86ARMCombinedMultipleStreams : public CRC32AcceleratedX86ARMCombinedMultipleStreamsBase { public: - void Extend(uint32_t* crc, const void* bytes, - const size_t length) const override { + ABSL_ATTRIBUTE_HOT void Extend(uint32_t* crc, const void* bytes, + const size_t length) const override { Extend<CopyType::kNone>(crc, bytes, length); } - void ExtendAndCopy(uint32_t* crc, void* __restrict dst, - const void* __restrict src, size_t length, - bool non_temporal) const override { + ABSL_ATTRIBUTE_HOT void ExtendAndCopy(uint32_t* crc, void* __restrict dst, + const void* __restrict src, + size_t length, + bool non_temporal) const override { if (non_temporal) { - Extend<CopyType::kNonTemporal>(crc, src, length, dst); + if constexpr (pclmul_stream_type == PclmulStreamType::VPCLMUL) { + // On x86, VPCLMUL uses inline assembly, which causes LLVM's + // X86FenceNonTemporalStoresPass to insert an `sfence` before every + // inline assembly block in functions containing non-temporal stores, so + // non-temporal copies fall back to 128-bit PCLMUL intrinsics. + CRC32AcceleratedX86ARMCombinedMultipleStreams< + num_crc_streams, num_pclmul_streams, + PclmulStreamType::PCLMUL>::template Extend<CopyType::kNonTemporal>( + crc, src, length, dst); + } else { + Extend<CopyType::kNonTemporal>(crc, src, length, dst); + } } else { Extend<CopyType::kTemporal>(crc, src, length, dst); } @@ -551,9 +561,9 @@ // `ExtendCrc32cInline()` in `absl::ExtendCrc32c()` and // `CrcMemcpy::CrcAndCopy()`. template <CopyType copy_type> - ABSL_ATTRIBUTE_HOT void Extend(uint32_t* crc, const void* bytes, - const size_t length, - void* __restrict dst = nullptr) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE static void Extend( + uint32_t* crc, const void* bytes, const size_t length, + void* __restrict dst = nullptr) { assert(length >= kSmallCutoff); if constexpr (pclmul_stream_type != PclmulStreamType::NONE) { if (length >= kMediumCutoff) { @@ -565,9 +575,9 @@ } template <bool copy> - ABSL_ATTRIBUTE_HOT void ExtendWithoutPclmul( + ABSL_ATTRIBUTE_HOT static void ExtendWithoutPclmul( uint32_t* crc, const void* bytes, const size_t length, - void* __restrict dst = nullptr) const { + void* __restrict dst = nullptr) { static_assert(num_crc_streams >= 1 && num_crc_streams <= kMaxStreams, "Invalid number of crc streams"); static_assert(num_pclmul_streams >= 0 && num_pclmul_streams <= kMaxStreams, @@ -664,10 +674,17 @@ *crc = l; } + // Always inline when the translation unit already supports AVX (or does not + // force AVX via `gnu::target`), so shared specializations like + // `<3, 3, PCLMUL>` stay inlined into `ExtendAndCopy`. template <CopyType copy_type> - ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_HOT void ExtendWithPclmul( - uint32_t* crc, const void* bytes, const size_t length, - void* __restrict dst = nullptr) const { +#if defined(__AVX__) || !defined(ABSL_INTERNAL_CAN_FORCE_AVX) + ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE static void +#else + ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_HOT static void +#endif + ExtendWithPclmul(uint32_t* crc, const void* bytes, const size_t length, + void* __restrict dst = nullptr) { static_assert(num_crc_streams >= 1 && num_crc_streams <= kMaxStreams, "Invalid number of crc streams"); static_assert(num_pclmul_streams >= 0 && num_pclmul_streams <= kMaxStreams, @@ -965,24 +982,22 @@ }; // Returns the number of crc and pclmul streams to use. Copying adds loads and - // stores, so fewer streams are needed to saturate the dispatch width. In copy - // mode, at most kMaxCopyStreams of the configured streams are used, taken in - // the order: pclmul 1, crc 1, pclmul 2, crc 2, pclmul 3, crc 3. + // stores, so fewer streams are needed to saturate the dispatch width. static constexpr StreamCounts GetStreamCounts(CopyType copy_type) { - if (copy_type == CopyType::kNone) { + if (copy_type == CopyType::kNone || num_pclmul_streams == 0) { return {num_crc_streams, num_pclmul_streams}; } - StreamCounts counts = {0, 0}; - for (size_t i = 0; i < kMaxStreams; ++i) { - if (i < num_pclmul_streams && - counts.crc + counts.pclmul < kMaxCopyStreams) { - counts.pclmul++; - } - if (i < num_crc_streams && counts.crc + counts.pclmul < kMaxCopyStreams) { - counts.crc++; - } + // A single 256-bit VPCLMUL stream keeps up with temporal copies on its own. + if (pclmul_stream_type == PclmulStreamType::VPCLMUL && + copy_type == CopyType::kTemporal) { + return {0, 1}; } - return counts; + // Non-temporal copies benefit from a second crc stream, notably on AMD + // Zen 2-4. + if (copy_type == CopyType::kNonTemporal && num_crc_streams >= 2) { + return {2, 1}; + } + return {1, 1}; } // Whether PCLMUL streams are folded with 256-bit `vpclmulqdq`. @@ -996,8 +1011,8 @@ using PclmulProduct = std::conditional_t<kIsVpclmul && kVpclmulBytes == 32, V256, V128>; - ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE void - InitPclmulStream(V256 v0, V256 v1, V128* partialCRC) const { + ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE static void + InitPclmulStream(V256 v0, V256 v1, V128* partialCRC) { if constexpr (pclmul_stream_type == PclmulStreamType::NONE) { return; } else if constexpr (kIsVpclmul) { @@ -1018,9 +1033,9 @@ // storing the low product in `partialCRC` and returning the high product, // which must be passed to `XorPclmulStream` to complete the fold. template <size_t kVpclmulBytes> - ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE - PclmulProduct<kVpclmulBytes> - PclmulStream(V128* partialCRC) const { + ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE static PclmulProduct< + kVpclmulBytes> + PclmulStream(V128* partialCRC) { if constexpr (pclmul_stream_type == PclmulStreamType::NONE || (kIsVpclmul && kVpclmulBytes == 0)) { return {}; @@ -1035,9 +1050,9 @@ // the high product returned by `PclmulStream`, the low product in // `partialCRC`, and the loaded data, and advances `*stream`. template <size_t kVpclmulBytes> - ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE void XorPclmulStream( - const uint8_t** stream, const PclmulProduct<kVpclmulBytes>& high, - V128* partialCRC) const { + ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE static void + XorPclmulStream(const uint8_t** stream, + const PclmulProduct<kVpclmulBytes>& high, V128* partialCRC) { if constexpr (pclmul_stream_type == PclmulStreamType::NONE || (kIsVpclmul && kVpclmulBytes == 0)) { return; @@ -1081,10 +1096,10 @@ // always folded. template <size_t kNumActiveCrcStreams, size_t kNumActivePclmulStreams, size_t kVpclmulBytes> - ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE void + ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE static void ProcessAllStreams16(const uint8_t** crc_streams, uint64_t* l64_crc, const uint8_t** pclmul_streams, V128 (*partialCRC)[4], - size_t lane) const { + size_t lane) { for (size_t j = 0; j < kMaxStreams; ++j) { if (j < kNumActiveCrcStreams) { l64_crc[j] = Process8BytesCRC(crc_streams[j], l64_crc[j]); @@ -1105,8 +1120,8 @@ } } - ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE uint64_t - FinalizePclmulStream(V128* partialCRC) const { + ABSL_INTERNAL_ATTRIBUTE_AVX ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t + FinalizePclmulStream(V128* partialCRC) { if constexpr (pclmul_stream_type == PclmulStreamType::NONE) { return 0; } else if constexpr (kIsVpclmul) { @@ -1195,6 +1210,7 @@ case CpuType::kArmNeoverseN3: case CpuType::kArmNeoverseN4: case CpuType::kNvidiaGrace: + case CpuType::kNvidiaVera: return new CRC32AcceleratedX86ARMCombinedMultipleStreams< 1, 1, PclmulStreamType::NEON_PCLMUL_EOR3>(); case CpuType::kAmpereSiryn:
diff --git a/absl/debugging/internal/vdso_support.cc b/absl/debugging/internal/vdso_support.cc index 48d4f50..6bc679d 100644 --- a/absl/debugging/internal/vdso_support.cc +++ b/absl/debugging/internal/vdso_support.cc
@@ -194,8 +194,8 @@ // GoogleOnceInit() and ::operator new. // The destination in VDSO is unknown to CFI and VDSO does not set MSAN // shadow for the return value. -ABSL_ATTRIBUTE_NO_SANITIZE_CFI ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY +ABSL_ATTRIBUTE_NO_SANITIZE_CFI int GetCPU() { unsigned cpu; long ret_code = // NOLINT(runtime/int)
diff --git a/absl/debugging/stacktrace_test.cc b/absl/debugging/stacktrace_test.cc index 3cdd999..02950bc 100644 --- a/absl/debugging/stacktrace_test.cc +++ b/absl/debugging/stacktrace_test.cc
@@ -339,13 +339,13 @@ ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); } -ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS void RaiseSignal() { +ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS ABSL_ATTRIBUTE_NOINLINE void RaiseSignal() { g_return_address = __builtin_return_address(0); raise(SIGUSR1); ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); } -ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS void +ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS ABSL_ATTRIBUTE_NOINLINE void TestNestedSignal() { constexpr size_t kAltstackSize = 1 << 14; // Allocate altstack on regular stack to make sure it'll have a higher
diff --git a/absl/debugging/symbolize_test.cc b/absl/debugging/symbolize_test.cc index 9ee0abd..87cdf6e 100644 --- a/absl/debugging/symbolize_test.cc +++ b/absl/debugging/symbolize_test.cc
@@ -97,17 +97,17 @@ // Create functions that will remain in different text sections in the // final binary when linker option "-z,keep-text-section-prefix" is used. -int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.unlikely) unlikely_func() { +ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.unlikely) int unlikely_func() { return 0; } -int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.hot) hot_func() { return 0; } +ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.hot) int hot_func() { return 0; } -int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.startup) startup_func() { return 0; } +ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.startup) int startup_func() { return 0; } -int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.exit) exit_func() { return 0; } +ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.exit) int exit_func() { return 0; } -int /*ABSL_ATTRIBUTE_SECTION_VARIABLE(.text)*/ regular_func() { return 0; } +/*ABSL_ATTRIBUTE_SECTION_VARIABLE(.text)*/ int regular_func() { return 0; } // Thread-local data may confuse the symbolizer, ensure that it does not. // Variable sizes and order are important. @@ -125,8 +125,8 @@ // Force the binary to be large enough that a THP .text remap will succeed. static constexpr size_t kHpageSize = 1 << 21; -const char kHpageTextPadding[kHpageSize * 4] ABSL_ATTRIBUTE_SECTION_VARIABLE( - .text) = ""; +ABSL_ATTRIBUTE_SECTION_VARIABLE(.text) +const char kHpageTextPadding[kHpageSize * 4] = ""; #endif // !defined(__EMSCRIPTEN__) @@ -297,8 +297,8 @@ const size_t kPageSize = 64 << 10; // We place a read-only symbols into the .text section and verify that we can // symbolize them and other symbols after remapping them. -const char kPadding0[kPageSize * 4] ABSL_ATTRIBUTE_SECTION_VARIABLE(.text) = ""; -const char kPadding1[kPageSize * 4] ABSL_ATTRIBUTE_SECTION_VARIABLE(.text) = ""; +ABSL_ATTRIBUTE_SECTION_VARIABLE(.text) const char kPadding0[kPageSize * 4] = ""; +ABSL_ATTRIBUTE_SECTION_VARIABLE(.text) const char kPadding1[kPageSize * 4] = ""; static int FilterElfHeader(struct dl_phdr_info *info, size_t size, void *data) { for (int i = 0; i < info->dlpi_phnum; i++) {
diff --git a/absl/flags/BUILD.bazel b/absl/flags/BUILD.bazel index 59771c7..4dbf975 100644 --- a/absl/flags/BUILD.bazel +++ b/absl/flags/BUILD.bazel
@@ -118,7 +118,6 @@ "//absl/base:log_severity", "//absl/numeric:int128", "//absl/strings", - "//absl/strings:str_format", "//absl/strings:string_view", "//absl/types:optional", ], @@ -240,6 +239,7 @@ "//absl/base:dynamic_annotations", "//absl/base:fast_type_id", "//absl/base:no_destructor", + "//absl/container:flat_hash_map", "//absl/memory", "//absl/meta:type_traits", "//absl/strings",
diff --git a/absl/flags/CMakeLists.txt b/absl/flags/CMakeLists.txt index 162b654..57dcc50 100644 --- a/absl/flags/CMakeLists.txt +++ b/absl/flags/CMakeLists.txt
@@ -92,7 +92,6 @@ absl::int128 absl::log_severity absl::optional - absl::str_format absl::string_view absl::strings ) @@ -201,6 +200,7 @@ absl::flags_commandlineflag_internal absl::flags_config absl::flags_marshalling + absl::flat_hash_map absl::meta absl::no_destructor absl::synchronization
diff --git a/absl/flags/commandlineflag_test.cc b/absl/flags/commandlineflag_test.cc index b6d01b2..35ce567 100644 --- a/absl/flags/commandlineflag_test.cc +++ b/absl/flags/commandlineflag_test.cc
@@ -16,7 +16,9 @@ #include "absl/flags/commandlineflag.h" #include <memory> +#include <optional> #include <string> +#include <vector> #include "gtest/gtest.h" #include "absl/flags/config.h" @@ -38,6 +40,21 @@ ABSL_FLAG(int, int_flag2, 201, ""); ABSL_FLAG(std::string, string_flag2, "dflt", ""); +using CustomIntAlias = int; +using CustomStringListAlias = std::vector<std::string>; + +struct CustomFlagUDT {}; +bool AbslParseFlag(absl::string_view, CustomFlagUDT*, std::string*) { + return true; +} +std::string AbslUnparseFlag(const CustomFlagUDT&) { return ""; } + +ABSL_FLAG(CustomIntAlias, int_alias_flag, 7, ""); +ABSL_FLAG(CustomStringListAlias, string_list_alias_flag, {}, ""); +ABSL_FLAG(std::vector<std::string>, string_vec_flag, {}, ""); +ABSL_FLAG(std::optional<int>, optional_int_flag, std::nullopt, ""); +ABSL_FLAG(CustomFlagUDT, custom_udt_flag, {}, ""); + namespace { namespace flags = absl::flags_internal; @@ -233,4 +250,67 @@ // EXPECT_EQ(err, "ERROR: int_flag is already set to 201"); } +void MakeEmptyString(void* dst) { new (dst) std::string(); } + +constexpr flags::FlagHelpArg kCompatHelpArg{flags::FlagHelpMsg("help"), + flags::FlagHelpKind::kLiteral}; +constexpr flags::FlagDefaultArg kCompatStringDefaultArg{ + flags::FlagDefaultSrc(&MakeEmptyString), flags::FlagDefaultKind::kGenFunc}; +constexpr absl::Flag<std::string> kCompat4ArgFlag{"compat4", "file", + kCompatHelpArg, + kCompatStringDefaultArg}; +constexpr absl::Flag<std::string> kCompat5ArgCommonFlag{ + "compat5_common", "std::string", "file", kCompatHelpArg, + kCompatStringDefaultArg}; +constexpr absl::Flag<std::string> kCompat5ArgCustomFlag{ + "compat5_custom", "UnlistedStringAlias", "file", kCompatHelpArg, + kCompatStringDefaultArg}; + +TEST_F(CommandLineFlagTest, TestTypeName) { + EXPECT_EQ(flags::PrivateHandleAccessor::TypeName( + *absl::FindCommandLineFlag("int_flag")), + "int"); + EXPECT_EQ(flags::PrivateHandleAccessor::TypeName( + *absl::FindCommandLineFlag("string_flag")), + "std::string"); + EXPECT_EQ(flags::PrivateHandleAccessor::TypeName( + *absl::FindCommandLineFlag("string_vec_flag")), + "std::vector<std::string>"); + EXPECT_EQ(flags::PrivateHandleAccessor::TypeName( + *absl::FindCommandLineFlag("optional_int_flag")), + "std::optional<int>"); + EXPECT_EQ(flags::PrivateHandleAccessor::TypeName( + *absl::FindCommandLineFlag("int_alias_flag")), + "CustomIntAlias"); + EXPECT_EQ(flags::PrivateHandleAccessor::TypeName( + *absl::FindCommandLineFlag("string_list_alias_flag")), + "CustomStringListAlias"); + EXPECT_EQ(flags::PrivateHandleAccessor::TypeName( + *absl::FindCommandLineFlag("custom_udt_flag")), + "CustomFlagUDT"); + + EXPECT_EQ(flags::PrivateHandleAccessor::TypeName( + absl::GetFlagReflectionHandle(kCompat4ArgFlag)), + ""); + EXPECT_EQ(flags::PrivateHandleAccessor::TypeName( + absl::GetFlagReflectionHandle(kCompat5ArgCommonFlag)), + "std::string"); + EXPECT_EQ(flags::PrivateHandleAccessor::TypeName( + absl::GetFlagReflectionHandle(kCompat5ArgCustomFlag)), + ""); +} + +TEST(CommandLineFlagStrippedTest, TestStrippedTypeName) { +#if ABSL_FLAGS_STRIP_NAMES + EXPECT_EQ(absl::GetFlagReflectionHandle(FLAGS_int_flag).Name(), ""); + EXPECT_EQ(flags::PrivateHandleAccessor::TypeName( + absl::GetFlagReflectionHandle(FLAGS_int_flag)), + ""); + EXPECT_EQ(absl::GetFlagReflectionHandle(FLAGS_custom_udt_flag).Name(), ""); + EXPECT_EQ(flags::PrivateHandleAccessor::TypeName( + absl::GetFlagReflectionHandle(FLAGS_custom_udt_flag)), + ""); +#endif +} + } // namespace
diff --git a/absl/flags/flag.h b/absl/flags/flag.h index 2e9a9e6..7c789f8 100644 --- a/absl/flags/flag.h +++ b/absl/flags/flag.h
@@ -207,6 +207,9 @@ #define ABSL_FLAG_IMPL_FLAGNAME(txt) "" #define ABSL_FLAG_IMPL_TYPENAME(txt) "" #define ABSL_FLAG_IMPL_FILENAME() "" +#define ABSL_FLAG_IMPL_NAME_ARG(name) \ + absl::flags_internal::FlagNameArg{"", absl::flags_internal::kEmptyFlagTypeId} +#define ABSL_FLAG_IMPL_DECLARE_NAME_METHODS(name, Type) #define ABSL_FLAG_IMPL_REGISTRAR(T, flag) \ absl::flags_internal::FlagRegistrar<T, false>(ABSL_FLAG_IMPL_FLAG_PTR(flag), \ nullptr) @@ -214,6 +217,18 @@ #define ABSL_FLAG_IMPL_FLAGNAME(txt) txt #define ABSL_FLAG_IMPL_TYPENAME(txt) txt #define ABSL_FLAG_IMPL_FILENAME() __FILE__ +#define ABSL_FLAG_IMPL_NAME_ARG(name) \ + absl::flags_internal::MakeFlagNameArg<AbslFlagDefaultGenFor##name>() +#define ABSL_FLAG_IMPL_DECLARE_NAME_METHODS(name, Type) \ + static constexpr const char* AbslFlagName() { \ + return #name; \ + } \ + static constexpr absl::string_view AbslFlagTypeName() { \ + return absl::string_view(#Type, sizeof(#Type) - 1); \ + } \ + static constexpr const char* AbslFlagPackedNameAndType() { \ + return #name "\0" #Type; \ + } #define ABSL_FLAG_IMPL_REGISTRAR(T, flag) \ absl::flags_internal::FlagRegistrar<T, true>(ABSL_FLAG_IMPL_FLAG_PTR(flag), \ __FILE__) @@ -235,22 +250,21 @@ // TODO(rogeeff): place these generated structs into local namespace and apply // ABSL_INTERNAL_UNIQUE_SHORT_NAME. // TODO(rogeeff): Apply __attribute__((nodebug)) to FLAGS_help_storage_##name -#define ABSL_FLAG_IMPL_DECLARE_HELP_WRAPPER(name, txt) \ - struct AbslFlagHelpGenFor##name { \ - /* The expression is run in the caller as part of the */ \ - /* default value argument. That keeps temporaries alive */ \ - /* long enough for NonConst to work correctly. */ \ - static constexpr absl::string_view Value( \ - absl::string_view absl_flag_help ABSL_ATTRIBUTE_LIFETIME_BOUND = \ - ABSL_FLAG_IMPL_FLAGHELP(txt)) { \ - return absl_flag_help; \ - } \ - static std::string NonConst() { return std::string(Value()); } \ - }; \ - constexpr auto FLAGS_help_storage_##name ABSL_INTERNAL_UNIQUE_SMALL_NAME() \ - ABSL_ATTRIBUTE_SECTION_VARIABLE(flags_help_cold) = \ - absl::flags_internal::HelpStringAsArray<AbslFlagHelpGenFor##name>( \ - 0); +#define ABSL_FLAG_IMPL_DECLARE_HELP_WRAPPER(name, txt) \ + struct AbslFlagHelpGenFor##name { \ + /* The expression is run in the caller as part of the */ \ + /* default value argument. That keeps temporaries alive */ \ + /* long enough for NonConst to work correctly. */ \ + static constexpr absl::string_view Value( \ + absl::string_view absl_flag_help ABSL_ATTRIBUTE_LIFETIME_BOUND = \ + ABSL_FLAG_IMPL_FLAGHELP(txt)) { \ + return absl_flag_help; \ + } \ + static std::string NonConst() { return std::string(Value()); } \ + }; \ + ABSL_ATTRIBUTE_SECTION_VARIABLE(flags_help_cold) \ + constexpr auto FLAGS_help_storage_##name ABSL_INTERNAL_UNIQUE_SMALL_NAME() = \ + absl::flags_internal::HelpStringAsArray<AbslFlagHelpGenFor##name>(0); #define ABSL_FLAG_IMPL_DECLARE_DEF_VAL_WRAPPER(name, Type, default_value) \ struct AbslFlagDefaultGenFor##name { \ @@ -258,6 +272,7 @@ static void Gen(void* absl_flag_default_loc) { \ new (absl_flag_default_loc) Type(AbslFlagDefaultGenFor##name{}.value); \ } \ + ABSL_FLAG_IMPL_DECLARE_NAME_METHODS(name, Type) \ }; // ABSL_FLAG_IMPL @@ -265,17 +280,16 @@ // Note: Name of registrar object is not arbitrary. It is used to "grab" // global name for FLAGS_no<flag_name> symbol, thus preventing the possibility // of defining two flags with names foo and nofoo. -#define ABSL_FLAG_IMPL(Type, name, default_value, help) \ - extern ::absl::Flag<Type> FLAGS_##name; \ - namespace absl /* block flags in namespaces */ {} \ - ABSL_FLAG_IMPL_DECLARE_DEF_VAL_WRAPPER(name, Type, default_value) \ - ABSL_FLAG_IMPL_DECLARE_HELP_WRAPPER(name, help) \ - ABSL_CONST_INIT absl::Flag<Type> FLAGS_##name{ \ - ABSL_FLAG_IMPL_FLAGNAME(#name), ABSL_FLAG_IMPL_TYPENAME(#Type), \ - ABSL_FLAG_IMPL_FILENAME(), ABSL_FLAG_IMPL_HELP_ARG(name), \ - ABSL_FLAG_IMPL_DEFAULT_ARG(Type, name)}; \ - extern absl::flags_internal::FlagRegistrarEmpty FLAGS_no##name; \ - absl::flags_internal::FlagRegistrarEmpty FLAGS_no##name = \ +#define ABSL_FLAG_IMPL(Type, name, default_value, help) \ + extern ::absl::Flag<Type> FLAGS_##name; \ + namespace absl /* block flags in namespaces */ {} \ + ABSL_FLAG_IMPL_DECLARE_DEF_VAL_WRAPPER(name, Type, default_value) \ + ABSL_FLAG_IMPL_DECLARE_HELP_WRAPPER(name, help) \ + ABSL_CONST_INIT absl::Flag<Type> FLAGS_##name{ \ + ABSL_FLAG_IMPL_NAME_ARG(name), ABSL_FLAG_IMPL_HELP_ARG(name), \ + ABSL_FLAG_IMPL_DEFAULT_ARG(Type, name)}; \ + extern absl::flags_internal::FlagRegistrarEmpty FLAGS_no##name; \ + absl::flags_internal::FlagRegistrarEmpty FLAGS_no##name = \ ABSL_FLAG_IMPL_REGISTRAR(Type, FLAGS_##name) // ABSL_RETIRED_FLAG
diff --git a/absl/flags/flag_test.cc b/absl/flags/flag_test.cc index 5cacf64..199577e 100644 --- a/absl/flags/flag_test.cc +++ b/absl/flags/flag_test.cc
@@ -137,6 +137,17 @@ flags::FlagValueStorageKind::kSequenceLocked); EXPECT_EQ(flags::StorageKind<absl::uint128>(), flags::FlagValueStorageKind::kSequenceLocked); + + // These sizes are not hard limits, but we want to keep per-flag size as + // small as possible because production binaries may define thousands of + // flags. + if (sizeof(void*) == 8) { + EXPECT_EQ(sizeof(flags::FlagImpl), 56); + EXPECT_EQ(sizeof(absl::Flag<bool>), 64); + EXPECT_EQ(sizeof(absl::Flag<int>), 64); + EXPECT_EQ(sizeof(absl::Flag<int64_t>), 64); + EXPECT_EQ(sizeof(absl::Flag<double>), 64); + } } // -------------------------------------------------------------------- @@ -148,17 +159,16 @@ using int128 = absl::int128; using uint128 = absl::uint128; -#define DEFINE_CONSTRUCTED_FLAG(T, dflt, dflt_kind) \ - constexpr flags::FlagDefaultArg f1default##T{ \ - flags::FlagDefaultSrc{dflt}, flags::FlagDefaultKind::dflt_kind}; \ - constexpr absl::Flag<T> f1##T{"f1", #T, "file", help_arg, f1default##T}; \ - ABSL_CONST_INIT absl::Flag<T> f2##T { \ - "f2", #T, "file", \ - {flags::FlagHelpMsg(&TestHelpMsg), flags::FlagHelpKind::kGenFunc}, \ - flags::FlagDefaultArg { \ - flags::FlagDefaultSrc(&TestMakeDflt<T>), \ - flags::FlagDefaultKind::kGenFunc \ - } \ +#define DEFINE_CONSTRUCTED_FLAG(T, dflt, dflt_kind) \ + constexpr flags::FlagDefaultArg f1default##T{ \ + flags::FlagDefaultSrc{dflt}, flags::FlagDefaultKind::dflt_kind}; \ + constexpr absl::Flag<T> f1##T{"f1", help_arg, f1default##T}; \ + ABSL_CONST_INIT absl::Flag<T> f2##T { \ + "f2", {flags::FlagHelpMsg(&TestHelpMsg), flags::FlagHelpKind::kGenFunc}, \ + flags::FlagDefaultArg { \ + flags::FlagDefaultSrc(&TestMakeDflt<T>), \ + flags::FlagDefaultKind::kGenFunc \ + } \ } DEFINE_CONSTRUCTED_FLAG(bool, true, kOneWord); @@ -175,13 +185,18 @@ DEFINE_CONSTRUCTED_FLAG(int128, 13, kGenFunc); DEFINE_CONSTRUCTED_FLAG(uint128, 14, kGenFunc); +constexpr absl::Flag<String> f_compat_5arg{ + "f_compat", "std::string", "file", help_arg, + flags::FlagDefaultArg{flags::FlagDefaultSrc(&TestMakeDflt<String>), + flags::FlagDefaultKind::kGenFunc}}; + template <typename T> bool TestConstructionFor(const absl::Flag<T>& f1, absl::Flag<T>& f2) { EXPECT_EQ(absl::GetFlagReflectionHandle(f1).Name(), "f1"); EXPECT_EQ(absl::GetFlagReflectionHandle(f1).Help(), "literal help"); - EXPECT_EQ(absl::GetFlagReflectionHandle(f1).Filename(), "file"); + EXPECT_EQ(absl::GetFlagReflectionHandle(f1).Filename(), ""); - flags::FlagRegistrar<T, false>(ABSL_FLAG_IMPL_FLAG_PTR(f2), nullptr) + flags::FlagRegistrar<T, false>(ABSL_FLAG_IMPL_FLAG_PTR(f2), "file") .OnUpdate(TestCallback); EXPECT_EQ(absl::GetFlagReflectionHandle(f2).Name(), "f2"); @@ -207,6 +222,10 @@ TEST_CONSTRUCTED_FLAG(UDT); TEST_CONSTRUCTED_FLAG(int128); TEST_CONSTRUCTED_FLAG(uint128); + EXPECT_EQ(absl::GetFlagReflectionHandle(f_compat_5arg).Name(), "f_compat"); + EXPECT_EQ(absl::GetFlagReflectionHandle(f_compat_5arg).Help(), + "literal help"); + EXPECT_EQ(absl::GetFlagReflectionHandle(f_compat_5arg).Filename(), ""); } // -------------------------------------------------------------------- @@ -1397,3 +1416,52 @@ #endif } // namespace + +ABSL_FLAG(int, concurrent_saver_test_flag, 0, + "test flag for concurrent FlagSaver"); + +namespace { + +TEST_F(FlagTest, ConcurrentFlagSaverAndSetFlag) { + std::atomic<bool> stop{false}; + std::thread writer([&stop]() { + int i = 1; + while (!stop.load(std::memory_order_relaxed)) { + absl::SetFlag(&FLAGS_concurrent_saver_test_flag, i++); + } + }); + // Run an arbitrary small number of FlagSaver save/restore cycles while the + // writer thread mutates the flag past the 7-update inline modification + // counter limit, checking under ThreadSanitizer that concurrent SaveState, + // RestoreState, and SetFlag calls do not race. Each FlagSaver snapshots + // every registered flag in the binary, so keep the cycle count small. + constexpr int kSaveRestoreCycles = 50; + for (int iter = 0; iter < kSaveRestoreCycles; ++iter) { + absl::FlagSaver saver; + (void)absl::GetFlag(FLAGS_concurrent_saver_test_flag); + } + stop.store(true, std::memory_order_relaxed); + writer.join(); + EXPECT_GE(absl::GetFlag(FLAGS_concurrent_saver_test_flag), 0); +} + +TEST_F(FlagTest, FilenameInterning) { + constexpr const char* kFileA = "dir/intern_test_a.cc"; + constexpr const char* kFileB = "dir/intern_test_b.cc"; + + absl::Flag<int32_t> f_a1{"fa1", help_arg, f1defaultint32_t}; + absl::Flag<int32_t> f_a2{"fa2", help_arg, f1defaultint32_t}; + absl::Flag<int32_t> f_b{"fb", help_arg, f1defaultint32_t}; + + flags::FlagRegistrar<int32_t, false>(ABSL_FLAG_IMPL_FLAG_PTR(f_a1), kFileA); + flags::FlagRegistrar<int32_t, false>(ABSL_FLAG_IMPL_FLAG_PTR(f_a2), kFileA); + flags::FlagRegistrar<int32_t, false>(ABSL_FLAG_IMPL_FLAG_PTR(f_b), kFileB); + // Duplicate registration preserves the first filename for ODR diagnostics. + flags::FlagRegistrar<int32_t, false>(ABSL_FLAG_IMPL_FLAG_PTR(f_a1), kFileB); + + EXPECT_EQ(f_a1.Filename(), "dir/intern_test_a.cc"); + EXPECT_EQ(f_a2.Filename(), "dir/intern_test_a.cc"); + EXPECT_EQ(f_b.Filename(), "dir/intern_test_b.cc"); +} + +} // namespace
diff --git a/absl/flags/internal/flag.cc b/absl/flags/internal/flag.cc index 662b342..4c70b7b 100644 --- a/absl/flags/internal/flag.cc +++ b/absl/flags/internal/flag.cc
@@ -23,6 +23,7 @@ #include <array> #include <atomic> #include <cstring> +#include <limits> #include <memory> #include <string> #include <typeinfo> @@ -39,6 +40,7 @@ #include "absl/base/no_destructor.h" #include "absl/base/optimization.h" #include "absl/base/thread_annotations.h" +#include "absl/container/flat_hash_map.h" #include "absl/flags/config.h" #include "absl/flags/internal/commandlineflag.h" #include "absl/flags/usage_config.h" @@ -104,6 +106,94 @@ s_freelist->push_back(p); } +// Uncommon per-flag data (callbacks and dynamic default overrides) is stored in +// side tables to keep FlagImpl small across the many flags in a binary. +// Logically, each map entry is an optional field of FlagImpl. +template <typename K, typename V> +class ThreadSafeMap { + public: + V Get(const K& key) { + absl::MutexLock l(mutex_); + auto it = map_.find(key); + return it != map_.end() ? it->second : V{}; + } + + V Set(const K& key, V new_val) { + absl::MutexLock l(mutex_); + return std::exchange(map_[key], new_val); + } + + template <typename Factory> + V GetOrCreate(const K& key, Factory factory) { + absl::MutexLock l(mutex_); + V& val = map_[key]; + if (val == V{}) { + val = factory(); + } + return val; + } + + void Increment(const K& key) { + absl::MutexLock l(mutex_); + ++map_[key]; + } + + private: + absl::Mutex mutex_; + absl::flat_hash_map<K, V> map_ ABSL_GUARDED_BY(mutex_); +}; + +FlagCallback* GetOrCreateCallback(const FlagImpl* flag) { + static absl::NoDestructor<ThreadSafeMap<const FlagImpl*, FlagCallback*>> + callbacks; + return callbacks->GetOrCreate(flag, [] { return new FlagCallback; }); +} + +ThreadSafeMap<const FlagImpl*, void*>& DynamicDefaults() { + static absl::NoDestructor<ThreadSafeMap<const FlagImpl*, void*>> + dynamic_defaults; + return *dynamic_defaults; +} + +void* GetDynamicDefault(const FlagImpl* flag) { + return DynamicDefaults().Get(flag); +} + +void* SetDynamicDefault(const FlagImpl* flag, void* new_val) { + return DynamicDefaults().Set(flag, new_val); +} + +ThreadSafeMap<const FlagImpl*, int64_t>& OverflowModCounts() { + static absl::NoDestructor<ThreadSafeMap<const FlagImpl*, int64_t>> + overflow_mod_counts; + return *overflow_mod_counts; +} + +int64_t GetOverflowModCount(const FlagImpl* flag) { + return OverflowModCounts().Get(flag); +} + +void IncrementOverflowModCount(const FlagImpl* flag) { + OverflowModCounts().Increment(flag); +} + +struct FilenameTable { + absl::Mutex mutex; + std::vector<const char*> files ABSL_GUARDED_BY(mutex); +}; + +FilenameTable& GlobalFilenames() { + static absl::NoDestructor<FilenameTable> filenames; + return *filenames; +} + +const char* GetFilenameById(uint16_t id) { + if (id == 0) return ""; + FilenameTable& table = GlobalFilenames(); + absl::MutexLock l(table.mutex); + return table.files[id - 1]; +} + } // namespace /////////////////////////////////////////////////////////////////////////////// @@ -210,10 +300,37 @@ return (reinterpret_cast<mask_t>(ptr_) & mask) != 0; } +void FlagImpl::SetFilename(const char* filename) { + // Keep the first registration's filename so FlagRegistry::RegisterFlag can + // report both files when dynamic symbol interposition merges duplicate flag + // definitions across shared libraries. + if (file_id_ != 0 || filename == nullptr) return; + FilenameTable& table = GlobalFilenames(); + absl::MutexLock l(table.mutex); + // Flags are typically defined in .cc files whose dynamic initializers run + // consecutively per translation unit, and compilers that pool string + // literals (such as Clang/GCC .rodata.str1.1 or MSVC /GF) share one + // __FILE__ literal address per file. Checking pointer equality against the + // last entry deduplicates that common case in O(1); if literals are not + // pooled or a translation unit spans multiple files, storing extra entries + // only uses an additional table slot without affecting correctness. + if (!table.files.empty() && table.files.back() == filename) { + file_id_ = static_cast<uint16_t>(table.files.size()); + return; + } + if (ABSL_PREDICT_FALSE(table.files.size() >= + std::numeric_limits<uint16_t>::max())) { + ABSL_INTERNAL_LOG(FATAL, "Too many flag filenames"); + } + table.files.push_back(filename); + file_id_ = static_cast<uint16_t>(table.files.size()); +} + void FlagImpl::Init() { new (&data_guard_) absl::Mutex; - auto def_kind = static_cast<FlagDefaultKind>(def_kind_); + FlagDefaultKind def_kind = + mu_state_.load(std::memory_order_relaxed).DefaultKind(); switch (ValueStorageKind()) { case FlagValueStorageKind::kValueAndInitBit: @@ -242,6 +359,7 @@ // during initialization. assert(def_kind == FlagDefaultKind::kGenFunc); (*default_value_.gen_func)(AtomicBufferValue()); + SeqLock().MarkInitialized(); break; } case FlagValueStorageKind::kHeapAllocated: @@ -256,7 +374,6 @@ std::memory_order_release); break; } - seq_lock_.MarkInitialized(); } absl::Mutex& FlagImpl::DataGuard() const { @@ -294,9 +411,9 @@ std::unique_ptr<void, DynValueDeleter> FlagImpl::MakeInitValue() const { void* res = nullptr; - switch (DefaultKind()) { + switch (mu_state_.load(std::memory_order_relaxed).DefaultKind()) { case FlagDefaultKind::kDynamicValue: - res = flags_internal::Clone(op_, default_value_.dynamic_value); + res = flags_internal::Clone(op_, GetDynamicDefault(this)); break; case FlagDefaultKind::kGenFunc: res = flags_internal::Alloc(op_); @@ -309,6 +426,17 @@ return {res, DynValueDeleter{op_}}; } +void FlagImpl::RecordMutation() { + MuState s = mu_state_.load(std::memory_order_relaxed); + if (s.mod_count < kMaxInlineModCount) { + ++s.mod_count; + } else { + IncrementOverflowModCount(this); + } + s.modified = true; + mu_state_.store(s, std::memory_order_relaxed); +} + void FlagImpl::StoreValue(const void* src, ValueSource source) { switch (ValueStorageKind()) { case FlagValueStorageKind::kValueAndInitBit: @@ -317,11 +445,10 @@ int64_t one_word_val = OneWordValue().load(std::memory_order_acquire); std::memcpy(&one_word_val, src, Sizeof(op_)); OneWordValue().store(one_word_val, std::memory_order_release); - seq_lock_.IncrementModificationCount(); break; } case FlagValueStorageKind::kSequenceLocked: { - seq_lock_.Write(AtomicBufferValue(), src, Sizeof(op_)); + SeqLock().Write(AtomicBufferValue(), src, Sizeof(op_)); break; } case FlagValueStorageKind::kHeapAllocated: @@ -345,19 +472,24 @@ } PtrStorage().store(ptr_value, std::memory_order_release); - seq_lock_.IncrementModificationCount(); break; } - modified_ = true; + RecordMutation(); InvokeCallback(); } absl::string_view FlagImpl::Name() const { return name_; } -absl::string_view FlagImpl::TypeName() const { return type_name_; } +absl::string_view FlagImpl::TypeName() const { + if (ABSL_PREDICT_TRUE(type_id_ != kCustomFlagTypeId)) { + return kCommonFlagTypeNames[type_id_]; + } + return name_ + std::strlen(name_) + 1; +} std::string FlagImpl::Filename() const { - return flags_internal::GetUsageConfig().normalize_filename(filename_); + return flags_internal::GetUsageConfig().normalize_filename( + GetFilenameById(file_id_)); } std::string FlagImpl::Help() const { @@ -370,12 +502,15 @@ } int64_t FlagImpl::ModificationCount() const { - return seq_lock_.ModificationCount(); + const uint8_t mod_count = mu_state_.load(std::memory_order_relaxed).mod_count; + if (ABSL_PREDICT_TRUE(mod_count < kMaxInlineModCount)) { + return mod_count; + } + return kMaxInlineModCount + GetOverflowModCount(this); } bool FlagImpl::IsSpecifiedOnCommandLine() const { - absl::MutexLock l(DataGuard()); - return on_command_line_; + return mu_state_.load(std::memory_order_relaxed).on_command_line; } std::string FlagImpl::DefaultValue() const { @@ -414,20 +549,22 @@ void FlagImpl::SetCallback(const FlagCallbackFunc mutation_callback) { absl::MutexLock l(DataGuard()); - if (callback_ == nullptr) { - callback_ = new FlagCallback; - } - callback_->func = mutation_callback; + FlagCallback* cb = GetOrCreateCallback(this); + cb->func = mutation_callback; + MuState s = mu_state_.load(std::memory_order_relaxed); + s.has_callback = true; + mu_state_.store(s, std::memory_order_relaxed); InvokeCallback(); } void FlagImpl::InvokeCallback() const { - if (!callback_) return; + if (!mu_state_.load(std::memory_order_relaxed).has_callback) return; + FlagCallback* cb_entry = GetOrCreateCallback(this); // Make a copy of the C-style function pointer that we are about to invoke // before we release the lock guarding it. - FlagCallbackFunc cb = callback_->func; + FlagCallbackFunc cb = cb_entry->func; // If the flag has a mutation callback this function invokes it. While the // callback is being invoked the primary flag's mutex is unlocked and it is @@ -441,30 +578,31 @@ // completed. Requires that *primary_lock be held in exclusive mode; it may be // released and reacquired by the implementation. MutexRelock relock(DataGuard()); - absl::MutexLock lock(callback_->guard); + absl::MutexLock lock(cb_entry->guard); cb(); } -// Returns true if an unmodified absl::Flag (i.e. `seq_lock_.IsUnmodified()`) -// can skip lazy initialization and state allocation in `SaveState()`, and -// instead reconstructs from the provided default value if modified before -// restoration. +// Returns true if an unmodified absl::Flag can skip lazy initialization and +// state allocation in `SaveState()`, and instead reconstructs from the +// provided default value if modified before restoration. bool FlagImpl::CanSkipInitOnSave() const { - if (!seq_lock_.IsUnmodified()) return false; + const MuState state = mu_state_.load(std::memory_order_relaxed); + if (state.mod_count != 0) return false; + const FlagDefaultKind def_kind = state.DefaultKind(); switch (ValueStorageKind()) { case FlagValueStorageKind::kValueAndInitBit: case FlagValueStorageKind::kOneWordAtomic: // Only `kOneWord` defaults are inlinable compile-time constants; other // kinds may have dynamic defaults or side effects. - return static_cast<FlagDefaultKind>(def_kind_) == - FlagDefaultKind::kOneWord; + return def_kind == FlagDefaultKind::kOneWord; case FlagValueStorageKind::kSequenceLocked: // Always uses a default-generator function when unmodified. - return true; + return def_kind == FlagDefaultKind::kGenFunc; case FlagValueStorageKind::kHeapAllocated: // Built-in types have side-effect-free defaults; user-defined types may // have custom construction or validation side effects. - return !ShouldValidateFlagValue(flags_internal::FastTypeId(op_)); + return def_kind == FlagDefaultKind::kGenFunc && + !ShouldValidateFlagValue(flags_internal::FastTypeId(op_)); } return false; } @@ -476,8 +614,9 @@ absl::MutexLock l(DataGuard()); - bool modified = modified_; - bool on_command_line = on_command_line_; + const MuState state = mu_state_.load(std::memory_order_relaxed); + bool modified = state.modified; + bool on_command_line = state.on_command_line; switch (ValueStorageKind()) { case FlagValueStorageKind::kValueAndInitBit: case FlagValueStorageKind::kOneWordAtomic: { @@ -489,7 +628,7 @@ void* cloned = flags_internal::Alloc(op_); // Read is guaranteed to be successful because we hold the lock. bool success = - seq_lock_.TryRead(cloned, AtomicBufferValue(), Sizeof(op_)); + SeqLock().TryRead(cloned, AtomicBufferValue(), Sizeof(op_)); assert(success); static_cast<void>(success); return std::make_unique<FlagState>(*this, cloned, modified, @@ -507,7 +646,7 @@ } bool FlagImpl::RestoreState(const FlagState& flag_state) { - if (ABSL_PREDICT_TRUE(flag_state.counter_ < 0 && seq_lock_.IsUnmodified())) { + if (ABSL_PREDICT_TRUE(flag_state.counter_ < 0 && IsUnmodifiedFast())) { return false; } @@ -538,8 +677,10 @@ break; } - modified_ = flag_state.modified_; - on_command_line_ = flag_state.on_command_line_; + MuState s = mu_state_.load(std::memory_order_relaxed); + s.modified = flag_state.modified_; + s.on_command_line = flag_state.on_command_line_; + mu_state_.store(s, std::memory_order_relaxed); return true; } @@ -558,6 +699,14 @@ return OffsetValue<std::atomic<uint64_t>>(); } +flags_internal::SequenceLock& FlagImpl::SeqLock() const { + assert(ValueStorageKind() == FlagValueStorageKind::kSequenceLocked); + size_t num_words = + flags_internal::AlignUp(Sizeof(op_), sizeof(uint64_t)) / sizeof(uint64_t); + return *reinterpret_cast<flags_internal::SequenceLock*>(AtomicBufferValue() + + num_words); +} + std::atomic<int64_t>& FlagImpl::OneWordValue() const { assert(ValueStorageKind() == FlagValueStorageKind::kOneWordAtomic || ValueStorageKind() == FlagValueStorageKind::kValueAndInitBit); @@ -638,13 +787,13 @@ void FlagImpl::ReadSequenceLockedData(void* dst) const { size_t size = Sizeof(op_); // Attempt to read using the sequence lock. - if (ABSL_PREDICT_TRUE(seq_lock_.TryRead(dst, AtomicBufferValue(), size))) { + if (ABSL_PREDICT_TRUE(SeqLock().TryRead(dst, AtomicBufferValue(), size))) { return; } // We failed due to contention. Acquire the lock to prevent contention // and try again. absl::ReaderMutexLock l(DataGuard()); - bool success = seq_lock_.TryRead(dst, AtomicBufferValue(), size); + bool success = SeqLock().TryRead(dst, AtomicBufferValue(), size); assert(success); static_cast<void>(success); } @@ -687,13 +836,15 @@ StoreValue(tentative_value.get(), source); if (source == kCommandLine) { - on_command_line_ = true; + MuState s = mu_state_.load(std::memory_order_relaxed); + s.on_command_line = true; + mu_state_.store(s, std::memory_order_relaxed); } break; } case SET_FLAG_IF_DEFAULT: { // set the flag's value, but only if it hasn't been set by someone else - if (modified_) { + if (mu_state_.load(std::memory_order_relaxed).modified) { // TODO(rogeeff): review and fix this semantic. Currently we do not fail // in this case if flag is modified. This is misleading since the flag's // value is not updated even though we return true. @@ -712,19 +863,23 @@ auto tentative_value = TryParse(value, err); if (!tentative_value) return false; - if (DefaultKind() == FlagDefaultKind::kDynamicValue) { - void* old_value = default_value_.dynamic_value; - default_value_.dynamic_value = tentative_value.release(); + void* new_default = tentative_value.release(); + void* old_value = SetDynamicDefault(this, new_default); + MuState s = mu_state_.load(std::memory_order_relaxed); + const bool was_modified = s.modified; + if (s.DefaultKind() == FlagDefaultKind::kDynamicValue) { tentative_value.reset(old_value); } else { - default_value_.dynamic_value = tentative_value.release(); - def_kind_ = static_cast<uint8_t>(FlagDefaultKind::kDynamicValue); + s.default_kind = static_cast<uint8_t>(FlagDefaultKind::kDynamicValue); + mu_state_.store(s, std::memory_order_relaxed); } - if (!modified_) { + if (!was_modified) { // Need to set both default value *and* current, in this case. - StoreValue(default_value_.dynamic_value, source); - modified_ = false; + StoreValue(new_default, source); + s = mu_state_.load(std::memory_order_relaxed); + s.modified = false; + mu_state_.store(s, std::memory_order_relaxed); } break; }
diff --git a/absl/flags/internal/flag.h b/absl/flags/internal/flag.h index c12c924..b565aaf 100644 --- a/absl/flags/internal/flag.h +++ b/absl/flags/internal/flag.h
@@ -19,8 +19,10 @@ #include <stddef.h> #include <stdint.h> +#include <algorithm> #include <atomic> #include <cstring> +#include <iterator> #include <memory> #include <string> #include <type_traits> @@ -44,7 +46,7 @@ #include "absl/synchronization/mutex.h" #include "absl/utility/utility.h" - namespace absl { +namespace absl { ABSL_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////////// @@ -154,7 +156,6 @@ return static_cast<ptrdiff_t>(reinterpret_cast<intptr_t>( op(FlagOp::kValueOffset, nullptr, nullptr, nullptr))); } - // Returns an address of RTTI's typeid(T). template <typename T> inline const std::type_info* GenRuntimeTypeId() { @@ -166,7 +167,7 @@ } /////////////////////////////////////////////////////////////////////////////// -// Flag help auxiliary structs. +// Flag help and name/type-name auxiliary structs. // This is help argument for absl::Flag encapsulating the string literal pointer // or pointer to function generating it as well as enum discriminating two @@ -184,6 +185,81 @@ } }; +inline constexpr uint8_t kEmptyFlagTypeId = 0; +inline constexpr uint8_t kCustomFlagTypeId = 31; + +// Common macro-stringified `#Type` spellings stored as a 5-bit ID in `FlagImpl` +// so common flags avoid emitting a per-flag type-name string. Entry 0 (`""`) is +// used when flag names are stripped or omitted; ID 31 (`kCustomFlagTypeId`) +// indicates that `name_` points to a packed `"<name>\0<type_name>\0"` array. +inline constexpr absl::string_view kCommonFlagTypeNames[] = { + "", + "bool", + "int", + "int16_t", + "uint16_t", + "int32_t", + "uint32_t", + "int64_t", + "uint64_t", + "size_t", + "float", + "double", + "std::string", + "string", + "std::vector<std::string>", + "absl::Duration", + "absl::Time", + "absl::int128", + "absl::uint128", + "std::int32_t", + "std::int64_t", + "std::optional<bool>", + "std::optional<int>", + "std::optional<int32_t>", + "std::optional<uint32_t>", + "std::optional<int64_t>", + "std::optional<uint64_t>", + "std::optional<size_t>", + "std::optional<double>", + "std::optional<std::string>", + "std::optional<absl::Duration>", +}; +static_assert(std::size(kCommonFlagTypeNames) == kCustomFlagTypeId, + "kCommonFlagTypeNames must have kCustomFlagTypeId entries"); + +constexpr uint8_t LookupCommonFlagTypeId(absl::string_view type_name) { + for (size_t i = 0; i < kCustomFlagTypeId; ++i) { + if (kCommonFlagTypeNames[i] == type_name) { + return static_cast<uint8_t>(i); + } + } + return kCustomFlagTypeId; +} + +constexpr uint8_t LookupCommonOrEmptyFlagTypeId(const char* type_name) { + if (type_name == nullptr) return kEmptyFlagTypeId; + size_t len = 0; + while (type_name[len] != '\0') ++len; + const uint8_t id = LookupCommonFlagTypeId(absl::string_view(type_name, len)); + return id == kCustomFlagTypeId ? kEmptyFlagTypeId : id; +} + +struct FlagNameArg { + const char* name; + uint8_t type_id; +}; + +template <typename Gen> +constexpr FlagNameArg MakeFlagNameArg() { + constexpr uint8_t kTypeId = LookupCommonFlagTypeId(Gen::AbslFlagTypeName()); + if constexpr (kTypeId != kCustomFlagTypeId) { + return {Gen::AbslFlagName(), kTypeId}; + } else { + return {Gen::AbslFlagPackedNameAndType(), kCustomFlagTypeId}; + } +} + template <typename Gen, size_t N = Gen::Value().size()> constexpr FixedCharArray<N + 1> HelpStringAsArray(int) { return FixedCharArray<N + 1>::FromLiteralString( @@ -437,7 +513,7 @@ template <typename T> struct FlagValue<T, FlagValueStorageKind::kValueAndInitBit> : FlagOneWordValue { constexpr FlagValue() : FlagOneWordValue(0) {} - ABSL_ATTRIBUTE_ALWAYS_INLINE bool Get(const SequenceLock&, T& dst) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE bool Get(T& dst) const { int64_t storage = value.load(std::memory_order_acquire); if (ABSL_PREDICT_FALSE(storage == 0)) { // This assert is to ensure that the initialization inside FlagImpl::Init @@ -458,7 +534,7 @@ template <typename T> struct FlagValue<T, FlagValueStorageKind::kOneWordAtomic> : FlagOneWordValue { constexpr FlagValue() : FlagOneWordValue() {} - ABSL_ATTRIBUTE_ALWAYS_INLINE bool Get(const SequenceLock&, T& dst) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE bool Get(T& dst) const { int64_t one_word_val = value.load(std::memory_order_acquire); if (ABSL_PREDICT_FALSE(one_word_val == FlagOneWordValue::Uninitialized())) { return false; @@ -476,16 +552,30 @@ // value once it is initialized. template <typename T> struct FlagValue<T, FlagValueStorageKind::kSequenceLocked> { - ABSL_ATTRIBUTE_ALWAYS_INLINE bool Get(const SequenceLock& lock, - T& dst) const { - return lock.TryRead(&dst, value_words, sizeof(T)); + constexpr FlagValue() : FlagValue(std::make_index_sequence<kNumWords>{}) {} + + ABSL_ATTRIBUTE_ALWAYS_INLINE bool Get(T& dst) const { + // FlagImpl::SeqLock() computes `&seq_lock` via `AtomicBufferValue() + + // kNumWords`, so verify no padding or fields sit between `value_words` + // and `seq_lock`. + static_assert( + offsetof(FlagValue, seq_lock) - offsetof(FlagValue, value_words) == + kNumWords * sizeof(std::atomic<uint64_t>), + "Unexpected memory layout of sequence-locked FlagValue"); + return seq_lock.TryRead(&dst, value_words, sizeof(T)); } static constexpr int kNumWords = flags_internal::AlignUp(sizeof(T), sizeof(uint64_t)) / sizeof(uint64_t); - alignas(T) alignas( - std::atomic<uint64_t>) std::atomic<uint64_t> value_words[kNumWords]; + alignas((std::max)(alignof(T), alignof(std::atomic<uint64_t>))) + std::atomic<uint64_t> value_words[kNumWords]; + flags_internal::SequenceLock seq_lock; + + private: + template <size_t... Is> + constexpr explicit FlagValue(std::index_sequence<Is...>) + : value_words{(static_cast<void>(Is), uint64_t{0})...} {} }; // This specialization represents the storage of flag values types with the @@ -532,7 +622,7 @@ // ensure Init is done before any access to the flag value. constexpr FlagValue() : FlagMaskedPointerValue(&buffer[0]) {} - ABSL_ATTRIBUTE_ALWAYS_INLINE bool Get(const SequenceLock&, T& dst) const { + ABSL_ATTRIBUTE_ALWAYS_INLINE bool Get(T& dst) const { MaskedPointer ptr_value = value.load(std::memory_order_acquire); if (ABSL_PREDICT_TRUE(ptr_value.AllowsUnprotectedRead())) { @@ -580,22 +670,37 @@ #pragma GCC diagnostic ignored "-Wnon-virtual-dtor" #endif class FlagImpl final : public CommandLineFlag { + private: + static constexpr uint8_t kMaxInlineModCount = 7; + + struct MuState { + uint8_t default_kind : 2; + bool modified : 1; + bool on_command_line : 1; + bool has_callback : 1; + // Saturates at kMaxInlineModCount; further mutations are tracked in + // OverflowModCounts(). + uint8_t mod_count : 3; + + constexpr FlagDefaultKind DefaultKind() const { + return static_cast<FlagDefaultKind>(default_kind); + } + }; + static_assert(std::atomic<MuState>::is_always_lock_free); + public: - constexpr FlagImpl(const char* name, const char* type_name, - const char* filename, FlagOpFn op, FlagHelpArg help, + constexpr FlagImpl(FlagNameArg name, FlagOpFn op, FlagHelpArg help, FlagValueStorageKind value_kind, FlagDefaultArg default_arg) - : name_(name), - type_name_(type_name), - filename_(filename), + : name_(name.name), op_(op), help_(help.source), help_source_kind_(static_cast<uint8_t>(help.kind)), value_storage_kind_(static_cast<uint8_t>(value_kind)), - def_kind_(static_cast<uint8_t>(default_arg.kind)), - modified_(false), - on_command_line_(false), - callback_(nullptr), + type_id_(name.type_id), + mu_state_(MuState{static_cast<uint8_t>(default_arg.kind), false, false, + false, 0}), + file_id_(0), default_value_(default_arg.source), data_guard_{} {} @@ -624,6 +729,7 @@ // Mutating access methods void Write(const void* src) ABSL_LOCKS_EXCLUDED(DataGuard()); + void SetFilename(const char* filename); // Interfaces to operate on callbacks. void SetCallback(const FlagCallbackFunc mutation_callback) @@ -665,6 +771,9 @@ // The same as above, but used for sequencelock-protected storage. std::atomic<uint64_t>* AtomicBufferValue() const; + // Accessor for the SequenceLock inside FlagValue<T, kSequenceLocked>. + flags_internal::SequenceLock& SeqLock() const; + // This is an accessor for a value stored as one word atomic. Returns a // mutable reference to an atomic value. std::atomic<int64_t>& OneWordValue() const; @@ -691,10 +800,6 @@ FlagValueStorageKind ValueStorageKind() const { return static_cast<FlagValueStorageKind>(value_storage_kind_); } - FlagDefaultKind DefaultKind() const - ABSL_EXCLUSIVE_LOCKS_REQUIRED(DataGuard()) { - return static_cast<FlagDefaultKind>(def_kind_); - } // CommandLineFlag interface implementation absl::string_view Name() const override; @@ -702,8 +807,7 @@ std::string Filename() const override; std::string Help() const override; FlagFastTypeId TypeId() const override; - bool IsSpecifiedOnCommandLine() const override - ABSL_LOCKS_EXCLUDED(DataGuard()); + bool IsSpecifiedOnCommandLine() const override; std::string DefaultValue() const override ABSL_LOCKS_EXCLUDED(DataGuard()); std::string CurrentValue() const override ABSL_LOCKS_EXCLUDED(DataGuard()); bool ValidateInputValue(absl::string_view value) const override @@ -712,7 +816,15 @@ ABSL_LOCKS_EXCLUDED(DataGuard()); int64_t ModificationCount() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(DataGuard()); + // Lock-free check used by RestoreState() to skip acquiring DataGuard() when + // restoring an unmodified state onto a still-unmodified flag. Uses relaxed + // memory ordering because the fast path returns immediately without reading + // any other dynamic state, and the slow path acquires DataGuard(). + bool IsUnmodifiedFast() const { + return mu_state_.load(std::memory_order_relaxed).mod_count == 0; + } bool CanSkipInitOnSave() const; + void RecordMutation() ABSL_EXCLUSIVE_LOCKS_REQUIRED(DataGuard()); // Interfaces to save and restore flags to/from persistent state. // Returns current flag state or nullptr if flag does not support @@ -731,14 +843,9 @@ // Immutable flag's state. - // Flags name passed to ABSL_FLAG as second arg. + // Flags name passed to ABSL_FLAG as second arg (followed by NUL-terminated + // type name when `type_id_ == kCustomFlagTypeId`). const char* const name_; - - // Flags type passed to ABSL_FLAG as first arg. - const char* const type_name_; - - // The file name where ABSL_FLAG resides. - const char* const filename_; // Type-specific operations vtable. const FlagOpFn op_; // Help message literal or function to generate it. @@ -747,33 +854,22 @@ const uint8_t help_source_kind_ : 1; // Kind of storage this flag is using for the flag's value. const uint8_t value_storage_kind_ : 2; + // Index into `kCommonFlagTypeNames`, or `kCustomFlagTypeId` when `name_` + // stores `"<name>\0<type_name>\0"`. + const uint8_t type_id_ : 5; - uint8_t : 0; // The bytes containing the const bitfields must not be - // shared with bytes containing the mutable bitfields. + // Mutable state updated under DataGuard() and read with relaxed atomic loads. + std::atomic<MuState> mu_state_; - // Mutable flag's state (guarded by `data_guard_`). - - // def_kind_ is not guard by DataGuard() since it is accessed in Init without - // locks. - uint8_t def_kind_ : 2; - // Has this flag's value been modified? - bool modified_ : 1 ABSL_GUARDED_BY(DataGuard()); - // Has this flag been specified on command line. - bool on_command_line_ : 1 ABSL_GUARDED_BY(DataGuard()); + // Deduplicated filename index assigned on registration (0 = unset). + uint16_t file_id_; // Unique tag for absl::call_once call to initialize this flag. absl::once_flag init_control_; - // Sequence lock / mutation counter. - flags_internal::SequenceLock seq_lock_; - - // Optional flag's callback and absl::Mutex to guard the invocations. - FlagCallback* callback_ ABSL_GUARDED_BY(DataGuard()); - // Either a pointer to the function generating the default value based on the - // value specified in ABSL_FLAG or pointer to the dynamically set default - // value via SetCommandLineOptionWithMode. def_kind_ is used to distinguish - // these two cases. - FlagDefaultSrc default_value_; + // Initial default value source specified in ABSL_FLAG. Dynamic default + // overrides set via SET_FLAGS_DEFAULT are stored in a side table. + const FlagDefaultSrc default_value_; // This is reserved space for an absl::Mutex to guard flag data. It will be // initialized in FlagImpl::Init via placement new. @@ -803,11 +899,23 @@ template <typename T> class Flag { public: - constexpr Flag(const char* name, const char* type_name, const char* filename, - FlagHelpArg help, const FlagDefaultArg default_arg) - : impl_(name, type_name, filename, &FlagOps<T>, help, - flags_internal::StorageKind<T>(), default_arg), + constexpr Flag(FlagNameArg name, FlagHelpArg help, + const FlagDefaultArg default_arg) + : impl_(name, &FlagOps<T>, help, flags_internal::StorageKind<T>(), + default_arg), value_() {} + constexpr Flag(const char* name, FlagHelpArg help, + const FlagDefaultArg default_arg) + : Flag(FlagNameArg{name, kEmptyFlagTypeId}, help, default_arg) {} + constexpr Flag(const char* name, const char* /*filename*/, FlagHelpArg help, + const FlagDefaultArg default_arg) + : Flag(FlagNameArg{name, kEmptyFlagTypeId}, help, default_arg) {} + // Kept for backwards compatibility. + constexpr Flag(const char* name, const char* type_name, + const char* /*filename*/, FlagHelpArg help, + const FlagDefaultArg default_arg) + : Flag(FlagNameArg{name, LookupCommonOrEmptyFlagTypeId(type_name)}, help, + default_arg) {} // CommandLineFlag interface absl::string_view Name() const { return impl_.Name(); } @@ -844,7 +952,7 @@ } #endif - if (ABSL_PREDICT_FALSE(!value_.Get(impl_.seq_lock_, u.value))) { + if (ABSL_PREDICT_FALSE(!value_.Get(u.value))) { impl_.Read(&u.value); } return std::move(u.value); @@ -960,8 +1068,12 @@ public: constexpr explicit FlagRegistrar(Flag<T>& flag, const char* filename) : flag_(flag) { - if (do_register) + if (filename != nullptr) { + flag_.impl_.SetFilename(filename); + } + if (do_register) { flags_internal::RegisterCommandLineFlag(flag_.impl_, filename); + } } FlagRegistrar OnUpdate(FlagCallbackFunc cb) && {
diff --git a/absl/flags/internal/sequence_lock.h b/absl/flags/internal/sequence_lock.h index 1729d7f..f3c95ec 100644 --- a/absl/flags/internal/sequence_lock.h +++ b/absl/flags/internal/sequence_lock.h
@@ -66,11 +66,6 @@ lock_.store(0, std::memory_order_release); } - // Returns true if the flag is either uninitialized or initialized with zero - // modifications. - bool IsUnmodified() const { - return lock_.load(std::memory_order_acquire) <= 0; - } // Copy "size" bytes of data from "src" to "dst", protected as a read-side // critical section of the sequence lock. @@ -124,25 +119,6 @@ lock_.store(orig_seq + 2, std::memory_order_release); } - // Return the number of times that Write() has been called. - // - // REQUIRES: This must be externally synchronized against concurrent calls to - // `Write()` or `IncrementModificationCount()`. - // REQUIRES: `MarkInitialized()` must have been previously called. - int64_t ModificationCount() const { - int64_t val = lock_.load(std::memory_order_relaxed); - assert(val != kUninitialized && (val & 1) == 0); - return val / 2; - } - - // REQUIRES: This must be externally synchronized against concurrent calls to - // `Write()` or `ModificationCount()`. - // REQUIRES: `MarkInitialized()` must have been previously called. - void IncrementModificationCount() { - int64_t val = lock_.load(std::memory_order_relaxed); - assert(val != kUninitialized); - lock_.store(val + 2, std::memory_order_relaxed); - } private: // Perform the equivalent of "memcpy(dst, src, size)", but using relaxed
diff --git a/absl/flags/marshalling.cc b/absl/flags/marshalling.cc index 99d1edd..cb829a4 100644 --- a/absl/flags/marshalling.cc +++ b/absl/flags/marshalling.cc
@@ -17,8 +17,6 @@ #include <stddef.h> -#include <cmath> -#include <limits> #include <sstream> #include <string> #include <type_traits> @@ -32,7 +30,6 @@ #include "absl/strings/match.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" -#include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" @@ -197,27 +194,8 @@ return ss.str(); } -template <typename T> -std::string UnparseFloatingPointVal(T v) { - // digits10 is guaranteed to roundtrip correctly in string -> value -> string - // conversions, but may not be enough to represent all the values correctly. - std::string digit10_str = - absl::StrFormat("%.*g", std::numeric_limits<T>::digits10, v); - if (std::isnan(v) || std::isinf(v)) return digit10_str; - - T roundtrip_val = 0; - std::string err; - if (absl::ParseFlag(digit10_str, &roundtrip_val, &err) && - roundtrip_val == v) { - return digit10_str; - } - - // max_digits10 is the number of base-10 digits that are necessary to uniquely - // represent all distinct values. - return absl::StrFormat("%.*g", std::numeric_limits<T>::max_digits10, v); -} -std::string Unparse(float v) { return UnparseFloatingPointVal(v); } -std::string Unparse(double v) { return UnparseFloatingPointVal(v); } +std::string Unparse(float v) { return absl::StrCat(absl::HighPrecision(v)); } +std::string Unparse(double v) { return absl::StrCat(absl::HighPrecision(v)); } std::string AbslUnparseFlag(absl::string_view v) { return std::string(v); } std::string AbslUnparseFlag(const std::vector<std::string>& v) { return absl::StrJoin(v, ",");
diff --git a/absl/flags/marshalling_test.cc b/absl/flags/marshalling_test.cc index 9629744..6870920 100644 --- a/absl/flags/marshalling_test.cc +++ b/absl/flags/marshalling_test.cc
@@ -1007,6 +1007,18 @@ EXPECT_EQ(absl::UnparseFlag(value), "0.0123"); value = -0.71f; EXPECT_EQ(absl::UnparseFlag(value), "-0.71"); + value = 0.0f; + EXPECT_EQ(absl::UnparseFlag(value), "0"); + value = -0.0f; + EXPECT_EQ(absl::UnparseFlag(value), "-0"); + value = std::nanf(""); + EXPECT_EQ(absl::UnparseFlag(value), "nan"); + value = -std::nanf(""); + EXPECT_EQ(absl::UnparseFlag(value), "nan"); + value = std::numeric_limits<float>::infinity(); + EXPECT_EQ(absl::UnparseFlag(value), "inf"); + value = -std::numeric_limits<float>::infinity(); + EXPECT_EQ(absl::UnparseFlag(value), "-inf"); } // -------------------------------------------------------------------- @@ -1024,10 +1036,16 @@ EXPECT_EQ(absl::UnparseFlag(value), "-0.71"); value = -0; EXPECT_EQ(absl::UnparseFlag(value), "0"); + value = -0.0; + EXPECT_EQ(absl::UnparseFlag(value), "-0"); value = std::nan(""); EXPECT_EQ(absl::UnparseFlag(value), "nan"); + value = -std::nan(""); + EXPECT_EQ(absl::UnparseFlag(value), "nan"); value = std::numeric_limits<double>::infinity(); EXPECT_EQ(absl::UnparseFlag(value), "inf"); + value = -std::numeric_limits<double>::infinity(); + EXPECT_EQ(absl::UnparseFlag(value), "-inf"); } // -------------------------------------------------------------------- @@ -1161,6 +1179,11 @@ TestRoundtrip(0.123456e-20f); TestRoundtrip(0.1234567e-20f); TestRoundtrip(0.12345678e-20f); + + TestRoundtrip(std::numeric_limits<float>::min()); + TestRoundtrip(std::numeric_limits<float>::max()); + TestRoundtrip(std::numeric_limits<float>::lowest()); + TestRoundtrip(std::numeric_limits<float>::denorm_min()); } TEST(MarshallingTest, TestDoubleRoundTrip) { @@ -1217,6 +1240,11 @@ TestRoundtrip(0.123456789123456e-50); TestRoundtrip(0.1234567891234567e-50); TestRoundtrip(0.12345678912345678e-50); + + TestRoundtrip(std::numeric_limits<double>::min()); + TestRoundtrip(std::numeric_limits<double>::max()); + TestRoundtrip(std::numeric_limits<double>::lowest()); + TestRoundtrip(std::numeric_limits<double>::denorm_min()); } } // namespace
diff --git a/absl/flags/parse.cc b/absl/flags/parse.cc index 940bf56..25669f3 100644 --- a/absl/flags/parse.cc +++ b/absl/flags/parse.cc
@@ -213,7 +213,8 @@ while (std::getline(flag_file, line)) { line_number++; - absl::string_view stripped = absl::StripLeadingAsciiWhitespace(line); + absl::string_view stripped = + absl::StripLeadingAsciiWhitespace(absl::StripSuffix(line, "\r")); if (stripped.empty() || stripped[0] == '#') { // Comment or empty line; just ignore.
diff --git a/absl/flags/parse_test.cc b/absl/flags/parse_test.cc index 138cf6e..9687950 100644 --- a/absl/flags/parse_test.cc +++ b/absl/flags/parse_test.cc
@@ -203,16 +203,17 @@ // temporary directory location. This way we can test inclusion of one flagfile // from another flagfile. const char* GetFlagfileFlag(const std::vector<FlagfileData>& ffd, - std::string& flagfile_flag) { + std::string& flagfile_flag, + absl::string_view line_ending = "\n") { flagfile_flag = "--flagfile="; absl::string_view separator; for (const auto& flagfile_data : ffd) { std::string flagfile_name = absl::StrCat(GetTestTempDir(), flagfile_data.file_name); - std::ofstream flagfile_out(flagfile_name); + std::ofstream flagfile_out(flagfile_name, std::ios::binary); for (auto line : flagfile_data.file_lines) { - flagfile_out << absl::Substitute(line, GetTestTempDir()) << "\n"; + flagfile_out << absl::Substitute(line, GetTestTempDir()) << line_ending; } absl::StrAppend(&flagfile_flag, separator, flagfile_name); @@ -769,6 +770,57 @@ // -------------------------------------------------------------------- +TEST_F(ParseTest, TestFlagfileWithCrLf) { + std::string flagfile_flag; + + constexpr const char* const crlf_basic_data[] = { + "# comment", + "", + " ", + "--int_flag=42", + "--string_flag=plain", + "--bool_flag", + "--udt_flag=AAA", + }; + const char* in_args1[] = { + "testbin", + GetFlagfileFlag( + {{"parse_test.crlf_basic", absl::MakeConstSpan(crlf_basic_data)}}, + flagfile_flag, "\r\n"), + }; + TestParse(in_args1, 42, 1.1, "plain", true); + EXPECT_EQ(absl::GetFlag(FLAGS_udt_flag).value, 10); + + GetFlagfileFlag({{"parse_test.crlf_ff2", absl::MakeConstSpan(ff2_data)}, + {"parse_test.crlf_ff1", absl::MakeConstSpan(ff1_data)}}, + flagfile_flag, "\r\n"); + + constexpr const char* const crlf_include_data[] = { + "--flagfile=$0/parse_test.crlf_ff1", + "--flagfile=$0/parse_test.crlf_ff2", + }; + const char* in_args2[] = { + "testbin", + GetFlagfileFlag( + {{"parse_test.crlf_include", absl::MakeConstSpan(crlf_include_data)}}, + flagfile_flag, "\r\n"), + }; + TestParse(in_args2, 100, 0.1, "q2w2 ", false); + + constexpr const char* const crlf_empty_str_data[] = { + "--string_flag=", + }; + const char* in_args3[] = { + "testbin", + GetFlagfileFlag({{"parse_test.crlf_empty_str", + absl::MakeConstSpan(crlf_empty_str_data)}}, + flagfile_flag, "\r\n"), + }; + TestParse(in_args3, 100, 0.1, "", false); +} + +// -------------------------------------------------------------------- + TEST_F(ParseDeathTest, TestInvalidFlagfiles) { std::string flagfile_flag; @@ -808,6 +860,15 @@ EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args3), "Flagfile can't contain position arguments or --"); + const char* in_args3_crlf[] = { + "testbin", + GetFlagfileFlag( + {{"parse_test.crlf_ff6", absl::MakeConstSpan(ff6_data)}}, + flagfile_flag, "\r\n"), + }; + EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args3_crlf), + "Flagfile can't contain position arguments or --"); + const char* in_args4[] = { "testbin", "--flagfile=invalid_flag_file",
diff --git a/absl/hash/BUILD.bazel b/absl/hash/BUILD.bazel index 50f1692..b797c0e 100644 --- a/absl/hash/BUILD.bazel +++ b/absl/hash/BUILD.bazel
@@ -211,6 +211,37 @@ ], ) +cc_library( + name = "canonical_hash", + hdrs = ["internal/canonical_hash.h"], + copts = ABSL_DEFAULT_COPTS, + linkopts = ABSL_DEFAULT_LINKOPTS, + visibility = [ + "//absl/container:__pkg__", + ], + deps = [ + ":hash", + "//absl/base", + "//absl/base:config", + "//absl/meta:type_traits", + ], +) + +cc_test( + name = "canonical_hash_test", + srcs = ["internal/canonical_hash_test.cc"], + copts = ABSL_TEST_COPTS, + linkopts = ABSL_DEFAULT_LINKOPTS, + deps = [ + ":canonical_hash", + ":hash", + "//absl/base:config", + "//absl/strings:string_view", + "@googletest//:gtest", + "@googletest//:gtest_main", + ], +) + cc_test( name = "low_level_hash_test", srcs = ["internal/low_level_hash_test.cc"],
diff --git a/absl/hash/CMakeLists.txt b/absl/hash/CMakeLists.txt index f8e7afa..61940f8 100644 --- a/absl/hash/CMakeLists.txt +++ b/absl/hash/CMakeLists.txt
@@ -164,6 +164,37 @@ absl::config ) +# Internal-only target, do not depend on directly. +absl_cc_library( + NAME + canonical_hash + HDRS + "internal/canonical_hash.h" + COPTS + ${ABSL_DEFAULT_COPTS} + DEPS + absl::base + absl::config + absl::hash + absl::type_traits + PUBLIC +) + +absl_cc_test( + NAME + canonical_hash_test + SRCS + "internal/canonical_hash_test.cc" + COPTS + ${ABSL_TEST_COPTS} + DEPS + absl::canonical_hash + absl::config + absl::hash + absl::string_view + GTest::gmock_main +) + absl_cc_test( NAME low_level_hash_test
diff --git a/absl/hash/hash_test.cc b/absl/hash/hash_test.cc index e42e1a0..7bca928 100644 --- a/absl/hash/hash_test.cc +++ b/absl/hash/hash_test.cc
@@ -930,6 +930,19 @@ t.value + static_cast<int>(InvokeTag::kHashValue)); } +struct NonTriviallyCopyableUniquelyRepresented { + uintptr_t v; + explicit NonTriviallyCopyableUniquelyRepresented(uintptr_t v) : v(v) {} + // NOLINTNEXTLINE(modernize-use-equals-default) + NonTriviallyCopyableUniquelyRepresented( + const NonTriviallyCopyableUniquelyRepresented& other) + : v(other.v) {} + friend bool operator==(const NonTriviallyCopyableUniquelyRepresented& a, + const NonTriviallyCopyableUniquelyRepresented& b) { + return a.v == b.v; + } +}; + } // namespace namespace absl { @@ -940,6 +953,10 @@ CustomHashType<Tags...>, typename EnableIfContained<InvokeTag::kUniquelyRepresented, Tags...>::type> : std::true_type {}; + +template <> +struct is_uniquely_represented<NonTriviallyCopyableUniquelyRepresented> + : std::true_type {}; } // namespace hash_internal ABSL_NAMESPACE_END } // namespace absl @@ -1118,7 +1135,15 @@ EXPECT_TRUE(is_uniquely_represented<unsigned char>::value); EXPECT_TRUE(is_uniquely_represented<int>::value); EXPECT_FALSE(is_uniquely_represented<bool>::value); - EXPECT_FALSE(is_uniquely_represented<int*>::value); + EXPECT_TRUE(is_uniquely_represented<int*>::value); +} + +TEST(IsUniquelyRepresentedTest, NonTriviallyCopyableInFlatHashMap) { + absl::flat_hash_map<NonTriviallyCopyableUniquelyRepresented, int> m; + m[NonTriviallyCopyableUniquelyRepresented{1}] = 10; + m.emplace(NonTriviallyCopyableUniquelyRepresented{2}, 20); + EXPECT_EQ(m.find(NonTriviallyCopyableUniquelyRepresented{1})->second, 10); + EXPECT_EQ(m[NonTriviallyCopyableUniquelyRepresented{2}], 20); } struct IntAndString {
diff --git a/absl/hash/internal/canonical_hash.h b/absl/hash/internal/canonical_hash.h new file mode 100644 index 0000000..5a467ce --- /dev/null +++ b/absl/hash/internal/canonical_hash.h
@@ -0,0 +1,149 @@ +// Copyright 2026 The Abseil Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef ABSL_HASH_INTERNAL_CANONICAL_HASH_H_ +#define ABSL_HASH_INTERNAL_CANONICAL_HASH_H_ + +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <type_traits> + +#include "absl/base/casts.h" +#include "absl/base/config.h" +#include "absl/hash/hash.h" +#include "absl/meta/type_traits.h" + +namespace absl { +ABSL_NAMESPACE_BEGIN +namespace hash_internal { + +// Unsigned integer type of size `N` if `N` is 1, 2, 4, or 8, `void` otherwise. +template <size_t N> +using UintOfSizeT = std::conditional_t< + N == 1, uint8_t, + std::conditional_t< + N == 2, uint16_t, + std::conditional_t<N == 4, uint32_t, + std::conditional_t<N == 8, uint64_t, void>>>>; + +// True if `T` can be copied as raw bytes without running a copy constructor or +// destructor. Unlike `std::is_trivially_copyable`, this does not require a +// trivial `operator=`, so it is true for `std::pair<int, int>` while still +// excluding Objective-C ARC pointers. +template <typename T> +using IsTriviallyCopyConstructibleAndDestructible = + std::bool_constant<std::is_trivially_copy_constructible_v<T> && + std::is_trivially_destructible_v<T>>; + +// Returns a canonical `absl::Hash` for `T`. Types with the exact same hash +// implementation (such as `is_uniquely_represented` types of the same size) +// return the same hasher type, which is useful for type erasure. +template <typename T> +constexpr auto CanonicalHasher() { + if constexpr (is_uniquely_represented<T>::value && + IsTriviallyCopyConstructibleAndDestructible<T>::value && + FitsIn64BitsPowerOf2<T>::value) { + return Hash<UintOfSizeT<sizeof(T)>>(); + } else { + return Hash<T>(); + } +} + +// Type-erased key argument passed by value in a single register on common ABIs. +struct EncodedHashKey { + // Returns true if `key` should be passed by value inside `EncodedHashKey`, + // avoiding spilling it to the stack at the call site. + template <class T> + static constexpr bool ShouldPassByValue() { + return FitsIn64BitsPowerOf2<T>::value && sizeof(T) <= sizeof(bytes) && + alignof(T) <= alignof(EncodedHashKey) && + IsTriviallyCopyConstructibleAndDestructible<T>::value; + } + + template <class T> + static EncodedHashKey FromValue(const T& v) { + static_assert(ShouldPassByValue<T>()); + EncodedHashKey res{}; + std::memcpy(res.bytes, &v, sizeof(T)); + return res; + } + + static EncodedHashKey FromPtr(const void* ptr) { return FromValue(ptr); } + + template <class T> + const T& ToValue() const { + static_assert(ShouldPassByValue<T>()); + return *reinterpret_cast<const T*>(bytes); + } + + template <class T> + const T* ToPtr() const { + return absl::bit_cast<const T*>(bytes); + } + + // Byte array (rather than `const void*`) avoids UB and MSan `noundef` errors + // when a small key contains padding or uninitialized bytes. + alignas(void*) unsigned char bytes[sizeof(void*)]; +}; + +using HashForKeyFn = size_t (*)(EncodedHashKey hasher, size_t seed); + +// Type erased function to apply `Hasher` (the result of `CanonicalHasher<T>()`) +// to the key encoded by `CanonicalHashKey::data()`. +template <class Hasher> +size_t TypeErasedApplyAbslHashToKeyFn(EncodedHashKey key, size_t seed) { + using T = typename Hasher::KeyType; + if constexpr (EncodedHashKey::ShouldPassByValue<T>()) { + return HashWithSeed().hash(Hasher(), key.ToValue<T>(), seed); + } else { + return HashWithSeed().hash(Hasher(), *key.ToPtr<T>(), seed); + } +} + +// No arguments hash function for a specific key that uses +// `CanonicalHasher<Key>`, so that `get_hash_fn()` is shared across all key +// types with the same canonical hasher. +template <class Key> +struct CanonicalHashKey { + using NonConstK = absl::remove_cvref_t<Key>; + using Canonical = decltype(CanonicalHasher<NonConstK>()); + using CanonicalKey = typename Canonical::KeyType; + + explicit CanonicalHashKey(const NonConstK& k) : key(k) {} + + // `data()` and `get_hash_fn()` are passed to type erased functions. + EncodedHashKey data() const { + // Check `CanonicalKey` to match `TypeErasedApplyAbslHashToKeyFn`. + if constexpr (EncodedHashKey::ShouldPassByValue<CanonicalKey>()) { + static_assert(sizeof(NonConstK) == sizeof(CanonicalKey)); + return EncodedHashKey::FromValue(key); + } else { + return EncodedHashKey::FromPtr(&key); + } + } + static constexpr HashForKeyFn get_hash_fn() { + return &TypeErasedApplyAbslHashToKeyFn<Canonical>; + } + + // Small keys are stored by value so that inlined caller keys stay in + // registers instead of becoming address-taken via `data()`. + type_traits_internal::AddConstRefIfExpensiveToCopy<Key> key; +}; + +} // namespace hash_internal +ABSL_NAMESPACE_END +} // namespace absl + +#endif // ABSL_HASH_INTERNAL_CANONICAL_HASH_H_
diff --git a/absl/hash/internal/canonical_hash_test.cc b/absl/hash/internal/canonical_hash_test.cc new file mode 100644 index 0000000..01e74cd --- /dev/null +++ b/absl/hash/internal/canonical_hash_test.cc
@@ -0,0 +1,173 @@ +// Copyright 2026 The Abseil Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "absl/hash/internal/canonical_hash.h" + +#include <array> +#include <cstddef> +#include <cstdint> +#include <optional> +#include <string> +#include <type_traits> +#include <utility> + +#include "gtest/gtest.h" +#include "absl/base/config.h" +#include "absl/hash/hash.h" +#include "absl/strings/string_view.h" + +namespace absl { +ABSL_NAMESPACE_BEGIN +namespace hash_internal { + +struct NonTriviallyCopyableKey { + uintptr_t v; + explicit NonTriviallyCopyableKey(uintptr_t v) : v(v) {} + // NOLINTNEXTLINE(modernize-use-equals-default) + NonTriviallyCopyableKey(const NonTriviallyCopyableKey& other) : v(other.v) {} +}; + +template <> +struct is_uniquely_represented<NonTriviallyCopyableKey> // NOLINT + : std::true_type {}; + +namespace { + +TEST(CanonicalHasherTest, UniquelyRepresentedTypesShareHasher) { + enum class Enum8 : uint8_t { kA = 1 }; + enum class Enum16 : uint16_t { kA = 1 }; + enum class Enum32 : uint32_t { kA = 1 }; + enum class SignedEnum32 : int32_t { kA = -1 }; + enum class Enum64 : uint64_t { kA = 1 }; + + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<int8_t>()), + absl::Hash<uint8_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<uint8_t>()), + absl::Hash<uint8_t>>)); + EXPECT_TRUE(( + std::is_same_v<decltype(CanonicalHasher<Enum8>()), absl::Hash<uint8_t>>)); + + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<int16_t>()), + absl::Hash<uint16_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<uint16_t>()), + absl::Hash<uint16_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<Enum16>()), + absl::Hash<uint16_t>>)); + + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<int32_t>()), + absl::Hash<uint32_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<uint32_t>()), + absl::Hash<uint32_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<Enum32>()), + absl::Hash<uint32_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<SignedEnum32>()), + absl::Hash<uint32_t>>)); + + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<int64_t>()), + absl::Hash<uint64_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<uint64_t>()), + absl::Hash<uint64_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<Enum64>()), + absl::Hash<uint64_t>>)); + + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<double*>()), + decltype(CanonicalHasher<uintptr_t>())>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<const int*>()), + decltype(CanonicalHasher<uintptr_t>())>)); + + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<std::string>()), + absl::Hash<std::string>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<std::array<char, 3>>()), + absl::Hash<std::array<char, 3>>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<std::array<char, 5>>()), + absl::Hash<std::array<char, 5>>>)); + EXPECT_TRUE( + (std::is_same_v<decltype(CanonicalHasher<NonTriviallyCopyableKey>()), + absl::Hash<NonTriviallyCopyableKey>>)); +} + +TEST(CanonicalHashKeyTest, UniquelyRepresentedTypesShareHashFn) { + enum class MyEnum : uint32_t { kOne = 1, kTwo = 2 }; + using HashKeyInt32 = CanonicalHashKey<int32_t>; + using HashKeyEnum = CanonicalHashKey<MyEnum>; + EXPECT_EQ(HashKeyInt32::get_hash_fn(), HashKeyEnum::get_hash_fn()); + EXPECT_NE(HashKeyInt32::get_hash_fn(), + CanonicalHashKey<int8_t>::get_hash_fn()); + EXPECT_EQ(CanonicalHashKey<int*>::get_hash_fn(), + CanonicalHashKey<uintptr_t>::get_hash_fn()); + + const MyEnum c = MyEnum::kTwo; + const size_t seed = 100; + HashKeyEnum hk{c}; + EXPECT_EQ(HashKeyEnum::get_hash_fn()(hk.data(), seed), + HashWithSeed().hash(absl::Hash<MyEnum>{}, c, seed)); +} + +TEST(CanonicalHashKeyTest, DataPointerForSmallAndLargeKeys) { + // Small keys are encoded by value. + int32_t a = 42; + CanonicalHashKey<int32_t> hk_int32{a}; + EXPECT_EQ(hk_int32.data().ToValue<int32_t>(), 42); + + // Cheap to copy keys are stored by value. + absl::string_view sv = "hello"; + CanonicalHashKey<absl::string_view> hk_sv{sv}; + EXPECT_EQ(hk_sv.data().ToPtr<absl::string_view>(), &hk_sv.key); + EXPECT_NE(hk_sv.data().ToPtr<absl::string_view>(), &sv); + + // Expensive to copy keys are stored by reference. + std::string s = "hello"; + CanonicalHashKey<std::string> hk_str{s}; + EXPECT_EQ(hk_str.data().ToPtr<std::string>(), &s); + + // Non-trivially-copyable uniquely-represented keys are passed by address. + NonTriviallyCopyableKey ntc{123}; + CanonicalHashKey<NonTriviallyCopyableKey> hk_ntc{ntc}; + EXPECT_EQ(hk_ntc.data().ToPtr<NonTriviallyCopyableKey>(), &ntc); + EXPECT_EQ( + CanonicalHashKey<NonTriviallyCopyableKey>::get_hash_fn()(hk_ntc.data(), + 100), + HashWithSeed().hash(absl::Hash<NonTriviallyCopyableKey>{}, ntc, 100)); +} + +struct NonDefaultConstructibleSmallKey { + explicit NonDefaultConstructibleSmallKey(int32_t v) : val(v) {} + template <typename H> + friend H AbslHashValue(H h, const NonDefaultConstructibleSmallKey& k) { + return H::combine(std::move(h), k.val); + } + int32_t val; +}; + +TEST(CanonicalHashKeyTest, PaddedAndPartiallyInitializedSmallKeys) { + auto check = [](const auto& key) { + using Key = absl::remove_cvref_t<decltype(key)>; + EXPECT_TRUE(EncodedHashKey::ShouldPassByValue<Key>()); + const size_t seed = 100; + CanonicalHashKey<Key> hk{key}; + EXPECT_EQ(CanonicalHashKey<Key>::get_hash_fn()(hk.data(), seed), + HashWithSeed().hash(absl::Hash<Key>{}, key, seed)); + }; + + // Disengaged std::optional has uninitialized payload and padding bytes. + check(std::optional<int16_t>(std::nullopt)); + check(NonDefaultConstructibleSmallKey{123}); + // Fits in `sizeof(void*)` on 32-bit platforms and has a padding byte. + check(std::pair<int16_t, int8_t>{1, 2}); +} + +} // namespace +} // namespace hash_internal +ABSL_NAMESPACE_END +} // namespace absl
diff --git a/absl/hash/internal/hash.h b/absl/hash/internal/hash.h index b30260d..8aef023 100644 --- a/absl/hash/internal/hash.h +++ b/absl/hash/internal/hash.h
@@ -293,7 +293,8 @@ // state = H::combine(std::move(state), value2); // state = H::combine(std::move(state), value3); template <typename T, typename... Ts> - static H combine(H state, const T& value, const Ts&... values); + ABSL_ATTRIBUTE_ALWAYS_INLINE inline static H combine(H state, const T& value, + const Ts&... values); static H combine(H state) { return state; } // Combines a contiguous array of `size` elements into a hash state, returning @@ -337,7 +338,7 @@ // `is_uniquely_represented` is like `std::has_unique_object_representations`, // but with a few differences for legacy reasons that predate cl/989071457, such -// as disallowing pointers or Booleans. +// as disallowing Booleans. // // A type is "uniquely represented" if two equal values of that type are // guaranteed to have the same bytes in their underlying storage. In other @@ -369,10 +370,15 @@ // to support certain SFINAE techniques when defining specializations. template <typename T, typename Enable = void> struct is_uniquely_represented - : std::conditional_t<(std::is_integral_v<T> && !std::is_same_v<bool, T>) || - std::is_enum_v<T>, - std::has_unique_object_representations<T>, - std::false_type> {}; + : std::conditional_t< + (std::is_integral_v<T> && !std::is_same_v<bool, T>) || + std::is_enum_v<T> || std::is_pointer_v<T>, + // Use `void*` for pointers because Clang's + // `has_unique_object_representations` returns false for Objective-C + // object pointers. + std::has_unique_object_representations< + std::conditional_t<std::is_pointer_v<T>, void*, T>>, + std::false_type> {}; #ifdef ABSL_HAVE_INTRINSIC_INT128 // Specialize the trait for GNU extension types. @@ -383,7 +389,7 @@ #endif // ABSL_HAVE_INTRINSIC_INT128 template <typename T> -using FitsIn64Bits = +using FitsIn64BitsPowerOf2 = std::bool_constant<sizeof(T) <= sizeof(uint64_t) && // Check that sizeof(T) is a power of 2, since unaligned // operations require it. @@ -408,7 +414,7 @@ // Convenience function that combines `hash_state` with the byte representation // of `value`. template <typename H, typename T, - std::enable_if_t<FitsIn64Bits<T>::value, int> = 0> + std::enable_if_t<FitsIn64BitsPowerOf2<T>::value, int> = 0> H hash_bytes(H hash_state, const T& value) { const unsigned char* start = reinterpret_cast<const unsigned char*>(&value); uint64_t v; @@ -425,7 +431,7 @@ return CombineRaw()(std::move(hash_state), v); } template <typename H, typename T, - std::enable_if_t<!FitsIn64Bits<T>::value, int> = 0> + std::enable_if_t<!FitsIn64BitsPowerOf2<T>::value, int> = 0> H hash_bytes(H hash_state, const T& value) { const unsigned char* start = reinterpret_cast<const unsigned char*>(&value); return H::combine_contiguous(std::move(hash_state), start, sizeof(value)); @@ -450,8 +456,8 @@ // We use SFINAE to ensure that this overload only accepts bool, not types that // are convertible to bool. template <typename H, typename B> -std::enable_if_t<std::is_same_v<B, bool>, H> AbslHashValue(H hash_state, - B value) { +ABSL_ATTRIBUTE_ALWAYS_INLINE inline std::enable_if_t<std::is_same_v<B, bool>, H> +AbslHashValue(H hash_state, B value) { // We use ~size_t{} instead of 1 so that all bits are different between // true/false instead of only 1. return H::combine(std::move(hash_state), @@ -526,16 +532,10 @@ return hash_state; } -// AbslHashValue() for hashing pointers +// This overload prevents `char*` from matching the `absl::string_view` +// overload. template <typename H, typename T> -std::enable_if_t<std::is_pointer_v<T>, H> AbslHashValue(H hash_state, T ptr) { - auto v = reinterpret_cast<uintptr_t>(ptr); - // Due to alignment, pointers tend to have low bits as zero, and the next few - // bits follow a pattern since they are also multiples of some base value. - // The PointerAlignment test verifies that our mixing is good enough to handle - // these cases. - return H::combine(std::move(hash_state), v); -} +void AbslHashValue(H hash_state, const T* ptr); // AbslHashValue() for hashing nullptr_t template <typename H> @@ -1388,6 +1388,16 @@ struct UniquelyRepresentedProbe { template <typename H, typename T> static H Invoke(H state, const T& value) { + if constexpr (std::is_pointer_v<T>) { + static_assert( + !std::is_same_v<State, + typename AbslHashValueResultOrVoid< + State, std::remove_const_t< + std::remove_pointer_t<T>>*>::type>, + "Pointer types cannot have custom AbslHashValue overloads. " + "All pointers are hashed by address; wrap the pointer in a struct " + "or use a custom hash functor to hash the pointee."); + } return hash_internal::hash_bytes(std::move(state), value); } }; @@ -1397,9 +1407,10 @@ // The std::conditional_t<false, H, T> test is to enable SFINAE by making T // be a dependent type. template <typename H> - static H Invoke(H state, type_traits_internal::AddConstRefIfExpensiveToCopy< - std::conditional_t<false, H, T>> - value) { + ABSL_ATTRIBUTE_ALWAYS_INLINE static H Invoke( + H state, type_traits_internal::AddConstRefIfExpensiveToCopy< + std::conditional_t<false, H, T>> + value) { return AbslHashValue(std::move(state), value); } }; @@ -1455,7 +1466,7 @@ template <typename T> using IntegralFastPath = std::conjunction<std::is_integral<T>, is_uniquely_represented<T>, - FitsIn64Bits<T>>; + FitsIn64BitsPowerOf2<T>>; public: // Move only @@ -1603,6 +1614,8 @@ template <typename T> struct HashImpl { + using KeyType = T; + size_t operator()(const T& value) const { return MixingHashState::hash(value); }
diff --git a/absl/log/absl_vlog_is_on.h b/absl/log/absl_vlog_is_on.h index 1a6792c..a099b97 100644 --- a/absl/log/absl_vlog_is_on.h +++ b/absl/log/absl_vlog_is_on.h
@@ -55,13 +55,12 @@ // Resetting --vmodule will override all previous modifications to `--vmodule`, // including via SetVLogLevel. +// SKIP_ABSL_INLINE_NAMESPACE_CHECK + #ifndef ABSL_LOG_ABSL_VLOG_IS_ON_H_ #define ABSL_LOG_ABSL_VLOG_IS_ON_H_ -#include "absl/base/attributes.h" -#include "absl/base/config.h" #include "absl/log/internal/vlog_config.h" // IWYU pragma: export -#include "absl/strings/string_view.h" // This is expanded at the callsite to allow the compiler to optimize // always-false cases out of the build. @@ -74,20 +73,17 @@ #define ABSL_LOG_INTERNAL_MAX_LOG_VERBOSITY_CHECK(x) #endif -// Each ABSL_VLOG_IS_ON call site gets its own VLogSite that registers with the -// global linked list of sites to asynchronously update its verbosity level on -// changes to --v or --vmodule. The verbosity can also be set by manually -// calling SetVLogLevel. +// Each source file's ABSL_VLOG_IS_ON call sites share a single VLogSite that +// registers with the global linked list of sites to asynchronously update its +// verbosity level on changes to --v or --vmodule. The verbosity can also be set +// by manually calling SetVLogLevel. // // ABSL_VLOG_IS_ON is not async signal safe, but it is guaranteed not to // allocate new memory. -#define ABSL_VLOG_IS_ON(verbose_level) \ - (ABSL_LOG_INTERNAL_MAX_LOG_VERBOSITY_CHECK(verbose_level)[]() \ - ->::absl::log_internal::VLogSite * \ - { \ - ABSL_CONST_INIT static ::absl::log_internal::VLogSite site(__FILE__); \ - return &site; \ - }() \ - ->IsEnabled(verbose_level)) +#define ABSL_VLOG_IS_ON(verbose_level) \ + (ABSL_LOG_INTERNAL_MAX_LOG_VERBOSITY_CHECK( \ + verbose_level)::absl::log_internal::GetVLogSiteHolder([] { \ + return __FILE__; \ + }).site.IsEnabled(verbose_level)) #endif // ABSL_LOG_ABSL_VLOG_IS_ON_H_
diff --git a/absl/log/internal/log_message.cc b/absl/log/internal/log_message.cc index e56ef25..5e58612 100644 --- a/absl/log/internal/log_message.cc +++ b/absl/log/internal/log_message.cc
@@ -300,39 +300,32 @@ // This cannot go in the header since LogMessageData is defined in this file. LogMessage::~LogMessage() = default; -LogMessage& LogMessage::AtLocation(absl::string_view file, int line) { +void LogMessage::AtLocationImpl(absl::string_view file, int line) { data_->entry.full_filename_ = file; data_->entry.base_filename_ = Basename(file); data_->entry.line_ = line; LogBacktraceIfNeeded(); - return *this; } -LogMessage& LogMessage::NoPrefix() { - data_->entry.prefix_ = false; - return *this; -} +void LogMessage::NoPrefixImpl() { data_->entry.prefix_ = false; } -LogMessage& LogMessage::WithVerbosity(int verbose_level) { +void LogMessage::WithVerbosityImpl(int verbose_level) { if (verbose_level == absl::LogEntry::kNoVerbosityLevel) { data_->entry.verbose_level_ = absl::LogEntry::kNoVerbosityLevel; } else { data_->entry.verbose_level_ = std::max(0, verbose_level); } - return *this; } -LogMessage& LogMessage::WithTimestamp(absl::Time timestamp) { +void LogMessage::WithTimestampImpl(absl::Time timestamp) { data_->entry.timestamp_ = timestamp; - return *this; } -LogMessage& LogMessage::WithThreadID(absl::LogEntry::tid_t tid) { +void LogMessage::WithThreadIDImpl(absl::LogEntry::tid_t tid) { data_->entry.tid_ = tid; - return *this; } -LogMessage& LogMessage::WithMetadataFrom(const absl::LogEntry& entry) { +void LogMessage::WithMetadataFromImpl(const absl::LogEntry& entry) { data_->entry.full_filename_ = entry.full_filename_; data_->entry.base_filename_ = entry.base_filename_; data_->entry.line_ = entry.line_; @@ -341,26 +334,20 @@ data_->entry.verbose_level_ = entry.verbose_level_; data_->entry.timestamp_ = entry.timestamp_; data_->entry.tid_ = entry.tid_; - return *this; } -LogMessage& LogMessage::WithPerror() { - data_->is_perror = true; - return *this; -} +void LogMessage::WithPerrorImpl() { data_->is_perror = true; } -LogMessage& LogMessage::ToSinkAlso(absl::LogSink* absl_nonnull sink) { +void LogMessage::ToSinkAlsoImpl(absl::LogSink* absl_nonnull sink) { ABSL_INTERNAL_CHECK(sink, "null LogSink*"); data_->extra_sinks.push_back(sink); - return *this; } -LogMessage& LogMessage::ToSinkOnly(absl::LogSink* absl_nonnull sink) { +void LogMessage::ToSinkOnlyImpl(absl::LogSink* absl_nonnull sink) { ABSL_INTERNAL_CHECK(sink, "null LogSink*"); data_->extra_sinks.clear(); data_->extra_sinks.push_back(sink); data_->extra_sinks_only = true; - return *this; } #ifdef __ELF__ @@ -400,16 +387,6 @@ _exit(1); } -LogMessage& LogMessage::operator<<(const std::string& v) { - CopyToEncodedBuffer<StringType::kNotLiteral>(v); - return *this; -} - -LogMessage& LogMessage::operator<<(absl::string_view v) { - CopyToEncodedBuffer<StringType::kNotLiteral>(v); - return *this; -} - LogMessage& LogMessage::operator<<(const std::wstring& v) { CopyToEncodedBuffer<StringType::kNotLiteral>(v); return *this; @@ -449,22 +426,22 @@ } // NOLINTBEGIN(runtime/int) // NOLINTBEGIN(google-runtime-int) -template LogMessage& LogMessage::operator<<(const char& v); -template LogMessage& LogMessage::operator<<(const signed char& v); -template LogMessage& LogMessage::operator<<(const unsigned char& v); -template LogMessage& LogMessage::operator<<(const short& v); -template LogMessage& LogMessage::operator<<(const unsigned short& v); -template LogMessage& LogMessage::operator<<(const int& v); -template LogMessage& LogMessage::operator<<(const unsigned int& v); -template LogMessage& LogMessage::operator<<(const long& v); -template LogMessage& LogMessage::operator<<(const unsigned long& v); -template LogMessage& LogMessage::operator<<(const long long& v); -template LogMessage& LogMessage::operator<<(const unsigned long long& v); -template LogMessage& LogMessage::operator<<(void* const& v); -template LogMessage& LogMessage::operator<<(const void* const& v); -template LogMessage& LogMessage::operator<<(const float& v); -template LogMessage& LogMessage::operator<<(const double& v); -template LogMessage& LogMessage::operator<<(const bool& v); +template void LogMessage::Stream(char v); +template void LogMessage::Stream(signed char v); +template void LogMessage::Stream(unsigned char v); +template void LogMessage::Stream(short v); +template void LogMessage::Stream(unsigned short v); +template void LogMessage::Stream(int v); +template void LogMessage::Stream(unsigned int v); +template void LogMessage::Stream(long v); +template void LogMessage::Stream(unsigned long v); +template void LogMessage::Stream(long long v); +template void LogMessage::Stream(unsigned long long v); +template void LogMessage::Stream(void* absl_nullable v); +template void LogMessage::Stream(const void* absl_nullable v); +template void LogMessage::Stream(float v); +template void LogMessage::Stream(double v); +template void LogMessage::Stream(bool v); // NOLINTEND(google-runtime-int) // NOLINTEND(runtime/int) @@ -632,6 +609,17 @@ absl::string_view str); template void LogMessage::CopyToEncodedBuffer< LogMessage::StringType::kNotLiteral>(absl::string_view str); + +template <LogMessage::StringType str_type> +ABSL_ATTRIBUTE_NOINLINE void LogMessage::CopyToEncodedBuffer( + const std::string& str) { + CopyToEncodedBuffer<str_type>(absl::string_view(str)); +} +template void LogMessage::CopyToEncodedBuffer<LogMessage::StringType::kLiteral>( + const std::string& str); +template void LogMessage::CopyToEncodedBuffer< + LogMessage::StringType::kNotLiteral>(const std::string& str); + template <LogMessage::StringType str_type> ABSL_ATTRIBUTE_NOINLINE void LogMessage::CopyToEncodedBuffer(char ch, size_t num) {
diff --git a/absl/log/internal/log_message.h b/absl/log/internal/log_message.h index cd12833..4e2e729 100644 --- a/absl/log/internal/log_message.h +++ b/absl/log/internal/log_message.h
@@ -85,17 +85,28 @@ LogMessage& operator=(const LogMessage&) = delete; ABSL_ATTRIBUTE_COLD ~LogMessage(); + // Methods that return `*this` are inline wrappers around out-of-line void + // helpers so the compiler knows the returned reference aliases `this`. + // Overrides the location inferred from the callsite. The string pointed to // by `file` must be valid until the end of the statement. - LogMessage& AtLocation(absl::string_view file, int line); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& AtLocation(absl::string_view file, + int line) { + AtLocationImpl(file, line); + return *this; + } // `loc` doesn't default to `absl::SourceLocation::current()` here since the // callsite is already the default location for `LOG` statements. - LogMessage& AtLocation(absl::SourceLocation loc) { + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& AtLocation( + absl::SourceLocation loc) { return AtLocation(loc.file_name(), static_cast<int>(loc.line())); } // Omits the prefix from this line. The prefix includes metadata about the // logged data such as source code location and timestamp. - LogMessage& NoPrefix(); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& NoPrefix() { + NoPrefixImpl(); + return *this; + } // Sets the verbosity field of the logged message as if it was logged by // `VLOG(verbose_level)`. Unlike `VLOG`, this method does not affect // evaluation of the statement when the specified `verbose_level` has been @@ -103,74 +114,135 @@ // make use of the `absl::LogSink::verbosity()` value. The value // `absl::LogEntry::kNoVerbosityLevel` can be specified to mark the message // not verbose. - LogMessage& WithVerbosity(int verbose_level); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& WithVerbosity(int verbose_level) { + WithVerbosityImpl(verbose_level); + return *this; + } // Uses the specified timestamp instead of one collected in the constructor. - LogMessage& WithTimestamp(absl::Time timestamp); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& WithTimestamp(absl::Time timestamp) { + WithTimestampImpl(timestamp); + return *this; + } // Uses the specified thread ID instead of one collected in the constructor. - LogMessage& WithThreadID(absl::LogEntry::tid_t tid); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& WithThreadID( + absl::LogEntry::tid_t tid) { + WithThreadIDImpl(tid); + return *this; + } // Copies all metadata (but no data) from the specified `absl::LogEntry`. - LogMessage& WithMetadataFrom(const absl::LogEntry& entry); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& WithMetadataFrom( + const absl::LogEntry& entry) { + WithMetadataFromImpl(entry); + return *this; + } // Appends to the logged message a colon, a space, a textual description of // the current value of `errno` (as by strerror(3)), and the numerical value // of `errno`. - LogMessage& WithPerror(); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& WithPerror() { + WithPerrorImpl(); + return *this; + } // Sends this message to `*sink` in addition to whatever other sinks it would // otherwise have been sent to. - LogMessage& ToSinkAlso(absl::LogSink* absl_nonnull sink); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& ToSinkAlso( + absl::LogSink* absl_nonnull sink) { + ToSinkAlsoImpl(sink); + return *this; + } // Sends this message to `*sink` and no others. - LogMessage& ToSinkOnly(absl::LogSink* absl_nonnull sink); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& ToSinkOnly( + absl::LogSink* absl_nonnull sink) { + ToSinkOnlyImpl(sink); + return *this; + } // Don't call this method from outside this library. - LogMessage& InternalStream() { return *this; } + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& InternalStream() { return *this; } // By-value overloads for small, common types let us overlook common failures // to define globals and static data members (i.e. in a .cc file). + // Values are passed by value to `Stream` so they stay in registers. // NOLINTBEGIN(runtime/int) // NOLINTBEGIN(google-runtime-int) // clang-format off: The CUDA toolchain cannot handle these <<<'s - LogMessage& operator<<(char v) { return operator<< <char>(v); } - LogMessage& operator<<(signed char v) { return operator<< <signed char>(v); } - LogMessage& operator<<(unsigned char v) { - return operator<< <unsigned char>(v); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(char v) { + Stream(v); + return *this; } - LogMessage& operator<<(signed short v) { - return operator<< <signed short>(v); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(signed char v) { + Stream(v); + return *this; } - LogMessage& operator<<(signed int v) { return operator<< <signed int>(v); } - LogMessage& operator<<(signed long v) { - return operator<< <signed long>(v); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(unsigned char v) { + Stream(v); + return *this; } - LogMessage& operator<<(signed long long v) { - return operator<< <signed long long>(v); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(signed short v) { + Stream(v); + return *this; } - LogMessage& operator<<(unsigned short v) { - return operator<< <unsigned short>(v); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(signed int v) { + Stream(v); + return *this; } - LogMessage& operator<<(unsigned int v) { - return operator<< <unsigned int>(v); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(signed long v) { + Stream(v); + return *this; } - LogMessage& operator<<(unsigned long v) { - return operator<< <unsigned long>(v); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(signed long long v) { + Stream(v); + return *this; } - LogMessage& operator<<(unsigned long long v) { - return operator<< <unsigned long long>(v); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(unsigned short v) { + Stream(v); + return *this; } - LogMessage& operator<<(void* absl_nullable v) { - return operator<< <void*>(v); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(unsigned int v) { + Stream(v); + return *this; } - LogMessage& operator<<(const void* absl_nullable v) { - return operator<< <const void*>(v); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(unsigned long v) { + Stream(v); + return *this; } - LogMessage& operator<<(float v) { return operator<< <float>(v); } - LogMessage& operator<<(double v) { return operator<< <double>(v); } - LogMessage& operator<<(bool v) { return operator<< <bool>(v); } + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(unsigned long long v) { + Stream(v); + return *this; + } + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(void* absl_nullable v) { + Stream(v); + return *this; + } + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<( + const void* absl_nullable v) { + Stream(v); + return *this; + } + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(float v) { + Stream(v); + return *this; + } + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(double v) { + Stream(v); + return *this; + } + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(bool v) { + Stream(v); + return *this; + } // clang-format on // NOLINTEND(google-runtime-int) // NOLINTEND(runtime/int) // These overloads are more efficient since no `ostream` is involved. - LogMessage& operator<<(const std::string& v); - LogMessage& operator<<(absl::string_view v); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(const std::string& v) { + CopyToEncodedBuffer<StringType::kNotLiteral>(v); + return *this; + } + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(absl::string_view v) { + CopyToEncodedBuffer<StringType::kNotLiteral>(v); + return *this; + } // Wide string overloads (since std::ostream does not provide them). LogMessage& operator<<(const std::wstring& v); @@ -216,7 +288,7 @@ // Types that don't support `AbslStringify()` but do support streaming into a // `std::ostream&` are serialized that way. template <typename T> - ABSL_ATTRIBUTE_NOINLINE LogMessage& operator<<(const T& v); + ABSL_ATTRIBUTE_ALWAYS_INLINE LogMessage& operator<<(const T& v); // Dispatches the completed `absl::LogEntry` to applicable `absl::LogSink`s. void Flush(); @@ -266,12 +338,28 @@ absl::Span<char> string_start_; }; + void AtLocationImpl(absl::string_view file, int line); + void NoPrefixImpl(); + void WithVerbosityImpl(int verbose_level); + void WithTimestampImpl(absl::Time timestamp); + void WithThreadIDImpl(absl::LogEntry::tid_t tid); + void WithMetadataFromImpl(const absl::LogEntry& entry); + void WithPerrorImpl(); + void ToSinkAlsoImpl(absl::LogSink* absl_nonnull sink); + void ToSinkOnlyImpl(absl::LogSink* absl_nonnull sink); + + template <typename T> + ABSL_ATTRIBUTE_NOINLINE void Stream(T v); + enum class StringType { kLiteral, kNotLiteral, }; template <StringType str_type> void CopyToEncodedBuffer(absl::string_view str); + // Keeps std::string data and size access out of callsites. + template <StringType str_type> + void CopyToEncodedBuffer(const std::string& str); template <StringType str_type> void CopyToEncodedBuffer(char ch, size_t num); template <StringType str_type> @@ -345,23 +433,31 @@ LogMessage& message_; }; +template <typename T> +inline LogMessage& LogMessage::operator<<(const T& v) { + Stream<const T&>(v); + return *this; +} + // Note: the following is declared `ABSL_ATTRIBUTE_NOINLINE` template <typename T> -LogMessage& LogMessage::operator<<(const T& v) { - if constexpr (absl::HasAbslStringify<T>::value) { +void LogMessage::Stream(T v) { + // `T` may be `const U&` (from the generic `operator<<`); strip `&` and + // `const` (preserving `volatile`) so trait and `NullGuard` lookups see `U`. + using RawT = std::remove_const_t<std::remove_reference_t<T>>; + if constexpr (absl::HasAbslStringify<RawT>::value) { StringifySink sink(*this); // Replace with public API. AbslStringify(sink, v); } else { OstreamView view(*data_); - view.stream() << log_internal::NullGuard<T>().Guard(v); + view.stream() << log_internal::NullGuard<RawT>().Guard(v); } - return *this; } template <int SIZE> LogMessage& LogMessage::operator<<(const char (&buf)[SIZE]) { - CopyToEncodedBuffer<StringType::kLiteral>(buf); + CopyToEncodedBuffer<StringType::kLiteral>(absl::string_view(buf)); return *this; } @@ -374,7 +470,7 @@ // Note: the following is declared `ABSL_ATTRIBUTE_NOINLINE` template <int SIZE> LogMessage& LogMessage::operator<<(char (&buf)[SIZE]) { - CopyToEncodedBuffer<StringType::kNotLiteral>(buf); + CopyToEncodedBuffer<StringType::kNotLiteral>(absl::string_view(buf)); return *this; } // We instantiate these specializations in the library's TU to save space in @@ -382,24 +478,22 @@ // emitting a function call either way. // NOLINTBEGIN(runtime/int) // NOLINTBEGIN(google-runtime-int) -extern template LogMessage& LogMessage::operator<<(const char& v); -extern template LogMessage& LogMessage::operator<<(const signed char& v); -extern template LogMessage& LogMessage::operator<<(const unsigned char& v); -extern template LogMessage& LogMessage::operator<<(const short& v); -extern template LogMessage& LogMessage::operator<<(const unsigned short& v); -extern template LogMessage& LogMessage::operator<<(const int& v); -extern template LogMessage& LogMessage::operator<<(const unsigned int& v); -extern template LogMessage& LogMessage::operator<<(const long& v); -extern template LogMessage& LogMessage::operator<<(const unsigned long& v); -extern template LogMessage& LogMessage::operator<<(const long long& v); -extern template LogMessage& LogMessage::operator<<(const unsigned long long& v); -extern template LogMessage& LogMessage::operator<<( - void* absl_nullable const& v); -extern template LogMessage& LogMessage::operator<<( - const void* absl_nullable const& v); -extern template LogMessage& LogMessage::operator<<(const float& v); -extern template LogMessage& LogMessage::operator<<(const double& v); -extern template LogMessage& LogMessage::operator<<(const bool& v); +extern template void LogMessage::Stream(char v); +extern template void LogMessage::Stream(signed char v); +extern template void LogMessage::Stream(unsigned char v); +extern template void LogMessage::Stream(short v); +extern template void LogMessage::Stream(unsigned short v); +extern template void LogMessage::Stream(int v); +extern template void LogMessage::Stream(unsigned int v); +extern template void LogMessage::Stream(long v); +extern template void LogMessage::Stream(unsigned long v); +extern template void LogMessage::Stream(long long v); +extern template void LogMessage::Stream(unsigned long long v); +extern template void LogMessage::Stream(void* absl_nullable v); +extern template void LogMessage::Stream(const void* absl_nullable v); +extern template void LogMessage::Stream(float v); +extern template void LogMessage::Stream(double v); +extern template void LogMessage::Stream(bool v); // NOLINTEND(google-runtime-int) // NOLINTEND(runtime/int) @@ -407,6 +501,10 @@ LogMessage::StringType::kLiteral>(absl::string_view str); extern template void LogMessage::CopyToEncodedBuffer< LogMessage::StringType::kNotLiteral>(absl::string_view str); +extern template void LogMessage::CopyToEncodedBuffer< + LogMessage::StringType::kLiteral>(const std::string& str); +extern template void LogMessage::CopyToEncodedBuffer< + LogMessage::StringType::kNotLiteral>(const std::string& str); extern template void LogMessage::CopyToEncodedBuffer<LogMessage::StringType::kLiteral>(char ch, size_t num);
diff --git a/absl/log/internal/vlog_config.cc b/absl/log/internal/vlog_config.cc index 79eb7df..304aca4 100644 --- a/absl/log/internal/vlog_config.cc +++ b/absl/log/internal/vlog_config.cc
@@ -64,23 +64,21 @@ } // namespace -bool VLogSite::SlowIsEnabled(int stale_v, int level) { +bool VLogSite::SlowIsEnabled(int level) { + int stale_v = v_.load(std::memory_order_relaxed); if (ABSL_PREDICT_TRUE(stale_v != kUninitialized)) { - // Because of the prerequisites to this function, we know that stale_v is - // either uninitialized or >= level. If it's not uninitialized, that means - // it must be >= level, thus we should log. - return true; + return stale_v >= level; } stale_v = log_internal::RegisterAndInitialize(this); return ABSL_PREDICT_FALSE(stale_v >= level); } -bool VLogSite::SlowIsEnabled0(int stale_v) { return SlowIsEnabled(stale_v, 0); } -bool VLogSite::SlowIsEnabled1(int stale_v) { return SlowIsEnabled(stale_v, 1); } -bool VLogSite::SlowIsEnabled2(int stale_v) { return SlowIsEnabled(stale_v, 2); } -bool VLogSite::SlowIsEnabled3(int stale_v) { return SlowIsEnabled(stale_v, 3); } -bool VLogSite::SlowIsEnabled4(int stale_v) { return SlowIsEnabled(stale_v, 4); } -bool VLogSite::SlowIsEnabled5(int stale_v) { return SlowIsEnabled(stale_v, 5); } +bool VLogSite::SlowIsEnabled0() { return SlowIsEnabled(0); } +bool VLogSite::SlowIsEnabled1() { return SlowIsEnabled(1); } +bool VLogSite::SlowIsEnabled2() { return SlowIsEnabled(2); } +bool VLogSite::SlowIsEnabled3() { return SlowIsEnabled(3); } +bool VLogSite::SlowIsEnabled4() { return SlowIsEnabled(4); } +bool VLogSite::SlowIsEnabled5() { return SlowIsEnabled(5); } namespace { struct VModuleInfo final {
diff --git a/absl/log/internal/vlog_config.h b/absl/log/internal/vlog_config.h index f65eb5d..0761b2c 100644 --- a/absl/log/internal/vlog_config.h +++ b/absl/log/internal/vlog_config.h
@@ -17,7 +17,8 @@ // ----------------------------------------------------------------------------- // // This header file defines `VLogSite`, a public primitive that represents -// a callsite for the `VLOG` family of macros and related libraries. +// the `--vmodule` state of a source file for the `VLOG` family of macros and +// related libraries. // It also declares and defines multiple internal utilities used to implement // `VLOG`, such as `VLogSiteManager`. @@ -27,10 +28,12 @@ // IWYU pragma: private, include "absl/log/log.h" #include <atomic> +#include <cstddef> #include <cstdint> #include <functional> #include <limits> #include <type_traits> +#include <utility> #include "absl/base/attributes.h" #include "absl/base/config.h" @@ -49,19 +52,21 @@ int RegisterAndInitialize(VLogSite* absl_nonnull v); void UpdateVLogSites(); -// Represents a unique callsite for a `VLOG()` or `VLOG_IS_ON()` call. +// Represents the `--vmodule` state for a source file. // -// Libraries that provide `VLOG`-like functionality should use this to -// efficiently handle --vmodule. +// When the file name is known at the callsite (`__FILE__`), prefer +// `VLOG_IS_ON(level)` so all callsites in the same file share a single +// `VLogSite`. Construct `VLogSite` directly only when the file name is +// determined at runtime (e.g. from `absl::SourceLocation` or language +// bindings). // -// VLogSite objects must not be destroyed until the program exits. Doing so will -// probably yield nasty segfaults in VLogSiteManager::UpdateLogSites(). The -// recommendation is to make all such objects function-local statics. +// `VLogSite` objects must not be destroyed until the program exits; doing so +// will corrupt the global `VLogSite` list in `UpdateVLogSites()`. class VLogSite final { public: // `f` must not be destroyed until the program exits. explicit constexpr VLogSite(const char* absl_nonnull f) - : file_(f), v_(kUninitialized), next_(nullptr) {} + : v_(kUninitialized), file_(f), next_(nullptr) {} VLogSite(const VLogSite&) = delete; VLogSite& operator=(const VLogSite&) = delete; @@ -81,15 +86,15 @@ // of code space by special-casing for a few common levels. #if ABSL_HAVE_BUILTIN(__builtin_constant_p) || defined(__GNUC__) if (__builtin_constant_p(level)) { - if (level == 0) return SlowIsEnabled0(stale_v); - if (level == 1) return SlowIsEnabled1(stale_v); - if (level == 2) return SlowIsEnabled2(stale_v); - if (level == 3) return SlowIsEnabled3(stale_v); - if (level == 4) return SlowIsEnabled4(stale_v); - if (level == 5) return SlowIsEnabled5(stale_v); + if (level == 0) return SlowIsEnabled0(); + if (level == 1) return SlowIsEnabled1(); + if (level == 2) return SlowIsEnabled2(); + if (level == 3) return SlowIsEnabled3(); + if (level == 4) return SlowIsEnabled4(); + if (level == 5) return SlowIsEnabled5(); } #endif - return SlowIsEnabled(stale_v, level); + return SlowIsEnabled(level); } private: @@ -99,30 +104,67 @@ static constexpr int kUninitialized = (std::numeric_limits<int>::max)(); // SlowIsEnabled performs slower checks to determine whether a log site is - // enabled. Because it is expected to be called somewhat rarely - // (comparatively), it is not inlined to save on code size. + // enabled, registering and initializing the site if needed. Because it is + // expected to be called somewhat rarely (comparatively), it is not inlined to + // save on code size. // - // Prerequisites to calling SlowIsEnabled: - // 1) stale_v is uninitialized OR - // 2) stale_v is initialized and >= level (meaning we must log). // Takes locks but does not allocate memory. - ABSL_ATTRIBUTE_NOINLINE - bool SlowIsEnabled(int stale_v, int level); - ABSL_ATTRIBUTE_NOINLINE bool SlowIsEnabled0(int stale_v); - ABSL_ATTRIBUTE_NOINLINE bool SlowIsEnabled1(int stale_v); - ABSL_ATTRIBUTE_NOINLINE bool SlowIsEnabled2(int stale_v); - ABSL_ATTRIBUTE_NOINLINE bool SlowIsEnabled3(int stale_v); - ABSL_ATTRIBUTE_NOINLINE bool SlowIsEnabled4(int stale_v); - ABSL_ATTRIBUTE_NOINLINE bool SlowIsEnabled5(int stale_v); + ABSL_ATTRIBUTE_NOINLINE bool SlowIsEnabled(int level); + ABSL_ATTRIBUTE_NOINLINE bool SlowIsEnabled0(); + ABSL_ATTRIBUTE_NOINLINE bool SlowIsEnabled1(); + ABSL_ATTRIBUTE_NOINLINE bool SlowIsEnabled2(); + ABSL_ATTRIBUTE_NOINLINE bool SlowIsEnabled3(); + ABSL_ATTRIBUTE_NOINLINE bool SlowIsEnabled4(); + ABSL_ATTRIBUTE_NOINLINE bool SlowIsEnabled5(); + // `v_` is kept at offset 0 so the fast path accesses `site` without a struct + // field displacement. // This object is too size-sensitive to use absl::string_view. - const char* absl_nonnull const file_; std::atomic<int> v_; + const char* absl_nonnull const file_; std::atomic<VLogSite*> next_; }; static_assert(std::is_trivially_destructible_v<VLogSite>, "VLogSite must be trivially destructible"); +#if ABSL_HAVE_CPP_ATTRIBUTE(gnu::visibility) +#define ABSL_LOG_INTERNAL_HIDDEN [[gnu::visibility("hidden")]] +#else +#define ABSL_LOG_INTERNAL_HIDDEN +#endif +// Prevents the x86-64 psABI from 16-byte-aligning char arrays of length >= 16. +#if ABSL_HAVE_CPP_ATTRIBUTE(gnu::aligned) +#define ABSL_LOG_INTERNAL_ALIGNED_1 [[gnu::aligned(1)]] +#else +#define ABSL_LOG_INTERNAL_ALIGNED_1 +#endif + +// TODO(b/576087803): Migrate to a C++20 class NTTP once Abseil requires C++20. +// Hidden visibility: +// 1. Keeps `site` and `kFile` out of `.dynsym`/`.dynstr` in shared libraries. +// 2. Allows direct PC-relative addressing instead of GOT indirection in PIC. +template <char... Cs> +struct ABSL_LOG_INTERNAL_HIDDEN VLogSiteHolder { + ABSL_LOG_INTERNAL_ALIGNED_1 static constexpr char kFile[sizeof...(Cs) + 1] = + {Cs..., '\0'}; + ABSL_CONST_INIT static inline VLogSite site{kFile}; +}; + +#undef ABSL_LOG_INTERNAL_ALIGNED_1 +#undef ABSL_LOG_INTERNAL_HIDDEN + +template <typename F, size_t... Is> +ABSL_ATTRIBUTE_ALWAYS_INLINE inline auto GetVLogSiteHolderImpl( + F f, std::index_sequence<Is...>) { + return VLogSiteHolder<f()[Is]...>{}; +} + +template <typename F> +ABSL_ATTRIBUTE_ALWAYS_INLINE inline auto GetVLogSiteHolder(F f) { + return GetVLogSiteHolderImpl( + f, std::make_index_sequence<absl::string_view(f()).size()>{}); +} + // Returns the current verbose log level of `file`. // Does not allocate memory. int VLogLevel(absl::string_view file);
diff --git a/absl/log/vlog_is_on.h b/absl/log/vlog_is_on.h index 67c6fb3..7ecd6fa 100644 --- a/absl/log/vlog_is_on.h +++ b/absl/log/vlog_is_on.h
@@ -55,15 +55,17 @@ // Resetting --vmodule will override all previous modifications to `--vmodule`, // including via SetVLogLevel. +// SKIP_ABSL_INLINE_NAMESPACE_CHECK + #ifndef ABSL_LOG_VLOG_IS_ON_H_ #define ABSL_LOG_VLOG_IS_ON_H_ #include "absl/log/absl_vlog_is_on.h" // IWYU pragma: export -// Each VLOG_IS_ON call site gets its own VLogSite that registers with the -// global linked list of sites to asynchronously update its verbosity level on -// changes to --v or --vmodule. The verbosity can also be set by manually -// calling SetVLogLevel. +// Each source file's VLOG_IS_ON call sites share a single VLogSite that +// registers with the global linked list of sites to asynchronously update its +// verbosity level on changes to --v or --vmodule. The verbosity can also be set +// by manually calling SetVLogLevel. // // VLOG_IS_ON is not async signal safe, but it is guaranteed not to allocate // new memory.
diff --git a/absl/log/vlog_is_on_test.cc b/absl/log/vlog_is_on_test.cc index d523781..81ef7b3 100644 --- a/absl/log/vlog_is_on_test.cc +++ b/absl/log/vlog_is_on_test.cc
@@ -231,4 +231,28 @@ VLOG(4) << "dfgh"; } +// Verifies that VLOG_IS_ON callsites in the same file share a single +// VLogSite instance, while callsites in different files get distinct VLogSite +// instances. +TEST_F(VLogIsOnTest, DeduplicatesVLogSitePerFile) { + if (MaxLogVerbosity().has_value() || MinLogLevel().has_value()) { + GTEST_SKIP(); + } + + using ::absl::log_internal::GetVLogSiteHolder; + // Not `decltype(GetVLogSiteHolder(...))::site`: lambdas may not appear in + // unevaluated operands before C++20. + auto* site1 = &GetVLogSiteHolder([] { return __FILE__; }).site; + auto* site2 = &GetVLogSiteHolder([] { return __FILE__; }).site; + auto* other_file_site = + &GetVLogSiteHolder([] { return "other_file.cc"; }).site; + EXPECT_EQ(site1, site2); + EXPECT_NE(site1, other_file_site); + + absl::SetVLogLevel("vlog_is_on_test", 2); + EXPECT_TRUE(VLOG_IS_ON(1)); + EXPECT_TRUE(VLOG_IS_ON(2)); + EXPECT_FALSE(VLOG_IS_ON(3)); +} + } // namespace
diff --git a/absl/profiling/internal/sample_recorder.h b/absl/profiling/internal/sample_recorder.h index 8663d6c..16f2c6e 100644 --- a/absl/profiling/internal/sample_recorder.h +++ b/absl/profiling/internal/sample_recorder.h
@@ -184,13 +184,10 @@ // preparation. } // `sample` is detached from the graveyard and will not be used in PopDead. - // SampleRecorder<T>::Iterate will acquire per sample lock, so there will be - // no data race either. - absl::MutexLock sample_lock(sample->init_mu); - // Note: consider PrepareForSampling out of the lock. - // Currently many clients have PrepareForSampling marked as - // ABSL_EXCLUSIVE_LOCKS_REQUIRED. + // SampleRecorder<T>::Iterate will only read `dead` that is still non-null. sample->PrepareForSampling(std::forward<Targs>(args)...); + // SampleRecorder<T>::Iterate acquires the same lock before access to `dead`. + absl::MutexLock sample_lock(sample->init_mu); sample->dead = nullptr; return sample; }
diff --git a/absl/random/BUILD.bazel b/absl/random/BUILD.bazel index d63f8f3..42b59d3 100644 --- a/absl/random/BUILD.bazel +++ b/absl/random/BUILD.bazel
@@ -135,7 +135,6 @@ visibility = ["//visibility:public"], deps = [ ":mocking_access", - ":random", "//absl/base:config", "//absl/base:core_headers", "//absl/base:fast_type_id",
diff --git a/absl/random/CMakeLists.txt b/absl/random/CMakeLists.txt index f9d2d60..b2c3fa2 100644 --- a/absl/random/CMakeLists.txt +++ b/absl/random/CMakeLists.txt
@@ -44,6 +44,7 @@ DEPS absl::config absl::core_headers + absl::fast_type_id absl::random_internal_fast_uniform_bits absl::random_internal_traits absl::random_mocking_access @@ -649,7 +650,7 @@ NAME random_internal_explicit_seed_seq HDRS - "internal/random_internal_explicit_seed_seq.h" + "internal/explicit_seed_seq.h" COPTS ${ABSL_DEFAULT_COPTS} LINKOPTS @@ -923,6 +924,7 @@ absl::str_format absl::string_view absl::strings + TESTONLY ) # Internal-only target, do not depend on directly.
diff --git a/absl/random/bit_gen_ref.h b/absl/random/bit_gen_ref.h index df8675b..d902114 100644 --- a/absl/random/bit_gen_ref.h +++ b/absl/random/bit_gen_ref.h
@@ -26,6 +26,7 @@ #include <cstdint> #include <limits> +#include <memory> #include <type_traits> #include "absl/base/attributes.h" @@ -76,6 +77,18 @@ template <typename T> using HasConversionOperator = detector<has_conversion_operator_t, void, T>; + // True when BitGenRef binds directly to a URBG, rather than copying + // (BitGenRef and derived types) or converting (types which provide + // `operator BitGenRef()`). + // + // The conversion operator detection allows for ref-qualification, so that + // types may prevent binding to temporaries via `operator BitGenRef() &`. + template <typename URBG> + static constexpr bool kBindsDirectly = + !std::is_same_v<URBG, BitGenRef> && !std::is_base_of_v<BitGenRef, URBG> && + !HasConversionOperator<URBG&>::value && + random_internal::is_urbg<URBG>::value; + public: BitGenRef(const BitGenRef&) = default; BitGenRef(BitGenRef&&) = default; @@ -84,27 +97,20 @@ template <typename URBGRef, typename URBG = absl::remove_cvref_t<URBGRef>, typename std::enable_if_t< - (!std::is_same_v<URBG, BitGenRef> && - !std::is_base_of_v<BitGenRef, URBG> && - !HasConversionOperator<URBG>::value && - random_internal::is_urbg<URBG>::value && - !RandomMockingAccess::HasInvokeMock<URBG>::value)>* = nullptr> + kBindsDirectly<URBG> && + !std::is_const_v<std::remove_reference_t<URBGRef>>>* = nullptr> BitGenRef(URBGRef&& gen ABSL_ATTRIBUTE_LIFETIME_BOUND) // NOLINT - : t_erased_gen_ptr_(reinterpret_cast<uintptr_t>(&gen)), - mock_call_(NotAMock), + : t_erased_gen_ptr_(std::addressof(gen)), + mock_call_(MockCallFn<URBG>()), generate_impl_fn_(ImplFn<URBG>) {} + // Generating a variate mutates the generator, so a BitGenRef may not bind to + // a const generator. template <typename URBGRef, typename URBG = absl::remove_cvref_t<URBGRef>, typename std::enable_if_t< - (!std::is_same_v<URBG, BitGenRef> && - !std::is_base_of_v<BitGenRef, URBG> && - !HasConversionOperator<URBG>::value && - random_internal::is_urbg<URBG>::value && - RandomMockingAccess::HasInvokeMock<URBG>::value)>* = nullptr> - BitGenRef(URBGRef&& gen ABSL_ATTRIBUTE_LIFETIME_BOUND) // NOLINT - : t_erased_gen_ptr_(reinterpret_cast<uintptr_t>(&gen)), - mock_call_(MockCall<URBG>), - generate_impl_fn_(ImplFn<URBG>) {} + kBindsDirectly<URBG> && + std::is_const_v<std::remove_reference_t<URBGRef>>>* = nullptr> + BitGenRef(URBGRef&& gen) = delete; // NOLINT using result_type = uint64_t; @@ -119,35 +125,41 @@ result_type operator()() { return generate_impl_fn_(t_erased_gen_ptr_); } private: - using impl_fn = result_type (*)(uintptr_t); - using mock_call_fn = bool (*)(uintptr_t, FastTypeIdType, void*, void*); + using impl_fn = result_type (*)(void*); + using mock_call_fn = bool (*)(void*, FastTypeIdType, void*, void*); template <typename URBG> - static result_type ImplFn(uintptr_t ptr) { + static result_type ImplFn(void* ptr) { // Ensure that the return values from operator() fill the entire // range promised by result_type, min() and max(). absl::random_internal::FastUniformBits<result_type> fast_uniform_bits; - return fast_uniform_bits(*reinterpret_cast<URBG*>(ptr)); + return fast_uniform_bits(*static_cast<URBG*>(ptr)); } // Get a type-erased InvokeMock pointer. template <typename URBG> - static bool MockCall(uintptr_t gen_ptr, FastTypeIdType key_id, - void* args_tuple, void* result) { - return RandomMockingAccess::InvokeMock(reinterpret_cast<URBG*>(gen_ptr), - key_id, args_tuple, result); - } - static bool NotAMock(uintptr_t, FastTypeIdType, void*, void*) { - return false; + static bool MockCall(void* gen_ptr, FastTypeIdType key_id, void* args_tuple, + void* result) { + return RandomMockingAccess::InvokeMock(static_cast<URBG*>(gen_ptr), key_id, + args_tuple, result); } - inline bool InvokeMock(FastTypeIdType key_id, void* args_tuple, - void* result) { - if (mock_call_ == NotAMock) return false; // avoids an indirect call. + // Returns MockCall<URBG> if URBG supports mocking, otherwise nullptr. + template <typename URBG> + static constexpr mock_call_fn MockCallFn() { + if constexpr (RandomMockingAccess::HasInvokeMock<URBG>::value) { + return MockCall<URBG>; + } else { + return nullptr; + } + } + + bool InvokeMock(FastTypeIdType key_id, void* args_tuple, void* result) { + if (mock_call_ == nullptr) return false; // avoids an indirect call. return mock_call_(t_erased_gen_ptr_, key_id, args_tuple, result); } - uintptr_t t_erased_gen_ptr_; + void* t_erased_gen_ptr_; mock_call_fn mock_call_; impl_fn generate_impl_fn_;
diff --git a/absl/random/bit_gen_ref_test.cc b/absl/random/bit_gen_ref_test.cc index ae5c1db..9c2ca0e 100644 --- a/absl/random/bit_gen_ref_test.cc +++ b/absl/random/bit_gen_ref_test.cc
@@ -114,13 +114,13 @@ // Implicit conversions allow passing MinStdRand to functions taking // absl::BitGenRef as well as explicitly constructing an absl::BitGenRef from // a MinStdRand. - operator absl::BitGenRef() const { + operator absl::BitGenRef() { conversion_count++; return absl::BitGenRef(minstd_gen); } std::minstd_rand minstd_gen; - mutable int conversion_count = 0; + int conversion_count = 0; }; TEST(BitGenRefTest, IsConvertibleTest) { @@ -145,6 +145,44 @@ } } +// Generating a variate mutates the generator, so binding to a const generator +// is disallowed. +static_assert(std::is_constructible_v<absl::BitGenRef, absl::BitGen&>); +static_assert(std::is_constructible_v<absl::BitGenRef, absl::BitGen&&>); +static_assert(!std::is_constructible_v<absl::BitGenRef, const absl::BitGen&>); +static_assert(!std::is_constructible_v<absl::BitGenRef, const absl::BitGen&&>); +static_assert(!std::is_constructible_v<absl::BitGenRef, const std::mt19937&>); + +// A URBG whose conversion operator is lvalue-only, which prevents binding an +// absl::BitGenRef to a temporary. +struct LvalueOnlyConversion { + using result_type = absl::BitGen::result_type; + static constexpr result_type(min)() { return (absl::BitGen::min)(); } + static constexpr result_type(max)() { return (absl::BitGen::max)(); } + result_type operator()() { return 0; } + + operator absl::BitGenRef() & { + conversion_count++; + return absl::BitGenRef(minstd_gen); + } + + std::minstd_rand minstd_gen; + int conversion_count = 0; +}; + +static_assert(std::is_convertible_v<LvalueOnlyConversion&, absl::BitGenRef>); +static_assert(!std::is_convertible_v<LvalueOnlyConversion, absl::BitGenRef>); + +TEST(BitGenRefTest, LvalueOnlyConversionIsUsed) { + // The conversion operator, rather than the URBG interface, is used. + LvalueOnlyConversion gen; + absl::BitGenRef gen_ref(gen); + EXPECT_EQ(gen.conversion_count, 1); + FnTest(gen); + EXPECT_EQ(gen.conversion_count, 2); + (void)gen_ref; +} + } // namespace ABSL_NAMESPACE_END } // namespace absl
diff --git a/absl/status/BUILD.bazel b/absl/status/BUILD.bazel index 3508b11..09060ff 100644 --- a/absl/status/BUILD.bazel +++ b/absl/status/BUILD.bazel
@@ -227,6 +227,7 @@ ":statusor", "//absl/base:config", "//absl/base:core_headers", + "//absl/meta:type_traits", "//absl/types:source_location", ], )
diff --git a/absl/status/CMakeLists.txt b/absl/status/CMakeLists.txt index 13ff4a6..5efa33b 100644 --- a/absl/status/CMakeLists.txt +++ b/absl/status/CMakeLists.txt
@@ -180,6 +180,7 @@ absl::status absl::status_builder absl::statusor + absl::type_traits PUBLIC )
diff --git a/absl/status/status.cc b/absl/status/status.cc index bb03157..bf91e90 100644 --- a/absl/status/status.cc +++ b/absl/status/status.cc
@@ -29,6 +29,7 @@ #include "absl/base/no_destructor.h" #include "absl/base/nullability.h" #include "absl/status/internal/status_internal.h" +#include "absl/status/status_payload_printer.h" #include "absl/strings/cord.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h"
diff --git a/absl/status/status_macros.h b/absl/status/status_macros.h index 965ea8e..4b1cc2b 100644 --- a/absl/status/status_macros.h +++ b/absl/status/status_macros.h
@@ -22,6 +22,7 @@ #define ABSL_STATUS_STATUS_MACROS_H_ #include <cstddef> +#include <memory> #include <string> #include <type_traits> #include <utility> @@ -29,6 +30,7 @@ #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/optimization.h" +#include "absl/meta/type_traits.h" #include "absl/status/status.h" #include "absl/status/status_builder.h" // IWYU pragma: export #include "absl/status/statusor.h" @@ -201,6 +203,61 @@ T*, typename absl::StatusOr<typename T::value_type>*>>> : std::true_type {}; +template <typename T> +class IndirectNonvirtualDestructor { + public: + ABSL_ATTRIBUTE_ALWAYS_INLINE explicit IndirectNonvirtualDestructor(T* value) + : value_(value) {} + IndirectNonvirtualDestructor(const IndirectNonvirtualDestructor&) = delete; + IndirectNonvirtualDestructor& operator=(const IndirectNonvirtualDestructor&) = + delete; + ABSL_ATTRIBUTE_ALWAYS_INLINE ~IndirectNonvirtualDestructor() { + // Qualified call suppresses virtual dispatch when `T` is polymorphic. + value_->T::~T(); + } + + private: + T* value_; +}; + +struct EmptySentinelType {}; + +// Fallback for types derived from `absl::StatusOr`. +template <typename StatusOrType> +union AssignOrReturnStorage { + static_assert(!std::is_reference_v<StatusOrType>); + StatusOrType v; + ABSL_ATTRIBUTE_ALWAYS_INLINE ~AssignOrReturnStorage() { v.~StatusOrType(); } + [[nodiscard]] ABSL_ATTRIBUTE_ALWAYS_INLINE auto DestroyValueOnExit() { + return EmptySentinelType(); + } +}; + +// Holds `absl::StatusOr<T>` in a union with a no-op destructor to suppress +// `~StatusOr()` at scope exit. On error, the caller must move the status out of +// `v` before returning. On OK, `DestroyValueOnExit()` destroys only `T` at +// scope exit. +// +// Not a `struct` with an anonymous `union`: that would break aggregate +// initialization for nontrivial `T`. +template <typename T> +union AssignOrReturnStorage<absl::StatusOr<T>> { + absl::StatusOr<T> v; + // Not `= default`, as that would delete the destructor for nontrivial `T`. + ABSL_ATTRIBUTE_ALWAYS_INLINE ~AssignOrReturnStorage() {} + + [[nodiscard]] ABSL_ATTRIBUTE_ALWAYS_INLINE auto DestroyValueOnExit() { + if constexpr (std::is_trivially_destructible_v<T>) { + return EmptySentinelType(); + } else { + return IndirectNonvirtualDestructor<T>(std::addressof(*v)); + } + } +}; + +template <typename T> +AssignOrReturnStorage(T&&) -> AssignOrReturnStorage<absl::remove_cvref_t<T>>; + } // namespace status_macro_internal ABSL_NAMESPACE_END } // namespace absl @@ -221,7 +278,8 @@ lhs, rexpr, \ return_keyword absl::Status( \ std::move(ABSL_INTERNAL_STATUS_MACROS_IMPL_CONCAT_(_status_or_value, \ - __LINE__)) \ + __LINE__) \ + .v) \ .status(), \ absl::SourceLocation::current())) @@ -232,18 +290,29 @@ lhs, rexpr, /* NOLINTNEXTLINE(misc-const-correctness) */ \ absl::StatusBuilder _( \ std::move(ABSL_INTERNAL_STATUS_MACROS_IMPL_CONCAT_(_status_or_value, \ - __LINE__)) \ + __LINE__) \ + .v) \ .status(), \ absl::SourceLocation::current()); \ (void)_; /* error_expression is allowed to not use this variable */ \ return_keyword(error_expression)) +// REQUIRES: `error_expression` must move the status out of `statusor_union.v` +// and must not fall through, since `~StatusOr()` is suppressed. #define ABSL_INTERNAL_STATUS_MACROS_IMPL_ASSIGN_OR_RETURN_( \ - statusor, lhs, rexpr, error_expression) \ - auto statusor = (rexpr); \ - if (ABSL_PREDICT_FALSE(!statusor.ok())) { \ + statusor_union, lhs, rexpr, error_expression) \ + absl::status_macro_internal::AssignOrReturnStorage statusor_union = { \ + (rexpr)}; \ + static_assert( \ + !std::is_const_v<decltype(statusor_union)>, \ + "Do not const-qualify ABSL_ASSIGN_OR_RETURN; put const on the lhs"); \ + if (ABSL_PREDICT_FALSE(!statusor_union.v.ok())) { \ error_expression; \ } \ + /* Declared before `lhs` so `statusor_union.v`'s value outlives `lhs` \ + * (e.g. when `lhs` is a view into the contained value). */ \ + [[maybe_unused]] const auto ABSL_INTERNAL_STATUS_MACROS_IMPL_CONCAT_( \ + statusor_union, _destroyer) = statusor_union.DestroyValueOnExit(); \ { \ static_assert(!HasPotentialConditionalOperator(#lhs, sizeof(#lhs) - 1), \ "Identified potential conditional operator, consider not " \ @@ -252,11 +321,11 @@ { \ static_assert( \ absl::status_macro_internal::IsAllowedStatusOrMacroType< \ - std::remove_const_t<decltype(statusor)>>(), \ + decltype(statusor_union.v)>(), \ "ABSL_ASSIGN_OR_RETURN should only be used with absl::StatusOr<>"); \ } \ ABSL_INTERNAL_STATUS_MACROS_IMPL_UNPARENTHESIZE_IF_PARENTHESIZED(lhs) = \ - (*std::move(statusor)) + (*std::move(statusor_union.v)) // Internal helpers for macro expansion. #define ABSL_INTERNAL_STATUS_MACROS_IMPL_EAT(...)
diff --git a/absl/status/status_macros_test.cc b/absl/status/status_macros_test.cc index 7b5751d..e5578b4 100644 --- a/absl/status/status_macros_test.cc +++ b/absl/status/status_macros_test.cc
@@ -400,6 +400,71 @@ CheckSourceLocation(result.status(), {func3_line, func4_line}); } +TEST(AssignOrReturn, DestroysValueOnlyOnOkAtScopeExit) { + int live = 0; + struct Counted { + int* live; + explicit Counted(int* l) : live(l) { ++*live; } + Counted(const Counted& o) : live(o.live) { ++*live; } + Counted(Counted&& o) : live(o.live) { ++*live; } + Counted& operator=(const Counted&) = delete; + Counted& operator=(Counted&&) = delete; + ~Counted() { --*live; } + }; + + const std::string kLong(64, 'x'); + auto ok_fn = [&]() -> absl::Status { + ABSL_ASSIGN_OR_RETURN(Counted c [[maybe_unused]], + absl::StatusOr<Counted>(Counted(&live))); + // Both `c` and the moved-from value in the macro's hidden `StatusOr` stay + // alive until scope exit (so views like `view` below remain valid). + EXPECT_EQ(live, 2); + ABSL_ASSIGN_OR_RETURN(absl::string_view view, + absl::StatusOr<std::string>(kLong)); + EXPECT_EQ(view, kLong); + ABSL_ASSIGN_OR_RETURN(std::string const_str, + absl::StatusOr<const std::string>(kLong)); + EXPECT_EQ(const_str, kLong); + return absl::OkStatus(); + }; + EXPECT_EQ(ok_fn(), absl::OkStatus()); + EXPECT_EQ(live, 0); + + auto err_fn = [&]() -> absl::Status { + ABSL_ASSIGN_OR_RETURN(Counted c [[maybe_unused]], + absl::StatusOr<Counted>(ReturnError("EXPECTED"))); + return absl::OkStatus(); + }; + EXPECT_THAT(err_fn().message(), Eq("EXPECTED")); + EXPECT_EQ(live, 0); +} + +TEST(AssignOrReturn, WorksWithStatusOrSubclass) { + struct DerivedStatusOr : absl::StatusOr<std::string> { + using absl::StatusOr<std::string>::StatusOr; + }; + const std::string kLong(64, 'y'); + auto fn = [&]() -> absl::Status { + ABSL_ASSIGN_OR_RETURN(std::string s, DerivedStatusOr(kLong)); + EXPECT_EQ(s, kLong); + ABSL_ASSIGN_OR_RETURN(s, DerivedStatusOr(ReturnError("EXPECTED"))); + return absl::OkStatus(); + }; + EXPECT_THAT(fn().message(), Eq("EXPECTED")); +} + +TEST(AssignOrReturn, WorksWithArrayReference) { + int arr[2] = {10, 20}; + auto fn = [&]() -> absl::Status { + ABSL_ASSIGN_OR_RETURN(auto& ref, absl::StatusOr<int(&)[2]>(arr)); + static_assert(std::is_same_v<decltype(ref), int(&)[2]>); + EXPECT_EQ(ref[0], 10); + EXPECT_EQ(ref[1], 20); + return absl::OkStatus(); + }; + EXPECT_EQ(fn(), absl::OkStatus()); +} + TEST(ReturnIfError, Works) { auto func = []() -> absl::Status { ABSL_RETURN_IF_ERROR(ReturnOk());
diff --git a/absl/strings/cord.cc b/absl/strings/cord.cc index f9f576a..5d6727f 100644 --- a/absl/strings/cord.cc +++ b/absl/strings/cord.cc
@@ -302,6 +302,12 @@ // -------------------------------------------------------------------- // Constructors and destructors +Cord::Cord(const Cord&) = default; + +Cord& Cord::operator=(const Cord&) = default; + +Cord& Cord::operator=(Cord&&) = default; + Cord::Cord(absl::string_view src, MethodIdentifier method) { const size_t n = src.size(); if (n <= InlineRep::kMaxInline) {
diff --git a/absl/strings/cord.h b/absl/strings/cord.h index 8fe8e9f..fb3b86e 100644 --- a/absl/strings/cord.h +++ b/absl/strings/cord.h
@@ -192,10 +192,10 @@ // movable. The moved-from state is valid but unspecified. // Moves need to be declared since they are otherwise inhibited via the // declaration of the destructor. - Cord(const Cord&) = default; + Cord(const Cord&); Cord(Cord&&) = default; - Cord& operator=(const Cord&) = default; - Cord& operator=(Cord&&) = default; + Cord& operator=(const Cord&); + Cord& operator=(Cord&&); // Creates a Cord from a `src` string. This constructor is marked explicit to // prevent implicit Cord constructions from arguments convertible to an
diff --git a/absl/strings/escaping.cc b/absl/strings/escaping.cc index efe9041..7338d37 100644 --- a/absl/strings/escaping.cc +++ b/absl/strings/escaping.cc
@@ -973,6 +973,8 @@ bool Base64UnescapeInternal(const char* absl_nullable src, size_t slen, String* absl_nonnull dest, const std::array<signed char, 256>& unbase64) { + ABSL_ASSERT(src != dest->data()); + // Determine the size of the output string. Base64 encodes every 3 bytes into // 4 characters. Any leftover chars are added directly for good measure. const size_t dest_len = 3 * (slen / 4) + (slen % 4);
diff --git a/absl/strings/escaping.h b/absl/strings/escaping.h index fb2de78..ee510b8 100644 --- a/absl/strings/escaping.h +++ b/absl/strings/escaping.h
@@ -154,7 +154,8 @@ // equivalent, writing it to a `dest` buffer, returning `true` on success. If // `src` contains invalid characters, `dest` is cleared and returns `false`. // If padding is included (note that `Base64Escape()` does produce it), it must -// be correct. In the padding, '=' and '.' are treated identically. +// be correct. In the padding, '=' and '.' are treated identically. `src` and +// `*dest` must not overlap. bool Base64Unescape(absl::string_view src, std::string* absl_nonnull dest); // WebSafeBase64Unescape() @@ -164,7 +165,7 @@ // success. If `src` contains invalid characters, `dest` is cleared and returns // `false`. If padding is included (note that `WebSafeBase64Escape()` does not // produce it), it must be correct. In the padding, '=' and '.' are treated -// identically. +// identically. `src` and `*dest` must not overlap. bool WebSafeBase64Unescape(absl::string_view src, std::string* absl_nonnull dest);
diff --git a/absl/strings/escaping_test.cc b/absl/strings/escaping_test.cc index e4a3868..7af9841 100644 --- a/absl/strings/escaping_test.cc +++ b/absl/strings/escaping_test.cc
@@ -706,6 +706,28 @@ EXPECT_EQ(huge, unescaped); } +#if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST +TEST(Base64DeathTest, InPlaceUnescape) { + { + std::string s; + EXPECT_DEATH(absl::Base64Unescape(s, &s), ""); + EXPECT_DEATH(absl::WebSafeBase64Unescape(s, &s), ""); + } + + { + std::string s = "YWJj"; + EXPECT_DEATH(absl::Base64Unescape(s, &s), ""); + EXPECT_DEATH(absl::WebSafeBase64Unescape(s, &s), ""); + } + + { + std::string s(64, 'A'); + EXPECT_DEATH(absl::Base64Unescape(s, &s), ""); + EXPECT_DEATH(absl::WebSafeBase64Unescape(s, &s), ""); + } +} +#endif // !defined(NDEBUG) && GTEST_HAS_DEATH_TEST + TEST(Escaping, HexStringToBytesBackToHex) { std::string bytes, hex;
diff --git a/absl/synchronization/mutex.cc b/absl/synchronization/mutex.cc index d5c1a3c..d6d474a 100644 --- a/absl/synchronization/mutex.cc +++ b/absl/synchronization/mutex.cc
@@ -2475,7 +2475,9 @@ int64_t cycles_waited = (now - wake_list->waitp->contention_start_cycles); total_wait_cycles += cycles_waited; - if (max_wait_cycles == 0) max_wait_cycles = cycles_waited; + // Waiters in wake_list are not ordered by contention_start_cycles + // (e.g. due to priority queueing or LIFO requeueing). + max_wait_cycles = std::max(max_wait_cycles, cycles_waited); wake_list->waitp->contention_start_cycles = now; wake_list->waitp->should_submit_contention_data = true; }
diff --git a/absl/synchronization/mutex_test.cc b/absl/synchronization/mutex_test.cc index 50b982e..037043a 100644 --- a/absl/synchronization/mutex_test.cc +++ b/absl/synchronization/mutex_test.cc
@@ -36,6 +36,7 @@ #include "absl/random/random.h" #include "absl/synchronization/internal/create_thread_identity.h" #include "absl/synchronization/internal/thread_pool.h" +#include "absl/synchronization/notification.h" #include "absl/time/clock.h" #include "absl/time/time.h" @@ -1119,11 +1120,15 @@ absl::Mutex mu1; // used to attempt to mess up state of mu0 absl::CondVar cv; // so the condition function can be invoked from // CondVar::Wait(). + absl::Notification started; }; static bool ConditionWithAcquire(AcquireFromConditionStruct *x) { x->value++; // count times this function is called + if (x->value == 1) { + x->started.Notify(); + } if (x->value == 2 || x->value == 3) { // On the second and third invocation of this function, sleep for 100ms, // but with the side-effect of altering the state of a Mutex other than @@ -1144,6 +1149,7 @@ // wait for cond0 to become true x->mu0.LockWhen(absl::Condition(&ConditionWithAcquire, x)); x->done = true; + x->cv.Signal(); x->mu0.unlock(); } @@ -1158,10 +1164,10 @@ std::bind(&WaitForCond2, &x)); // run WaitForCond2() in a thread T // T will hang because the first invocation of ConditionWithAcquire() will // return false. - absl::SleepFor(absl::Milliseconds(500)); // allow T time to hang + x.started.WaitForNotification(); // allow T time to hang x.mu0.lock(); - x.cv.WaitWithTimeout(&x.mu0, absl::Milliseconds(500)); // wake T + x.cv.Wait(&x.mu0); // wake T // T will be woken because the Wait() will call ConditionWithAcquire() // for the second time, and it will return true.
diff --git a/absl/time/internal/cctz/include/cctz/civil_time_detail.h b/absl/time/internal/cctz/include/cctz/civil_time_detail.h index fe3b8bd..bdaafe9 100644 --- a/absl/time/internal/cctz/include/cctz/civil_time_detail.h +++ b/absl/time/internal/cctz/include/cctz/civil_time_detail.h
@@ -22,11 +22,15 @@ #include "absl/base/config.h" -// Disable constexpr support unless we are in C++14 mode. -#if __cpp_constexpr >= 201304 || (defined(_MSC_VER) && _MSC_VER >= 1910) -#define CONSTEXPR_D constexpr // data -#define CONSTEXPR_F constexpr // function -#define CONSTEXPR_M constexpr // member +#if __cpp_constexpr >= 201304L || (defined(_MSC_VER) && _MSC_VER >= 1910) +#if __cpp_inline_variables >= 201606L +#define INLINE_VAR inline +#else +#define INLINE_VAR static +#endif +#define CONSTEXPR_D INLINE_VAR constexpr // data +#define CONSTEXPR_F constexpr // function +#define CONSTEXPR_M constexpr // member #else #define CONSTEXPR_D const #define CONSTEXPR_F inline @@ -96,6 +100,11 @@ CONSTEXPR_F int days_per_year(year_t y, month_t m) noexcept { return is_leap_year(y + (m > 2)) ? 366 : 365; } + +CONSTEXPR_D int k_days_per_month[1 + 12] = { + -1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 // non leap year +}; + // The compiler cannot optimize away the check if we use // -fsanitize=array-bounds. // m is guaranteed to be in [1:12] in the caller, but the compiler cannot @@ -109,9 +118,6 @@ #endif #endif CONSTEXPR_F int days_per_month(year_t y, month_t m) noexcept { - CONSTEXPR_D int k_days_per_month[1 + 12] = { - -1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 // non leap year - }; return k_days_per_month[m] + (m == 2 && is_leap_year(y)); } @@ -554,38 +560,57 @@ sunday, }; +namespace impl { + +CONSTEXPR_D weekday k_weekday_by_mon_off[13] = { + weekday::monday, weekday::tuesday, weekday::wednesday, + weekday::thursday, weekday::friday, weekday::saturday, + weekday::sunday, weekday::monday, weekday::tuesday, + weekday::wednesday, weekday::thursday, weekday::friday, + weekday::saturday, +}; + +CONSTEXPR_D int k_weekday_offsets[1 + 12] = { + -1, 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4, +}; + +CONSTEXPR_D weekday k_weekdays_forw[14] = { + weekday::monday, weekday::tuesday, weekday::wednesday, + weekday::thursday, weekday::friday, weekday::saturday, + weekday::sunday, weekday::monday, weekday::tuesday, + weekday::wednesday, weekday::thursday, weekday::friday, + weekday::saturday, weekday::sunday, +}; + +CONSTEXPR_D weekday k_weekdays_back[14] = { + weekday::sunday, weekday::saturday, weekday::friday, + weekday::thursday, weekday::wednesday, weekday::tuesday, + weekday::monday, weekday::sunday, weekday::saturday, + weekday::friday, weekday::thursday, weekday::wednesday, + weekday::tuesday, weekday::monday, +}; + +CONSTEXPR_D int k_month_offsets[1 + 12] = { + -1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, +}; + +} // namespace impl + CONSTEXPR_F weekday get_weekday(const civil_second& cs) noexcept { - CONSTEXPR_D weekday k_weekday_by_mon_off[13] = { - weekday::monday, weekday::tuesday, weekday::wednesday, - weekday::thursday, weekday::friday, weekday::saturday, - weekday::sunday, weekday::monday, weekday::tuesday, - weekday::wednesday, weekday::thursday, weekday::friday, - weekday::saturday, - }; - CONSTEXPR_D int k_weekday_offsets[1 + 12] = { - -1, 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4, - }; year_t wd = 2400 + (cs.year() % 400) - (cs.month() < 3); wd += wd / 4 - wd / 100 + wd / 400; - wd += k_weekday_offsets[cs.month()] + cs.day(); - return k_weekday_by_mon_off[wd % 7 + 6]; + wd += impl::k_weekday_offsets[cs.month()] + cs.day(); + return impl::k_weekday_by_mon_off[wd % 7 + 6]; } //////////////////////////////////////////////////////////////////////// CONSTEXPR_F civil_day next_weekday(civil_day cd, weekday wd) noexcept { - CONSTEXPR_D weekday k_weekdays_forw[14] = { - weekday::monday, weekday::tuesday, weekday::wednesday, - weekday::thursday, weekday::friday, weekday::saturday, - weekday::sunday, weekday::monday, weekday::tuesday, - weekday::wednesday, weekday::thursday, weekday::friday, - weekday::saturday, weekday::sunday, - }; weekday base = get_weekday(cd); for (int i = 0;; ++i) { - if (base == k_weekdays_forw[i]) { + if (base == impl::k_weekdays_forw[i]) { for (int j = i + 1;; ++j) { - if (wd == k_weekdays_forw[j]) { + if (wd == impl::k_weekdays_forw[j]) { return cd + (j - i); } } @@ -594,18 +619,11 @@ } CONSTEXPR_F civil_day prev_weekday(civil_day cd, weekday wd) noexcept { - CONSTEXPR_D weekday k_weekdays_back[14] = { - weekday::sunday, weekday::saturday, weekday::friday, - weekday::thursday, weekday::wednesday, weekday::tuesday, - weekday::monday, weekday::sunday, weekday::saturday, - weekday::friday, weekday::thursday, weekday::wednesday, - weekday::tuesday, weekday::monday, - }; weekday base = get_weekday(cd); for (int i = 0;; ++i) { - if (base == k_weekdays_back[i]) { + if (base == impl::k_weekdays_back[i]) { for (int j = i + 1;; ++j) { - if (wd == k_weekdays_back[j]) { + if (wd == impl::k_weekdays_back[j]) { return cd - (j - i); } } @@ -614,11 +632,8 @@ } CONSTEXPR_F int get_yearday(const civil_second& cs) noexcept { - CONSTEXPR_D int k_month_offsets[1 + 12] = { - -1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, - }; const int feb29 = (cs.month() > 2 && impl::is_leap_year(cs.year())); - return k_month_offsets[cs.month()] + feb29 + cs.day(); + return impl::k_month_offsets[cs.month()] + feb29 + cs.day(); } //////////////////////////////////////////////////////////////////////// @@ -640,5 +655,6 @@ #undef CONSTEXPR_M #undef CONSTEXPR_F #undef CONSTEXPR_D +#undef INLINE_VAR #endif // ABSL_TIME_INTERNAL_CCTZ_CIVIL_TIME_DETAIL_H_
diff --git a/absl/time/internal/cctz/src/time_zone_lookup_test.cc b/absl/time/internal/cctz/src/time_zone_lookup_test.cc index c242bbc..db0b8d6 100644 --- a/absl/time/internal/cctz/src/time_zone_lookup_test.cc +++ b/absl/time/internal/cctz/src/time_zone_lookup_test.cc
@@ -80,7 +80,7 @@ EXPECT_EQ(ss, al.cs.second()); \ EXPECT_EQ(off, al.offset); \ EXPECT_TRUE(isdst == al.is_dst); \ - /* EXPECT_STREQ(zone, al.abbr); */ \ + EXPECT_STREQ(zone, al.abbr); \ } while (0) // These tests sometimes run on platforms that have zoneinfo data so old @@ -1205,7 +1205,6 @@ auto tp_max = time_point<absl::time_internal::cctz::seconds>::max(); ExpectTime(tp_max, tz, 292277026596, 12, 4, 10, 30, 7, -5 * 3600, false, "EST"); - EXPECT_STREQ("EST", tz.lookup(tp_max).abbr); } } // namespace cctz
diff --git a/absl/time/internal/cctz/src/tzfile.h b/absl/time/internal/cctz/src/tzfile.h index 00e75de..b2e036f 100644 --- a/absl/time/internal/cctz/src/tzfile.h +++ b/absl/time/internal/cctz/src/tzfile.h
@@ -107,9 +107,9 @@ #ifndef TZ_MAX_LEAPS /* The following limit applies to localtime.c; zic has no such limit. - The limit must be at least 27 for leap seconds from 1972 through mid-2023. - There's a plan to discontinue leap seconds by 2035. */ -#define TZ_MAX_LEAPS 50 /* Maximum number of leap second corrections */ -#endif /* !defined TZ_MAX_LEAPS */ + It must be at least 27 for all 27 historical leap seconds (1972-2016), + plus 1 for leap second table expiry as per TZif version 4. */ +#define TZ_MAX_LEAPS (27 + 1) /* Maximum number of leap second corrections */ +#endif /* !defined TZ_MAX_LEAPS */ #endif /* !defined TZFILE_H */
diff --git a/absl/time/internal/cctz/testdata/version b/absl/time/internal/cctz/testdata/version index 2c2d640..3a0e355 100644 --- a/absl/time/internal/cctz/testdata/version +++ b/absl/time/internal/cctz/testdata/version
@@ -1 +1 @@ -2026e +2026f
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Araguaina b/absl/time/internal/cctz/testdata/zoneinfo/America/Araguaina index f66c9f7..85de9f0 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Araguaina +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Araguaina Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Bahia b/absl/time/internal/cctz/testdata/zoneinfo/America/Bahia index 7969e30..b05e83c 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Bahia +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Bahia Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Belem b/absl/time/internal/cctz/testdata/zoneinfo/America/Belem index e0d7653..1caf418 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Belem +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Belem Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Boa_Vista b/absl/time/internal/cctz/testdata/zoneinfo/America/Boa_Vista index fca9720..465ccd6 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Boa_Vista +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Boa_Vista Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Campo_Grande b/absl/time/internal/cctz/testdata/zoneinfo/America/Campo_Grande index 6855e4e..5240711 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Campo_Grande +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Campo_Grande Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Cuiaba b/absl/time/internal/cctz/testdata/zoneinfo/America/Cuiaba index c09a875..bb11e3b 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Cuiaba +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Cuiaba Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Eirunepe b/absl/time/internal/cctz/testdata/zoneinfo/America/Eirunepe index 7da4b98..e2793b2 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Eirunepe +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Eirunepe Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Fortaleza b/absl/time/internal/cctz/testdata/zoneinfo/America/Fortaleza index 092e40d..d603a01 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Fortaleza +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Fortaleza Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Havana b/absl/time/internal/cctz/testdata/zoneinfo/America/Havana index e06629d..9b27e73 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Havana +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Havana Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Maceio b/absl/time/internal/cctz/testdata/zoneinfo/America/Maceio index dbb8d57..a6feff2 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Maceio +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Maceio Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Manaus b/absl/time/internal/cctz/testdata/zoneinfo/America/Manaus index 59c952e..0cccb47 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Manaus +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Manaus Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Noronha b/absl/time/internal/cctz/testdata/zoneinfo/America/Noronha index 9e74745..482a279 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Noronha +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Noronha Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Porto_Acre b/absl/time/internal/cctz/testdata/zoneinfo/America/Porto_Acre index fb5185c..3552c8c 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Porto_Acre +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Porto_Acre Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Porto_Velho b/absl/time/internal/cctz/testdata/zoneinfo/America/Porto_Velho index 7f8047d..e0afa18 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Porto_Velho +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Porto_Velho Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Recife b/absl/time/internal/cctz/testdata/zoneinfo/America/Recife index 305abcb..f555a70 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Recife +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Recife Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Rio_Branco b/absl/time/internal/cctz/testdata/zoneinfo/America/Rio_Branco index fb5185c..3552c8c 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Rio_Branco +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Rio_Branco Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Santarem b/absl/time/internal/cctz/testdata/zoneinfo/America/Santarem index f81d144..3f630f4 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Santarem +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Santarem Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/America/Sao_Paulo b/absl/time/internal/cctz/testdata/zoneinfo/America/Sao_Paulo index a16da2c..f9d3d8a 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/America/Sao_Paulo +++ b/absl/time/internal/cctz/testdata/zoneinfo/America/Sao_Paulo Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/Brazil/Acre b/absl/time/internal/cctz/testdata/zoneinfo/Brazil/Acre index fb5185c..3552c8c 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/Brazil/Acre +++ b/absl/time/internal/cctz/testdata/zoneinfo/Brazil/Acre Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/Brazil/DeNoronha b/absl/time/internal/cctz/testdata/zoneinfo/Brazil/DeNoronha index 9e74745..482a279 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/Brazil/DeNoronha +++ b/absl/time/internal/cctz/testdata/zoneinfo/Brazil/DeNoronha Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/Brazil/East b/absl/time/internal/cctz/testdata/zoneinfo/Brazil/East index a16da2c..f9d3d8a 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/Brazil/East +++ b/absl/time/internal/cctz/testdata/zoneinfo/Brazil/East Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/Brazil/West b/absl/time/internal/cctz/testdata/zoneinfo/Brazil/West index 59c952e..0cccb47 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/Brazil/West +++ b/absl/time/internal/cctz/testdata/zoneinfo/Brazil/West Binary files differ
diff --git a/absl/time/internal/cctz/testdata/zoneinfo/Cuba b/absl/time/internal/cctz/testdata/zoneinfo/Cuba index e06629d..9b27e73 100644 --- a/absl/time/internal/cctz/testdata/zoneinfo/Cuba +++ b/absl/time/internal/cctz/testdata/zoneinfo/Cuba Binary files differ
diff --git a/ci/rbe_grpc_service_config.json b/ci/rbe_grpc_service_config.json new file mode 100644 index 0000000..58dc87f --- /dev/null +++ b/ci/rbe_grpc_service_config.json
@@ -0,0 +1,8 @@ +{ + "methodConfig": [ + { + "name": [{}], + "timeout": "60s" + } + ] +}