Deduplicate type-erased SwissTable key hashing for types with identical hash implementations.

Use `CanonicalHasher` for the type-erased key hash function passed to the growth functions (as already done for the slot hash function), so that key types with identical hash implementations share one function. Small trivially copyable keys are passed by value inside the `const void*` argument to avoid spilling them to the stack.

PiperOrigin-RevId: 1011560109
diff --git a/CMake/AbseilDll.cmake b/CMake/AbseilDll.cmake
index 5b24d67..2cd40dc 100644
--- a/CMake/AbseilDll.cmake
+++ b/CMake/AbseilDll.cmake
@@ -162,6 +162,7 @@
   "hash/internal/city.h"
   "hash/internal/hash.cc"
   "hash/internal/hash.h"
+  "hash/internal/hash_key.h"
   "hash/internal/weakly_mixed_integer.h"
   "log/absl_check.h"
   "log/absl_log.h"
diff --git a/absl/container/BUILD.bazel b/absl/container/BUILD.bazel
index 7d74f26..2be85b5 100644
--- a/absl/container/BUILD.bazel
+++ b/absl/container/BUILD.bazel
@@ -442,6 +442,7 @@
         "//absl/base:config",
         "//absl/base:core_headers",
         "//absl/hash",
+        "//absl/hash:hash_key",
         "//absl/memory",
         "//absl/meta:type_traits",
         "//absl/utility",
diff --git a/absl/container/CMakeLists.txt b/absl/container/CMakeLists.txt
index c249378..2f9fcf8 100644
--- a/absl/container/CMakeLists.txt
+++ b/absl/container/CMakeLists.txt
@@ -492,6 +492,7 @@
     absl::config
     absl::core_headers
     absl::hash
+    absl::hash_key
     absl::memory
     absl::type_traits
     absl::utility
diff --git a/absl/container/internal/container_memory.h b/absl/container/internal/container_memory.h
index c821cfd..e3be242 100644
--- a/absl/container/internal/container_memory.h
+++ b/absl/container/internal/container_memory.h
@@ -28,6 +28,7 @@
 #include "absl/base/attributes.h"
 #include "absl/base/config.h"
 #include "absl/hash/hash.h"
+#include "absl/hash/internal/hash_key.h"
 #include "absl/memory/memory.h"
 #include "absl/meta/type_traits.h"
 #include "absl/utility/utility.h"
@@ -592,22 +593,37 @@
   size_t seed;
 };
 
+using HashForKeyFn = absl::hash_internal::HashForKeyFn;
+
 // No arguments function hash function for a specific key.
-template <class Hash, class Key, bool kIsAbsl, size_t kSeedShift>
+// `data()` and `get_hash_fn()` are passed to type erased functions.
+// 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(const void* data, size_t seed) {
+    const auto& self = *static_cast<const HashKey*>(data);
+    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);
-  }
+  const void* data() const { return 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>
diff --git a/absl/container/internal/container_memory_test.cc b/absl/container/internal/container_memory_test.cc
index 1bd2dde..f22f24a 100644
--- a/absl/container/internal/container_memory_test.cc
+++ b/absl/container/internal/container_memory_test.cc
@@ -388,6 +388,38 @@
                 absl::Hash<MyEnum>{}, seed)(c)));
 }
 
