// Copyright 2018 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. // // An open-addressing // [https://en.wikipedia.org/wiki/Open_addressing] // hashtable with quadratic probing. // // This is a low level hashtable on top of which different interfaces can be // implemented, like flat_hash_set, node_hash_set, string_hash_set, etc. // // The table interface is similar to that of std::unordered_set. Notable // differences are that most member functions support heterogeneous keys when // BOTH the hash and eq functions are marked as transparent. They do so by // providing a typedef called `is_transparent`. // // When heterogeneous lookup is enabled, functions that take key_type act as if // they have an overload set like: // // iterator find(const key_type& key); // template // iterator find(const K& key); // // size_type erase(const key_type& key); // template // size_type erase(const K& key); // // std::pair equal_range(const key_type& key); // template // std::pair equal_range(const K& key); // // When heterogeneous lookup is disabled, only the explicit `key_type` overloads // exist. // // In addition the pointer to element and iterator stability guarantees are // weaker: all iterators and pointers are invalidated after a new element is // inserted. // // IMPLEMENTATION DETAILS // // # Table Layout // // A raw_hash_set's backing array consists of control bytes followed by slots // that may or may not contain objects. // // The layout of the backing array, for `capacity` slots, is thus, as a // pseudo-struct: // // struct BackingArray { // // Sampling handler. This field isn't present when the sampling is // // disabled or this allocation hasn't been selected for sampling. // HashtablezInfoHandle infoz_; // optional // // Additional number that can be added to growth_left_lower_bound. // // Only stored for tables with large capacities. // uint64_t growth_left_overflow; // optional // // Control bytes for the "real" slots. // ctrl_t ctrl[capacity]; // // Always `ctrl_t::kSentinel`. This is used by iterators to find when to // // stop and serves no other purpose. // ctrl_t sentinel; // // A copy of the first `kWidth - 1` elements of `ctrl`. This is used so // // that if a probe sequence picks a value near the end of `ctrl`, // // `Group` will have valid control bytes to look at. // ctrl_t clones[kWidth - 1]; // // The actual slot data. // slot_type slots[capacity]; // }; // // The length of this array is computed by `RawHashSetLayout::alloc_size` below. // // Control bytes (`ctrl_t`) are bytes (collected into groups of a // platform-specific size) that define the state of the corresponding slot in // the slot array. Group manipulation is tightly optimized to be as efficient // as possible: SSE and friends on x86, clever bit operations on other arches. // // Group 1 Group 2 Group 3 // +---------------+---------------+---------------+ // | | | | | | | | | | | | | | | | | | | | | | | | | // +---------------+---------------+---------------+ // // Each control byte is either a special value for empty slots, deleted slots // (sometimes called *tombstones*), and a special end-of-table marker used by // iterators, or, if occupied, seven bits (H2) from the hash of the value in the // corresponding slot. // // Storing control bytes in a separate array also has beneficial cache effects, // since more logical slots will fit into a cache line. // // # Small Object Optimization (SOO) // // When the size/alignment of the value_type and the capacity of the table are // small, we enable small object optimization and store the values inline in // the raw_hash_set object. This optimization allows us to avoid // allocation/deallocation as well as cache/dTLB misses. // // # Hashing // // We compute two separate hashes, `H1` and `H2`, from the hash of an object. // `H1(hash(x))` is an index into `slots`, and essentially the starting point // for the probe sequence. `H2(hash(x))` is a 7-bit value used to filter out // objects that cannot possibly be the one we are looking for. // // # Table operations. // // The key operations are `insert`, `find`, and `erase`. // // Since `insert` and `erase` are implemented in terms of `find`, we describe // `find` first. To `find` a value `x`, we compute `hash(x)`. From // `H1(hash(x))` and the capacity, we construct a `probe_seq` that visits every // group of slots in some interesting order. // // We now walk through these indices. At each index, we select the entire group // starting with that index and extract potential candidates: occupied slots // with a control byte equal to `H2(hash(x))`. If we find an empty slot in the // group, we stop and return an error. Each candidate slot `y` is compared with // `x`; if `x == y`, we are done and return `&y`; otherwise we continue to the // next probe index. Tombstones effectively behave like full slots that never // match the value we're looking for. // // The `H2` bits ensure when we compare a slot to an object with `==`, we are // likely to have actually found the object. That is, the chance is low that // `==` is called and returns `false`. Thus, when we search for an object, we // are unlikely to call `==` many times. This likelyhood can be analyzed as // follows (assuming that H2 is a random enough hash function). // // Let's assume that there are `k` "wrong" objects that must be examined in a // probe sequence. For example, when doing a `find` on an object that is in the // table, `k` is the number of objects between the start of the probe sequence // and the final found object (not including the final found object). The // expected number of objects with an H2 match is then `k/128`. Measurements // and analysis indicate that even at high load factors, `k` is less than 32, // meaning that the number of "false positive" comparisons we must perform is // less than 1/8 per `find`. // `insert` is implemented in terms of `unchecked_insert`, which inserts a // value presumed to not be in the table (violating this requirement will cause // the table to behave erratically). Given `x` and its hash `hash(x)`, to insert // it, we construct a `probe_seq` once again, and use it to find the first // group with an unoccupied (empty *or* deleted) slot. We place `x` into the // first such slot in the group and mark it as full with `x`'s H2. // // To `insert`, we compose `unchecked_insert` with `find`. We compute `h(x)` and // perform a `find` to see if it's already present; if it is, we're done. If // it's not, we may decide the table is getting overcrowded (i.e. the load // factor is greater than 7/8 for big tables; tables smaller than one probing // group use a max load factor of 1); in this case, we allocate a bigger array, // `unchecked_insert` each element of the table into the new array (we know that // no insertion here will insert an already-present value), and discard the old // backing array. At this point, we may `unchecked_insert` the value `x`. // // Below, `unchecked_insert` is partly implemented by `prepare_insert`, which // presents a viable, initialized slot pointee to the caller. // // `erase` is implemented in terms of `erase_at`, which takes an index to a // slot. Given an offset, we simply create a tombstone and destroy its contents. // If we can prove that the slot would not appear in a probe sequence, we can // make the slot as empty, instead. We can prove this by observing that if a // group has any empty slots, it has never been full (assuming we never create // an empty slot in a group with no empties, which this heuristic guarantees we // never do) and find would stop at this group anyways (since it does not probe // beyond groups with empties). // // `erase` is `erase_at` composed with `find`: if we // have a value `x`, we can perform a `find`, and then `erase_at` the resulting // slot. // // To iterate, we simply traverse the array, skipping empty and deleted slots // and stopping when we hit a `kSentinel`. #ifndef ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_ #define ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "absl/base/attributes.h" #include "absl/base/casts.h" #include "absl/base/config.h" #include "absl/base/internal/endian.h" #include "absl/base/internal/iterator_traits.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/unaligned_access.h" #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/base/options.h" #include "absl/base/port.h" #include "absl/base/prefetch.h" #include "absl/container/internal/common.h" // IWYU pragma: export // for node_handle #include "absl/container/internal/common_policy_traits.h" #include "absl/container/internal/container_memory.h" #include "absl/container/internal/hash_function_defaults.h" #include "absl/container/internal/hash_policy_traits.h" #include "absl/container/internal/hashtable_control_bytes.h" #include "absl/container/internal/hashtable_debug_hooks.h" #include "absl/container/internal/hashtablez_sampler.h" #include "absl/functional/function_ref.h" #include "absl/hash/hash.h" #include "absl/hash/internal/weakly_mixed_integer.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" #include "absl/numeric/bits.h" #include "absl/strings/string_view.h" #include "absl/utility/utility.h" #if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L #include // NOLINT(build/c++20) #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { #ifdef ABSL_SWISSTABLE_ENABLE_GENERATIONS #error ABSL_SWISSTABLE_ENABLE_GENERATIONS cannot be directly set #elif (defined(ABSL_HAVE_ADDRESS_SANITIZER) || \ defined(ABSL_HAVE_HWADDRESS_SANITIZER) || \ defined(ABSL_HAVE_MEMORY_SANITIZER)) && \ !defined(NDEBUG_SANITIZER) // If defined, performance is important. // When compiled in sanitizer mode, we add generation integers to the backing // array and iterators. In the backing array, we store the generation between // the control bytes and the slots. When iterators are dereferenced, we assert // that the container has not been mutated in a way that could cause iterator // invalidation since the iterator was initialized. #define ABSL_SWISSTABLE_ENABLE_GENERATIONS #endif #ifdef ABSL_SWISSTABLE_ASSERT #error ABSL_SWISSTABLE_ASSERT cannot be directly set #else // We use this macro for assertions that users may see when the table is in an // invalid state that sanitizers may help diagnose. #define ABSL_SWISSTABLE_ASSERT(CONDITION) \ assert((CONDITION) && "Try enabling sanitizers.") #endif // ABSL_SWISSTABLE_ASSUME_SEPARATE_STORAGE(a, b) // // Informs the compiler that the two pointer arguments point into separately // allocated storage (either different variable definitions or different dynamic // storage allocations), allowing the compiler to assume they do not alias for // optimization purposes. Differences from __restrict: // - __restrict only applies to the pointer itself, not the pointed-to object. // - This macro allows the compiler to optimize caller code, not just the // pointer dereferences of a function argument within that function. // // WARNING: If the arguments point into the same storage, the program has // undefined behavior. Note that the definition of "storage" here refers to the // outermost enclosing allocation of any particular object (for example, it is // never correct to call this macro passing the addresses of fields in the same // struct, elements of the same array, objects on the same arena block, etc.). // Note that in the example below, the annotation will affect callers of // SetFirstAndGetSize as well (they may be mis-compiled if the arguments are not // from separate allocations). // // See // https://clang.llvm.org/docs/LanguageExtensions.html#builtin-assume-separate-storage // // Example: // // class Buffer { // public: // size_t* data() { // // Safe because `data_` is allocated via `::operator new`, so it is // // guaranteed to be in a separate allocation from `*this`. // ABSL_SWISSTABLE_ASSUME_SEPARATE_STORAGE(data_, this); // return data_; // } // size_t size() const { return size_; } // // private: // size_t* data_ = new size_t[10]; // size_t size_ = 10; // }; // // size_t SetFirstAndGetSize(Buffer& buf) { // size_t n = buf.size(); // buf.data()[0] = n; // // After inlining, the compiler knows storing to `buf.data()[0]` cannot // // clobber `buf.size_`, and can return `n` without reloading `buf.size_`. // return buf.size(); // } #if ABSL_HAVE_BUILTIN(__builtin_assume_separate_storage) #define ABSL_SWISSTABLE_ASSUME_SEPARATE_STORAGE(a, b) \ __builtin_assume_separate_storage(a, b) #elif ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L #define ABSL_SWISSTABLE_ASSUME_SEPARATE_STORAGE(a, b) \ (decltype((void)(a), (void)(b))()) #else #define ABSL_SWISSTABLE_ASSUME_SEPARATE_STORAGE(a, b) \ (false ? ((void)(a), (void)(b)) : void()) #endif // We use uint8_t so we don't need to worry about padding. using GenerationType = uint8_t; // A sentinel value for empty generations. Using 0 makes it easy to constexpr // initialize an array of this value. constexpr GenerationType SentinelEmptyGeneration() { return 0; } constexpr GenerationType NextGeneration(GenerationType generation) { return ++generation == SentinelEmptyGeneration() ? ++generation : generation; } #ifdef NDEBUG inline constexpr bool kIsDebug = false; #else inline constexpr bool kIsDebug = true; #endif constexpr bool SwisstableDebugEnabled() { #if defined(ABSL_SWISSTABLE_ENABLE_GENERATIONS) || ABSL_OPTION_HARDENED == 1 return true; #else return kIsDebug; #endif } #ifdef ABSL_SWISSTABLE_ENABLE_GENERATIONS constexpr bool SwisstableGenerationsEnabled() { return true; } constexpr size_t NumGenerationBytes() { return sizeof(GenerationType); } #else constexpr bool SwisstableGenerationsEnabled() { return false; } constexpr size_t NumGenerationBytes() { return 0; } #endif constexpr bool SwisstableGenerationsOrDebugEnabled() { if constexpr (kIsDebug) { return true; } else { return SwisstableGenerationsEnabled(); } } template class Template> struct is_instance_of : std::false_type {}; template