hashing_test.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "common/hashing.h"
  5. #include <gmock/gmock.h>
  6. #include <gtest/gtest.h>
  7. #include <concepts>
  8. #include "llvm/ADT/Sequence.h"
  9. #include "llvm/ADT/StringExtras.h"
  10. #include "llvm/Support/FormatVariadic.h"
  11. #include "llvm/Support/TypeName.h"
  12. namespace Carbon {
  13. namespace {
  14. using ::testing::Eq;
  15. using ::testing::Le;
  16. using ::testing::Ne;
  17. TEST(HashingTest, HashCodeAPI) {
  18. // Manually compute a few hash codes where we can exercise the underlying API.
  19. HashCode empty = HashValue("");
  20. HashCode a = HashValue("a");
  21. HashCode b = HashValue("b");
  22. ASSERT_THAT(HashValue(""), Eq(empty));
  23. ASSERT_THAT(HashValue("a"), Eq(a));
  24. ASSERT_THAT(HashValue("b"), Eq(b));
  25. ASSERT_THAT(empty, Ne(a));
  26. ASSERT_THAT(empty, Ne(b));
  27. ASSERT_THAT(a, Ne(b));
  28. // Exercise the methods in basic ways across a few sizes. This doesn't check
  29. // much beyond stability across re-computed values, crashing, or hitting UB.
  30. EXPECT_THAT(HashValue("a").ExtractIndex(), Eq(a.ExtractIndex()));
  31. EXPECT_THAT(a.ExtractIndex(), Ne(b.ExtractIndex()));
  32. EXPECT_THAT(a.ExtractIndex(), Ne(empty.ExtractIndex()));
  33. // The tag shouldn't have bits set outside the range requested.
  34. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<1>().second & ~0b1, Eq(0));
  35. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<2>().second & ~0b11, Eq(0));
  36. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<3>().second & ~0b111, Eq(0));
  37. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<4>().second & ~0b1111, Eq(0));
  38. // Note that the index produced with a tag may be different from the index
  39. // alone!
  40. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<2>(),
  41. Eq(a.ExtractIndexAndTag<2>()));
  42. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<16>(),
  43. Eq(a.ExtractIndexAndTag<16>()));
  44. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<7>(),
  45. Eq(a.ExtractIndexAndTag<7>()));
  46. const auto [a_index, a_tag] = a.ExtractIndexAndTag<4>();
  47. const auto [b_index, b_tag] = b.ExtractIndexAndTag<4>();
  48. EXPECT_THAT(a_index, Ne(b_index));
  49. EXPECT_THAT(a_tag, Ne(b_tag));
  50. }
  51. TEST(HashingTest, Integers) {
  52. for (int64_t i : {0, 1, 2, 3, 42, -1, -2, -3, -13}) {
  53. SCOPED_TRACE(llvm::formatv("Hashing: {0}", i).str());
  54. auto test_int_hash = [](auto i) {
  55. using T = decltype(i);
  56. SCOPED_TRACE(
  57. llvm::formatv("Hashing type: {0}", llvm::getTypeName<T>()).str());
  58. HashCode hash = HashValue(i);
  59. // Hashes should be stable within the execution.
  60. EXPECT_THAT(HashValue(i), Eq(hash));
  61. // Zero should match, and other integers shouldn't collide trivially.
  62. HashCode hash_zero = HashValue(static_cast<T>(0));
  63. if (i == 0) {
  64. EXPECT_THAT(hash, Eq(hash_zero));
  65. } else {
  66. EXPECT_THAT(hash, Ne(hash_zero));
  67. }
  68. };
  69. test_int_hash(static_cast<int8_t>(i));
  70. test_int_hash(static_cast<uint8_t>(i));
  71. test_int_hash(static_cast<int16_t>(i));
  72. test_int_hash(static_cast<uint16_t>(i));
  73. test_int_hash(static_cast<int32_t>(i));
  74. test_int_hash(static_cast<uint32_t>(i));
  75. // `i` is already an int64_t variable.
  76. test_int_hash(i);
  77. test_int_hash(static_cast<uint64_t>(i));
  78. }
  79. }
  80. TEST(HashingTest, BasicSeeding) {
  81. auto unseeded_hash = HashValue(42);
  82. EXPECT_THAT(unseeded_hash, Ne(HashValue(42, 1)));
  83. EXPECT_THAT(unseeded_hash, Ne(HashValue(42, 2)));
  84. EXPECT_THAT(unseeded_hash, Ne(HashValue(42, 3)));
  85. EXPECT_THAT(unseeded_hash,
  86. Ne(HashValue(42, static_cast<uint64_t>(unseeded_hash))));
  87. }
  88. TEST(HashingTest, Pointers) {
  89. int object1 = 42;
  90. std::string object2 =
  91. "Hello World! This is a long-ish string so it ends up on the heap!";
  92. HashCode hash_null = HashValue(nullptr);
  93. // Hashes should be stable.
  94. EXPECT_THAT(HashValue(nullptr), Eq(hash_null));
  95. // Hash other kinds of pointers without trivial collisions.
  96. HashCode hash1 = HashValue(&object1);
  97. HashCode hash2 = HashValue(&object2);
  98. HashCode hash3 = HashValue(object2.data());
  99. EXPECT_THAT(hash1, Ne(hash_null));
  100. EXPECT_THAT(hash2, Ne(hash_null));
  101. EXPECT_THAT(hash3, Ne(hash_null));
  102. EXPECT_THAT(hash1, Ne(hash2));
  103. EXPECT_THAT(hash1, Ne(hash3));
  104. EXPECT_THAT(hash2, Ne(hash3));
  105. // Hash values reflect the address and not the type.
  106. EXPECT_THAT(HashValue(static_cast<void*>(nullptr)), Eq(hash_null));
  107. EXPECT_THAT(HashValue(static_cast<int*>(nullptr)), Eq(hash_null));
  108. EXPECT_THAT(HashValue(static_cast<std::string*>(nullptr)), Eq(hash_null));
  109. EXPECT_THAT(HashValue(reinterpret_cast<void*>(&object1)), Eq(hash1));
  110. EXPECT_THAT(HashValue(reinterpret_cast<int*>(&object2)), Eq(hash2));
  111. EXPECT_THAT(HashValue(reinterpret_cast<std::string*>(object2.data())),
  112. Eq(hash3));
  113. }
  114. TEST(HashingTest, PairsAndTuples) {
  115. // Note that we can't compare hash codes across arity, or in general, compare
  116. // hash codes for different types as the type isn't part of the hash. These
  117. // hashes are targeted at use in hash tables which pick a single type that's
  118. // the basis of any comparison.
  119. HashCode hash_00 = HashValue(std::pair(0, 0));
  120. HashCode hash_01 = HashValue(std::pair(0, 1));
  121. HashCode hash_10 = HashValue(std::pair(1, 0));
  122. HashCode hash_11 = HashValue(std::pair(1, 1));
  123. EXPECT_THAT(hash_00, Ne(hash_01));
  124. EXPECT_THAT(hash_00, Ne(hash_10));
  125. EXPECT_THAT(hash_00, Ne(hash_11));
  126. EXPECT_THAT(hash_01, Ne(hash_10));
  127. EXPECT_THAT(hash_01, Ne(hash_11));
  128. EXPECT_THAT(hash_10, Ne(hash_11));
  129. HashCode hash_000 = HashValue(std::tuple(0, 0, 0));
  130. HashCode hash_001 = HashValue(std::tuple(0, 0, 1));
  131. HashCode hash_010 = HashValue(std::tuple(0, 1, 0));
  132. HashCode hash_011 = HashValue(std::tuple(0, 1, 1));
  133. HashCode hash_100 = HashValue(std::tuple(1, 0, 0));
  134. HashCode hash_101 = HashValue(std::tuple(1, 0, 1));
  135. HashCode hash_110 = HashValue(std::tuple(1, 1, 0));
  136. HashCode hash_111 = HashValue(std::tuple(1, 1, 1));
  137. EXPECT_THAT(hash_000, Ne(hash_001));
  138. EXPECT_THAT(hash_000, Ne(hash_010));
  139. EXPECT_THAT(hash_000, Ne(hash_011));
  140. EXPECT_THAT(hash_000, Ne(hash_100));
  141. EXPECT_THAT(hash_000, Ne(hash_101));
  142. EXPECT_THAT(hash_000, Ne(hash_110));
  143. EXPECT_THAT(hash_000, Ne(hash_111));
  144. EXPECT_THAT(hash_001, Ne(hash_010));
  145. EXPECT_THAT(hash_001, Ne(hash_011));
  146. EXPECT_THAT(hash_001, Ne(hash_100));
  147. EXPECT_THAT(hash_001, Ne(hash_101));
  148. EXPECT_THAT(hash_001, Ne(hash_110));
  149. EXPECT_THAT(hash_001, Ne(hash_111));
  150. EXPECT_THAT(hash_010, Ne(hash_011));
  151. EXPECT_THAT(hash_010, Ne(hash_100));
  152. EXPECT_THAT(hash_010, Ne(hash_101));
  153. EXPECT_THAT(hash_010, Ne(hash_110));
  154. EXPECT_THAT(hash_010, Ne(hash_111));
  155. EXPECT_THAT(hash_011, Ne(hash_100));
  156. EXPECT_THAT(hash_011, Ne(hash_101));
  157. EXPECT_THAT(hash_011, Ne(hash_110));
  158. EXPECT_THAT(hash_011, Ne(hash_111));
  159. EXPECT_THAT(hash_100, Ne(hash_101));
  160. EXPECT_THAT(hash_100, Ne(hash_110));
  161. EXPECT_THAT(hash_100, Ne(hash_111));
  162. EXPECT_THAT(hash_101, Ne(hash_110));
  163. EXPECT_THAT(hash_101, Ne(hash_111));
  164. EXPECT_THAT(hash_110, Ne(hash_111));
  165. // Hashing a 2-tuple and a pair should produce identical results, so pairs
  166. // are compatible with code using things like variadic tuple construction.
  167. EXPECT_THAT(HashValue(std::tuple(0, 0)), Eq(hash_00));
  168. EXPECT_THAT(HashValue(std::tuple(0, 1)), Eq(hash_01));
  169. EXPECT_THAT(HashValue(std::tuple(1, 0)), Eq(hash_10));
  170. EXPECT_THAT(HashValue(std::tuple(1, 1)), Eq(hash_11));
  171. // Integers in tuples should also work.
  172. for (int i : {0, 1, 2, 3, 42, -1, -2, -3, -13}) {
  173. SCOPED_TRACE(llvm::formatv("Hashing: ({0}, {0}, {0})", i).str());
  174. auto test_int_tuple_hash = [](auto i) {
  175. using T = decltype(i);
  176. SCOPED_TRACE(
  177. llvm::formatv("Hashing integer type: {0}", llvm::getTypeName<T>())
  178. .str());
  179. std::tuple v = {i, i, i};
  180. HashCode hash = HashValue(v);
  181. // Hashes should be stable within the execution.
  182. EXPECT_THAT(HashValue(v), Eq(hash));
  183. // Zero should match, and other integers shouldn't collide trivially.
  184. T zero = 0;
  185. std::tuple zero_tuple = {zero, zero, zero};
  186. HashCode hash_zero = HashValue(zero_tuple);
  187. if (i == 0) {
  188. EXPECT_THAT(hash, Eq(hash_zero));
  189. } else {
  190. EXPECT_THAT(hash, Ne(hash_zero));
  191. }
  192. };
  193. test_int_tuple_hash(i);
  194. test_int_tuple_hash(static_cast<int8_t>(i));
  195. test_int_tuple_hash(static_cast<uint8_t>(i));
  196. test_int_tuple_hash(static_cast<int16_t>(i));
  197. test_int_tuple_hash(static_cast<uint16_t>(i));
  198. test_int_tuple_hash(static_cast<int32_t>(i));
  199. test_int_tuple_hash(static_cast<uint32_t>(i));
  200. test_int_tuple_hash(static_cast<int64_t>(i));
  201. test_int_tuple_hash(static_cast<uint64_t>(i));
  202. // Heterogeneous integer types should also work, but we only support
  203. // comparing against hashes of tuples with the exact same type.
  204. using T1 = std::tuple<int8_t, uint32_t, int16_t>;
  205. using T2 = std::tuple<uint32_t, int16_t, uint64_t>;
  206. if (i == 0) {
  207. EXPECT_THAT(HashValue(T1{i, i, i}), Eq(HashValue(T1{0, 0, 0})));
  208. EXPECT_THAT(HashValue(T2{i, i, i}), Eq(HashValue(T2{0, 0, 0})));
  209. } else {
  210. EXPECT_THAT(HashValue(T1{i, i, i}), Ne(HashValue(T1{0, 0, 0})));
  211. EXPECT_THAT(HashValue(T2{i, i, i}), Ne(HashValue(T2{0, 0, 0})));
  212. }
  213. }
  214. // Hash values of pointers in pairs and tuples reflect the address and not the
  215. // type. Pairs and 2-tuples give the same hash values.
  216. HashCode hash_2null = HashValue(std::pair(nullptr, nullptr));
  217. EXPECT_THAT(HashValue(std::tuple(static_cast<int*>(nullptr),
  218. static_cast<double*>(nullptr))),
  219. Eq(hash_2null));
  220. // Hash other kinds of pointers without trivial collisions.
  221. int object1 = 42;
  222. std::string object2 = "Hello world!";
  223. HashCode hash_3ptr =
  224. HashValue(std::tuple(&object1, &object2, object2.data()));
  225. EXPECT_THAT(hash_3ptr, Ne(HashValue(std::tuple(nullptr, nullptr, nullptr))));
  226. // Hash values reflect the address and not the type.
  227. EXPECT_THAT(
  228. HashValue(std::tuple(reinterpret_cast<void*>(&object1),
  229. reinterpret_cast<int*>(&object2),
  230. reinterpret_cast<std::string*>(object2.data()))),
  231. Eq(hash_3ptr));
  232. }
  233. TEST(HashingTest, BasicStrings) {
  234. llvm::SmallVector<std::pair<std::string, HashCode>> hashes;
  235. for (int size : {0, 1, 2, 4, 16, 64, 256, 1024}) {
  236. std::string s(size, 'a');
  237. hashes.push_back({s, HashValue(s)});
  238. }
  239. for (const auto& [s1, hash1] : hashes) {
  240. EXPECT_THAT(HashValue(s1), Eq(hash1));
  241. // Also check that we get the same hashes even when using string-wrapping
  242. // types.
  243. EXPECT_THAT(HashValue(std::string_view(s1)), Eq(hash1));
  244. EXPECT_THAT(HashValue(llvm::StringRef(s1)), Eq(hash1));
  245. // And some basic tests that simple things don't collide.
  246. for (const auto& [s2, hash2] : hashes) {
  247. if (s1 != s2) {
  248. EXPECT_THAT(hash1, Ne(hash2))
  249. << "Matching hashes for '" << s1 << "' and '" << s2 << "'";
  250. }
  251. }
  252. }
  253. }
  254. struct HashableType {
  255. int x;
  256. int y;
  257. int ignored = 0;
  258. // See common/hashing.h.
  259. friend auto CarbonHashValue(const HashableType& value, uint64_t seed)
  260. -> HashCode {
  261. Hasher hasher(seed);
  262. hasher.Hash(value.x, value.y);
  263. return static_cast<HashCode>(hasher);
  264. }
  265. };
  266. TEST(HashingTest, CustomType) {
  267. HashableType a = {.x = 1, .y = 2};
  268. HashableType b = {.x = 3, .y = 4};
  269. EXPECT_THAT(HashValue(a), Eq(HashValue(a)));
  270. EXPECT_THAT(HashValue(a), Ne(HashValue(b)));
  271. // Differences in an ignored field have no impact.
  272. HashableType c = {.x = 3, .y = 4, .ignored = 42};
  273. EXPECT_THAT(HashValue(c), Eq(HashValue(b)));
  274. }
  275. // The only significantly bad seed is zero, so pick a non-zero seed with a tiny
  276. // amount of entropy to make sure that none of the testing relies on the entropy
  277. // from this.
  278. constexpr uint64_t TestSeed = 42ULL * 1024;
  279. auto ToHexBytes(llvm::StringRef s) -> std::string {
  280. std::string rendered;
  281. llvm::raw_string_ostream os(rendered);
  282. os << "{";
  283. llvm::ListSeparator sep(", ");
  284. for (const char c : s) {
  285. os << sep << llvm::formatv("{0:x2}", static_cast<uint8_t>(c));
  286. }
  287. os << "}";
  288. return rendered;
  289. }
  290. template <typename T>
  291. struct HashedValue {
  292. HashCode hash;
  293. T v;
  294. };
  295. using HashedString = HashedValue<std::string>;
  296. template <typename T>
  297. auto PrintFullWidthHex(llvm::raw_ostream& os, T value) {
  298. static_assert(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 ||
  299. sizeof(T) == 8);
  300. // Given the nature of a format string and the good formatting, a nested
  301. // conditional seems like the most readable structure.
  302. // NOLINTBEGIN(readability-avoid-nested-conditional-operator)
  303. os << llvm::formatv(sizeof(T) == 1 ? "{0:x2}"
  304. : sizeof(T) == 2 ? "{0:x4}"
  305. : sizeof(T) == 4 ? "{0:x8}"
  306. : "{0:x16}",
  307. static_cast<uint64_t>(value));
  308. // NOLINTEND(readability-avoid-nested-conditional-operator)
  309. }
  310. template <typename T>
  311. requires std::integral<T>
  312. auto operator<<(llvm::raw_ostream& os, HashedValue<T> hv)
  313. -> llvm::raw_ostream& {
  314. os << "hash " << hv.hash << " for value ";
  315. PrintFullWidthHex(os, hv.v);
  316. return os;
  317. }
  318. template <typename T, typename U>
  319. requires std::integral<T> && std::integral<U>
  320. auto operator<<(llvm::raw_ostream& os, HashedValue<std::pair<T, U>> hv)
  321. -> llvm::raw_ostream& {
  322. os << "hash " << hv.hash << " for pair of ";
  323. PrintFullWidthHex(os, hv.v.first);
  324. os << " and ";
  325. PrintFullWidthHex(os, hv.v.second);
  326. return os;
  327. }
  328. struct Collisions {
  329. int total;
  330. int median;
  331. int max;
  332. };
  333. // Analyzes a list of hashed values to find all of the hash codes which collide
  334. // within a specific bit-range.
  335. //
  336. // With `BitBegin=0` and `BitEnd=64`, this is equivalent to finding full
  337. // collisions. But when the begin and end of the bit range are narrower than the
  338. // 64-bits of the hash code, it allows this function to analyze a specific
  339. // window of bits within the 64-bit hash code to understand how many collisions
  340. // emerge purely within that bit range.
  341. //
  342. // With narrow ranges (we often look at the first N and last N bits for small
  343. // N), collisions are common and so this function summarizes this with the total
  344. // number of collisions and the median number of collisions for an input value.
  345. template <int BitBegin, int BitEnd, typename T>
  346. auto FindBitRangeCollisions(llvm::ArrayRef<HashedValue<T>> hashes)
  347. -> Collisions {
  348. static_assert(BitBegin < BitEnd);
  349. constexpr int BitCount = BitEnd - BitBegin;
  350. static_assert(BitCount <= 32);
  351. constexpr int BitShift = BitBegin;
  352. constexpr uint64_t BitMask = ((1ULL << BitCount) - 1) << BitShift;
  353. // We collect counts of collisions in a vector. Initially, we just have a zero
  354. // and all inputs map to that collision count. As we discover collisions,
  355. // we'll create a dedicated counter for it and count how many inputs collide.
  356. llvm::SmallVector<int> collision_counts;
  357. collision_counts.push_back(0);
  358. // The "map" for collision counts. Each input hashed value has a corresponding
  359. // index stored here. That index is the index of the collision count in the
  360. // container above. We resize this to fill it with zeros to start as the zero
  361. // index above has a collision count of zero.
  362. //
  363. // The result of this is that the number of collisions for `hashes[i]` is
  364. // `collision_counts[collision_map[i]]`.
  365. llvm::SmallVector<int> collision_map;
  366. collision_map.resize(hashes.size());
  367. // First, we extract the bit subsequence we want to examine from each hash and
  368. // store it with an index back into the hashed values (or the collision map).
  369. //
  370. // The result is that, `bits_and_indices[i].bits` has the hash bits of
  371. // interest from `hashes[bits_and_indices[i].index]`.
  372. //
  373. // And because `collision_map` above uses the same indices as `hashes`,
  374. // `collision_counts[collision_map[bits_and_indices[i].index]]` is the number
  375. // of collisions for `bits_and_indices[i].bits`.
  376. struct BitSequenceAndHashIndex {
  377. // The bit subsequence of a hash input, adjusted into the low bits.
  378. uint32_t bits;
  379. // The index of the hash input corresponding to this bit sequence.
  380. int index;
  381. };
  382. llvm::SmallVector<BitSequenceAndHashIndex> bits_and_indices;
  383. bits_and_indices.reserve(hashes.size());
  384. for (const auto& [hash, v] : hashes) {
  385. CARBON_DCHECK(v == hashes[bits_and_indices.size()].v);
  386. auto hash_bits = (static_cast<uint64_t>(hash) & BitMask) >> BitShift;
  387. bits_and_indices.push_back(
  388. {.bits = static_cast<uint32_t>(hash_bits),
  389. .index = static_cast<int>(bits_and_indices.size())});
  390. }
  391. // Now we sort by the extracted bit sequence so we can efficiently scan for
  392. // colliding bit patterns.
  393. std::sort(
  394. bits_and_indices.begin(), bits_and_indices.end(),
  395. [](const auto& lhs, const auto& rhs) { return lhs.bits < rhs.bits; });
  396. // Scan the sorted bit sequences we've extracted looking for collisions. We
  397. // count the total collisions, but we also track the number of individual
  398. // inputs that collide with each specific bit pattern.
  399. uint32_t prev_hash_bits = bits_and_indices[0].bits;
  400. int prev_index = bits_and_indices[0].index;
  401. bool in_collision = false;
  402. int total = 0;
  403. for (const auto& [hash_bits, hash_index] :
  404. llvm::ArrayRef(bits_and_indices).slice(1)) {
  405. // Check if we've found a new hash (and thus a new value), reset everything.
  406. CARBON_CHECK(hashes[prev_index].v != hashes[hash_index].v);
  407. if (hash_bits != prev_hash_bits) {
  408. CARBON_CHECK(hashes[prev_index].hash != hashes[hash_index].hash);
  409. prev_hash_bits = hash_bits;
  410. prev_index = hash_index;
  411. in_collision = false;
  412. continue;
  413. }
  414. // Otherwise, we have a colliding bit sequence.
  415. ++total;
  416. // If we've already created a collision count to track this, just increment
  417. // it and map this hash to it.
  418. if (in_collision) {
  419. ++collision_counts.back();
  420. collision_map[hash_index] = collision_counts.size() - 1;
  421. continue;
  422. }
  423. // If this is a new collision, create a dedicated count to track it and
  424. // begin counting.
  425. in_collision = true;
  426. collision_map[prev_index] = collision_counts.size();
  427. collision_map[hash_index] = collision_counts.size();
  428. collision_counts.push_back(1);
  429. }
  430. // Sort by collision count for each hash.
  431. std::sort(bits_and_indices.begin(), bits_and_indices.end(),
  432. [&](const auto& lhs, const auto& rhs) {
  433. return collision_counts[collision_map[lhs.index]] <
  434. collision_counts[collision_map[rhs.index]];
  435. });
  436. // And compute the median and max.
  437. int median = collision_counts
  438. [collision_map[bits_and_indices[bits_and_indices.size() / 2].index]];
  439. int max = *std::max_element(collision_counts.begin(), collision_counts.end());
  440. CARBON_CHECK(max ==
  441. collision_counts[collision_map[bits_and_indices.back().index]]);
  442. return {.total = total, .median = median, .max = max};
  443. }
  444. auto CheckNoDuplicateValues(llvm::ArrayRef<HashedString> hashes) -> void {
  445. for (int i = 0, size = hashes.size(); i < size - 1; ++i) {
  446. const auto& [_, value] = hashes[i];
  447. CARBON_CHECK(value != hashes[i + 1].v) << "Duplicate value: " << value;
  448. }
  449. }
  450. template <int N>
  451. auto AllByteStringsHashedAndSorted() {
  452. static_assert(N < 5, "Can only generate all 4-byte strings or shorter.");
  453. llvm::SmallVector<HashedString> hashes;
  454. int64_t count = 1LL << (N * 8);
  455. for (int64_t i : llvm::seq(count)) {
  456. uint8_t bytes[N];
  457. for (int j : llvm::seq(N)) {
  458. bytes[j] = (static_cast<uint64_t>(i) >> (8 * j)) & 0xff;
  459. }
  460. std::string s(std::begin(bytes), std::end(bytes));
  461. hashes.push_back({HashValue(s, TestSeed), s});
  462. }
  463. std::sort(hashes.begin(), hashes.end(),
  464. [](const HashedString& lhs, const HashedString& rhs) {
  465. return static_cast<uint64_t>(lhs.hash) <
  466. static_cast<uint64_t>(rhs.hash);
  467. });
  468. CheckNoDuplicateValues(hashes);
  469. return hashes;
  470. }
  471. auto ExpectNoHashCollisions(llvm::ArrayRef<HashedString> hashes) -> void {
  472. HashCode prev_hash = hashes[0].hash;
  473. llvm::StringRef prev_s = hashes[0].v;
  474. for (const auto& [hash, s] : hashes.slice(1)) {
  475. if (hash != prev_hash) {
  476. prev_hash = hash;
  477. prev_s = s;
  478. continue;
  479. }
  480. FAIL() << "Colliding hash '" << hash << "' of strings "
  481. << ToHexBytes(prev_s) << " and " << ToHexBytes(s);
  482. }
  483. }
  484. TEST(HashingTest, Collisions1ByteSized) {
  485. auto hashes_storage = AllByteStringsHashedAndSorted<1>();
  486. auto hashes = llvm::ArrayRef(hashes_storage);
  487. ExpectNoHashCollisions(hashes);
  488. auto low_32bit_collisions = FindBitRangeCollisions<0, 32>(hashes);
  489. EXPECT_THAT(low_32bit_collisions.total, Eq(0));
  490. auto high_32bit_collisions = FindBitRangeCollisions<32, 64>(hashes);
  491. EXPECT_THAT(high_32bit_collisions.total, Eq(0));
  492. // We expect collisions when only looking at 7-bits of the hash. However,
  493. // modern hash table designs need to use either the low or high 7 bits as tags
  494. // for faster searching. So we add some direct testing that the median and max
  495. // collisions for any given key stay within bounds. We express the bounds in
  496. // terms of the minimum expected "perfect" rate of collisions if uniformly
  497. // distributed.
  498. int min_7bit_collisions = llvm::NextPowerOf2(hashes.size() - 1) / (1 << 7);
  499. auto low_7bit_collisions = FindBitRangeCollisions<0, 7>(hashes);
  500. EXPECT_THAT(low_7bit_collisions.median, Le(8 * min_7bit_collisions));
  501. EXPECT_THAT(low_7bit_collisions.max, Le(8 * min_7bit_collisions));
  502. auto high_7bit_collisions = FindBitRangeCollisions<64 - 7, 64>(hashes);
  503. EXPECT_THAT(high_7bit_collisions.median, Le(2 * min_7bit_collisions));
  504. EXPECT_THAT(high_7bit_collisions.max, Le(4 * min_7bit_collisions));
  505. }
  506. TEST(HashingTest, Collisions2ByteSized) {
  507. auto hashes_storage = AllByteStringsHashedAndSorted<2>();
  508. auto hashes = llvm::ArrayRef(hashes_storage);
  509. ExpectNoHashCollisions(hashes);
  510. auto low_32bit_collisions = FindBitRangeCollisions<0, 32>(hashes);
  511. EXPECT_THAT(low_32bit_collisions.total, Eq(0));
  512. auto high_32bit_collisions = FindBitRangeCollisions<32, 64>(hashes);
  513. EXPECT_THAT(high_32bit_collisions.total, Eq(0));
  514. // Similar to 1-byte keys, we do expect a certain rate of collisions here but
  515. // bound the median and max.
  516. int min_7bit_collisions = llvm::NextPowerOf2(hashes.size() - 1) / (1 << 7);
  517. auto low_7bit_collisions = FindBitRangeCollisions<0, 7>(hashes);
  518. EXPECT_THAT(low_7bit_collisions.median, Le(2 * min_7bit_collisions));
  519. EXPECT_THAT(low_7bit_collisions.max, Le(2 * min_7bit_collisions));
  520. auto high_7bit_collisions = FindBitRangeCollisions<64 - 7, 64>(hashes);
  521. EXPECT_THAT(high_7bit_collisions.median, Le(2 * min_7bit_collisions));
  522. EXPECT_THAT(high_7bit_collisions.max, Le(2 * min_7bit_collisions));
  523. }
  524. // Generate and hash all strings of of [BeginByteCount, EndByteCount) bytes,
  525. // with [BeginSetBitCount, EndSetBitCount) contiguous bits at each possible bit
  526. // offset set to one and all other bits set to zero.
  527. template <int BeginByteCount, int EndByteCount, int BeginSetBitCount,
  528. int EndSetBitCount>
  529. struct SparseHashTestParamRanges {
  530. static_assert(BeginByteCount >= 0);
  531. static_assert(BeginByteCount < EndByteCount);
  532. static_assert(BeginSetBitCount >= 0);
  533. static_assert(BeginSetBitCount < EndSetBitCount);
  534. // Note that we intentionally allow the end-set-bit-count to result in more
  535. // set bits than are available -- we truncate the number of set bits to fit
  536. // within the byte string.
  537. static_assert(BeginSetBitCount <= BeginByteCount * 8);
  538. struct ByteCount {
  539. static constexpr int Begin = BeginByteCount;
  540. static constexpr int End = EndByteCount;
  541. };
  542. struct SetBitCount {
  543. static constexpr int Begin = BeginSetBitCount;
  544. static constexpr int End = EndSetBitCount;
  545. };
  546. };
  547. template <typename ParamRanges>
  548. struct SparseHashTest : ::testing::Test {
  549. using ByteCount = typename ParamRanges::ByteCount;
  550. using SetBitCount = typename ParamRanges::SetBitCount;
  551. static auto GetHashedByteStrings() {
  552. llvm::SmallVector<HashedString> hashes;
  553. for (int byte_count :
  554. llvm::seq_inclusive(ByteCount::Begin, ByteCount::End)) {
  555. int bits = byte_count * 8;
  556. for (int set_bit_count : llvm::seq_inclusive(
  557. SetBitCount::Begin, std::min(bits, SetBitCount::End))) {
  558. if (set_bit_count == 0) {
  559. std::string s(byte_count, '\0');
  560. hashes.push_back({HashValue(s, TestSeed), std::move(s)});
  561. continue;
  562. }
  563. for (int begin_set_bit : llvm::seq_inclusive(0, bits - set_bit_count)) {
  564. std::string s(byte_count, '\0');
  565. int begin_set_bit_byte_index = begin_set_bit / 8;
  566. int begin_set_bit_bit_index = begin_set_bit % 8;
  567. int end_set_bit_byte_index = (begin_set_bit + set_bit_count) / 8;
  568. int end_set_bit_bit_index = (begin_set_bit + set_bit_count) % 8;
  569. // We build a begin byte and end byte. We set the begin byte, set
  570. // subsequent bytes up to *and including* the end byte to all ones,
  571. // and then mask the end byte. For multi-byte runs, the mask just sets
  572. // the end byte and for single-byte runs the mask computes the
  573. // intersecting bits.
  574. //
  575. // Consider a 4-set-bit count, starting at bit 2. The begin bit index
  576. // is 2, and the end bit index is 6.
  577. //
  578. // Begin byte: 0b11111111 -(shl 2)-----> 0b11111100
  579. // End byte: 0b11111111 -(shr (8-6))-> 0b00111111
  580. // Masked byte: 0b00111100
  581. //
  582. // Or a 10-set-bit-count starting at bit 2. The begin bit index is 2,
  583. // the end byte index is (12 / 8) or 1, and the end bit index is (12 %
  584. // 8) or 4.
  585. //
  586. // Begin byte: 0b11111111 -(shl 2)-----> 0b11111100 -> 6 bits
  587. // End byte: 0b11111111 -(shr (8-4))-> 0b00001111 -> 4 bits
  588. // 10 total bits
  589. //
  590. uint8_t begin_set_bit_byte = 0xFFU << begin_set_bit_bit_index;
  591. uint8_t end_set_bit_byte = 0xFFU >> (8 - end_set_bit_bit_index);
  592. bool has_end_byte_bits = end_set_bit_byte != 0;
  593. s[begin_set_bit_byte_index] = begin_set_bit_byte;
  594. for (int i : llvm::seq(begin_set_bit_byte_index + 1,
  595. end_set_bit_byte_index + has_end_byte_bits)) {
  596. s[i] = '\xFF';
  597. }
  598. // If there are no bits set in the end byte, it may be past-the-end
  599. // and we can't even mask a zero byte safely.
  600. if (has_end_byte_bits) {
  601. s[end_set_bit_byte_index] &= end_set_bit_byte;
  602. }
  603. hashes.push_back({HashValue(s, TestSeed), std::move(s)});
  604. }
  605. }
  606. }
  607. std::sort(hashes.begin(), hashes.end(),
  608. [](const HashedString& lhs, const HashedString& rhs) {
  609. return static_cast<uint64_t>(lhs.hash) <
  610. static_cast<uint64_t>(rhs.hash);
  611. });
  612. CheckNoDuplicateValues(hashes);
  613. return hashes;
  614. }
  615. };
  616. using SparseHashTestParams = ::testing::Types<
  617. SparseHashTestParamRanges</*BeginByteCount=*/0, /*EndByteCount=*/256,
  618. /*BeginSetBitCount=*/0, /*EndSetBitCount=*/1>,
  619. SparseHashTestParamRanges</*BeginByteCount=*/1, /*EndByteCount=*/128,
  620. /*BeginSetBitCount=*/2, /*EndSetBitCount=*/4>,
  621. SparseHashTestParamRanges</*BeginByteCount=*/1, /*EndByteCount=*/64,
  622. /*BeginSetBitCount=*/4, /*EndSetBitCount=*/16>>;
  623. TYPED_TEST_SUITE(SparseHashTest, SparseHashTestParams);
  624. TYPED_TEST(SparseHashTest, Collisions) {
  625. auto hashes_storage = this->GetHashedByteStrings();
  626. auto hashes = llvm::ArrayRef(hashes_storage);
  627. ExpectNoHashCollisions(hashes);
  628. int min_7bit_collisions = llvm::NextPowerOf2(hashes.size() - 1) / (1 << 7);
  629. auto low_7bit_collisions = FindBitRangeCollisions<0, 7>(hashes);
  630. EXPECT_THAT(low_7bit_collisions.median, Le(2 * min_7bit_collisions));
  631. EXPECT_THAT(low_7bit_collisions.max, Le(2 * min_7bit_collisions));
  632. auto high_7bit_collisions = FindBitRangeCollisions<64 - 7, 64>(hashes);
  633. EXPECT_THAT(high_7bit_collisions.median, Le(2 * min_7bit_collisions));
  634. EXPECT_THAT(high_7bit_collisions.max, Le(2 * min_7bit_collisions));
  635. }
  636. } // namespace
  637. } // namespace Carbon