+TEST(HashKeyTest, CanonicalSharesHashFn) {
+  enum class MyEnum : uint32_t { kOne = 1, kTwo = 2 };
+  using HashKeyInt32 = HashKey<absl::Hash<int32_t>, int32_t, /*kIsAbsl=*/true,
+                               /*kSeedShift=*/0, /*kUseCanonical=*/true>;
+  using HashKeyEnum = HashKey<absl::Hash<MyEnum>, MyEnum, /*kIsAbsl=*/true,
+                              /*kSeedShift=*/0, /*kUseCanonical=*/true>;
+  using HashKeyNonCanonical =
+      HashKey<absl::Hash<int32_t>, int32_t, /*kIsAbsl=*/true,
+              /*kSeedShift=*/0, /*kUseCanonical=*/false>;
+  EXPECT_EQ(HashKeyInt32::get_hash_fn(), HashKeyEnum::get_hash_fn());
+  EXPECT_NE(HashKeyInt32::get_hash_fn(), HashKeyNonCanonical::get_hash_fn());
+
+  MyEnum c = MyEnum::kTwo;
+  size_t seed = 100;
+  HashKeyEnum hk{absl::Hash<MyEnum>{}, c};
+  EXPECT_EQ(HashKeyEnum::get_hash_fn()(hk.data(), 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(), &hk);
+  EXPECT_EQ(HashKeyCustom::get_hash_fn()(hk.data(), seed),
+            (HashElement<decltype(hash), /*kIsAbsl=*/false, 0>(hash, seed)(a)));
+}
+
 TEST(HashElement, DefaultHash) {
   size_t x = 7;
   size_t seed = 100;
diff --git a/absl/container/internal/raw_hash_set.cc b/absl/container/internal/raw_hash_set.cc
index 0fb3f83..60dc669 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) {
+    const void* 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) {
+                                      const void* 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,
+                               const void* 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) {
+                               const void* 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) {
+    const void* 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) {
+    const void* 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) {
+    const void* 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&, const void*, HashForKeyFn, bool);
 template void* GrowSooTableToNextCapacityAndPrepareInsert<
     OptimalMemcpySizeForSooSlotTransfer(1), true>(CommonFields&,
-                                                  const PolicyFunctions&, void*,
-                                                  HashForKeyFn, bool);
+                                                  const PolicyFunctions&,
+                                                  const void*, HashForKeyFn,
+                                                  bool);
 
 static_assert(VerifyOptimalMemcpySizeForSooSlotTransferRange(2, 3));
 template void* GrowSooTableToNextCapacityAndPrepareInsert<
     OptimalMemcpySizeForSooSlotTransfer(3), true>(CommonFields&,
-                                                  const PolicyFunctions&, void*,
-                                                  HashForKeyFn, bool);
+                                                  const PolicyFunctions&,
+                                                  const void*, 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&,
+                                                  const void*, 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 422181e..767feb0 100644
--- a/absl/container/internal/raw_hash_set.h
+++ b/absl/container/internal/raw_hash_set.h
@@ -2383,24 +2383,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,
+                                                 const void* 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,
+                               const void* hasher, HashForKeyFn get_hash);
 
 // Resizes table with allocated slots and change the table seed.
 // Tables with SOO enabled must have capacity > policy.soo_capacity.
@@ -2499,7 +2499,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);
+    const void* hasher, HashForKeyFn recompute_hash);
 
 template <typename Policy, typename Hash, typename Eq, typename Alloc>
 struct InstantiateRawHashSet {
@@ -2623,6 +2623,14 @@
   constexpr static size_t kSeedShift =
       kIsAbslHash ? 0 : HashtableInlineData::kSeedShift;
 
+  // When `kIsAbslHash` is true, `hasher` hashes `key_type` identically to
+  // `absl::Hash<key_type>` (see `GetTypeErasedApplyToSlotFn`), but may convert
+  // other lookup keys first (e.g. `const char*` for `StringHash`).
+  template <class K>
+  using HashKeyFor =
+      HashKey<hasher, absl::remove_cvref_t<K>, kIsAbslHash, kSeedShift,
+              kIsAbslHash && std::is_same_v<absl::remove_cvref_t<K>, key_type>>;
+
   constexpr static bool SooEnabled() {
     return FitsInSooSlot(sizeof(slot_type), alignof(slot_type));
   }
@@ -3968,14 +3976,14 @@
     }
     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};
   }
 
@@ -3990,10 +3998,11 @@
         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};
   }
 
@@ -4024,15 +4033,17 @@
       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);
+        void* slot;
+        if constexpr (SwisstableGenerationsEnabled()) {
+          using Hasher = HashKeyFor<K>;
+          Hasher hash_key{hash_ref(), key};
+          slot = PrepareInsertLargeGenerationsEnabled(
+              common(), GetPolicyFunctions(), hash, mask_empty,
+              target_group_offset, hash_key.data(), Hasher::get_hash_fn());
+        } else {
+          slot = PrepareInsertLarge(common(), GetPolicyFunctions(), hash,
+                                    mask_empty, target_group_offset);
+        }
         return {to_slot(slot), true};
       }
       seq.next();
@@ -4577,18 +4588,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&, const void*, HashForKeyFn, bool);
 extern template void* GrowSooTableToNextCapacityAndPrepareInsert<1, true>(
-    CommonFields&, const PolicyFunctions&, void*, HashForKeyFn,
-    bool);
+    CommonFields&, const PolicyFunctions&, const void*, HashForKeyFn, bool);
 extern template void* GrowSooTableToNextCapacityAndPrepareInsert<4, true>(
-    CommonFields&, const PolicyFunctions&, void*, HashForKeyFn,
-    bool);
+    CommonFields&, const PolicyFunctions&, const void*, HashForKeyFn, bool);
 #if UINTPTR_MAX == UINT64_MAX
 extern template void* GrowSooTableToNextCapacityAndPrepareInsert<8, true>(
-    CommonFields&, const PolicyFunctions&, void*, HashForKeyFn,
-    bool);
+    CommonFields&, const PolicyFunctions&, const void*, HashForKeyFn, bool);
 #endif
 
 extern template void
diff --git a/absl/hash/BUILD.bazel b/absl/hash/BUILD.bazel
index 50f1692..d09edb4 100644
--- a/absl/hash/BUILD.bazel
+++ b/absl/hash/BUILD.bazel
@@ -211,6 +211,37 @@
     ],
 )
 
+cc_library(
+    name = "hash_key",
+    hdrs = ["internal/hash_key.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 = "hash_key_test",
+    srcs = ["internal/hash_key_test.cc"],
+    copts = ABSL_TEST_COPTS,
+    linkopts = ABSL_DEFAULT_LINKOPTS,
+    deps = [
+        ":hash",
+        ":hash_key",
+        "//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..b999814 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
+    hash_key
+  HDRS
+    "internal/hash_key.h"
+  COPTS
+    ${ABSL_DEFAULT_COPTS}
+  DEPS
+    absl::base
+    absl::config
+    absl::hash
+    absl::type_traits
+  PUBLIC
+)
+
+absl_cc_test(
+  NAME
+    hash_key_test
+  SRCS
+    "internal/hash_key_test.cc"
+  COPTS
+    ${ABSL_TEST_COPTS}
+  DEPS
+    absl::config
+    absl::hash
+    absl::hash_key
+    absl::string_view
+    GTest::gmock_main
+)
+
 absl_cc_test(
   NAME
     low_level_hash_test
diff --git a/absl/hash/hash.h b/absl/hash/hash.h
index 28ab855..d2327ec 100644
--- a/absl/hash/hash.h
+++ b/absl/hash/hash.h
@@ -88,7 +88,7 @@
 
 #include "absl/base/config.h"
 #include "absl/functional/function_ref.h"
-#include "absl/hash/internal/hash.h"
+#include "absl/hash/internal/hash.h"  // IWYU pragma: export
 #include "absl/hash/internal/weakly_mixed_integer.h"
 #include "absl/meta/type_traits.h"
 
diff --git a/absl/hash/internal/hash.h b/absl/hash/internal/hash.h
index 8303ff9..54aa410 100644
--- a/absl/hash/internal/hash.h
+++ b/absl/hash/internal/hash.h
@@ -1621,6 +1621,30 @@
 struct Hash
     : std::conditional_t<is_hashable<T>::value, HashImpl<T>, PoisonedHash> {};
 
+// Unsigned integer type of size `N`, which must be 1, 2, 4, or 8.
+template <size_t N>
+struct UintOfSize {
+  static_assert(N == 1 || N == 2 || N == 4 || N == 8, "Unsupported size");
+};
+template <>
+struct UintOfSize<1> {
+  using type = uint8_t;
+};
+template <>
+struct UintOfSize<2> {
+  using type = uint16_t;
+};
+template <>
+struct UintOfSize<4> {
+  using type = uint32_t;
+};
+template <>
+struct UintOfSize<8> {
+  using type = uint64_t;
+};
+template <size_t N>
+using UintOfSizeT = typename UintOfSize<N>::type;
+
 // 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.
@@ -1628,11 +1652,7 @@
 constexpr auto CanonicalHasher() {
   if constexpr (is_uniquely_represented<T>::value &&
                 FitsIn64BitsPowerOf2<T>::value) {
-    constexpr size_t N = sizeof(T);
-    return Hash<std::conditional_t<
-        N == 1, uint8_t,
-        std::conditional_t<N == 2, uint16_t,
-                           std::conditional_t<N == 4, uint32_t, uint64_t>>>>();
+    return Hash<UintOfSizeT<sizeof(T)>>();
   } else {
     return Hash<T>();
   }
diff --git a/absl/hash/internal/hash_key.h b/absl/hash/internal/hash_key.h
new file mode 100644
index 0000000..5e56f56
--- /dev/null
+++ b/absl/hash/internal/hash_key.h
@@ -0,0 +1,90 @@
+// 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_HASH_KEY_H_
+#define ABSL_HASH_INTERNAL_HASH_KEY_H_
+
+#include <cstddef>
+#include <cstdint>
+#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 {
+
+using HashForKeyFn = size_t (*)(const void* hasher, size_t seed);
+
+// Returns true if `key` is passed by value inside the `const void*` argument of
+// `HashForKeyFn`, which avoids spilling it to the stack at the call site.
+template <class T>
+constexpr bool PassKeyByValueInVoidPtr() {
+  return FitsIn64BitsPowerOf2<T>::value && sizeof(T) <= sizeof(uintptr_t) &&
+         std::is_trivially_copyable_v<T>;
+}
+
+template <class T>
+const void* KeyToVoidPtr(const T& key) {
+  if constexpr (PassKeyByValueInVoidPtr<T>()) {
+    return reinterpret_cast<const void*>(
+        uintptr_t{absl::bit_cast<UintOfSizeT<sizeof(T)>>(key)});
+  } else {
+    return &key;
+  }
+}
+
+// Type erased function to apply `CanonicalHasher` to the key encoded by
+// `KeyToVoidPtr`.
+template <class CanonicalHasher>
+size_t TypeErasedApplyAbslHashToKeyFn(const void* key, size_t seed) {
+  using T = typename CanonicalHasher::KeyType;
+  if constexpr (PassKeyByValueInVoidPtr<T>()) {
+    const auto val =
+        static_cast<UintOfSizeT<sizeof(T)>>(reinterpret_cast<uintptr_t>(key));
+    return HashWithSeed().hash(CanonicalHasher(), absl::bit_cast<T>(val), seed);
+  } else {
+    return HashWithSeed().hash(CanonicalHasher(), *static_cast<const T*>(key),
+                               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>());
+
+  explicit CanonicalHashKey(const NonConstK& k) : key(k) {}
+
+  const void* data() const { return KeyToVoidPtr(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_HASH_KEY_H_
diff --git a/absl/hash/internal/hash_key_test.cc b/absl/hash/internal/hash_key_test.cc
new file mode 100644
index 0000000..acd74fe
--- /dev/null
+++ b/absl/hash/internal/hash_key_test.cc
@@ -0,0 +1,80 @@
+// 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/hash_key.h"
+
+#include <cstddef>
+#include <cstdint>
+#include <string>
+
+#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 {
+namespace {
+
+TEST(CanonicalHashKeyTest, UniquelyRepresentedTypesShareHashFn) {
+  enum class MyEnum : uint32_t { kOne = 1, kTwo = 2 };
+  int32_t a = -42;
+  uint32_t b = 2;
+  MyEnum c = MyEnum::kTwo;
+  size_t seed = 100;
+
+  using HashKeyInt32 = CanonicalHashKey<int32_t>;
+  using HashKeyUint32 = CanonicalHashKey<uint32_t>;
+  using HashKeyEnum = CanonicalHashKey<MyEnum>;
+
+  EXPECT_EQ(HashKeyInt32::get_hash_fn(), HashKeyUint32::get_hash_fn());
+  EXPECT_EQ(HashKeyInt32::get_hash_fn(), HashKeyEnum::get_hash_fn());
+  EXPECT_NE(HashKeyInt32::get_hash_fn(),
+            CanonicalHashKey<int8_t>::get_hash_fn());
+
+  HashKeyInt32 hk_int32{a};
+  HashKeyUint32 hk_uint32{b};
+  HashKeyEnum hk_enum{c};
+
+  EXPECT_EQ(HashKeyInt32::get_hash_fn()(hk_int32.data(), seed),
+            HashWithSeed().hash(absl::Hash<int32_t>{}, a, seed));
+  EXPECT_EQ(HashKeyUint32::get_hash_fn()(hk_uint32.data(), seed),
+            HashWithSeed().hash(absl::Hash<uint32_t>{}, b, seed));
+  EXPECT_EQ(HashKeyEnum::get_hash_fn()(hk_enum.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(reinterpret_cast<uintptr_t>(hk_int32.data()), 42u);
+
+  // 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(), &hk_sv.key);
+  EXPECT_NE(hk_sv.data(), &sv);
+
+  // Expensive to copy keys are stored by reference.
+  std::string s = "hello";
+  CanonicalHashKey<std::string> hk_str{s};
+  EXPECT_EQ(hk_str.data(), &s);
+}
+
+}  // namespace
+}  // namespace hash_internal
+ABSL_NAMESPACE_END
+}  // namespace absl