LLVM API Documentation

Hashing.h
Go to the documentation of this file.
00001 //===-- llvm/ADT/Hashing.h - Utilities for hashing --------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the newly proposed standard C++ interfaces for hashing
00011 // arbitrary data and building hash functions for user-defined types. This
00012 // interface was originally proposed in N3333[1] and is currently under review
00013 // for inclusion in a future TR and/or standard.
00014 //
00015 // The primary interfaces provide are comprised of one type and three functions:
00016 //
00017 //  -- 'hash_code' class is an opaque type representing the hash code for some
00018 //     data. It is the intended product of hashing, and can be used to implement
00019 //     hash tables, checksumming, and other common uses of hashes. It is not an
00020 //     integer type (although it can be converted to one) because it is risky
00021 //     to assume much about the internals of a hash_code. In particular, each
00022 //     execution of the program has a high probability of producing a different
00023 //     hash_code for a given input. Thus their values are not stable to save or
00024 //     persist, and should only be used during the execution for the
00025 //     construction of hashing datastructures.
00026 //
00027 //  -- 'hash_value' is a function designed to be overloaded for each
00028 //     user-defined type which wishes to be used within a hashing context. It
00029 //     should be overloaded within the user-defined type's namespace and found
00030 //     via ADL. Overloads for primitive types are provided by this library.
00031 //
00032 //  -- 'hash_combine' and 'hash_combine_range' are functions designed to aid
00033 //      programmers in easily and intuitively combining a set of data into
00034 //      a single hash_code for their object. They should only logically be used
00035 //      within the implementation of a 'hash_value' routine or similar context.
00036 //
00037 // Note that 'hash_combine_range' contains very special logic for hashing
00038 // a contiguous array of integers or pointers. This logic is *extremely* fast,
00039 // on a modern Intel "Gainestown" Xeon (Nehalem uarch) @2.2 GHz, these were
00040 // benchmarked at over 6.5 GiB/s for large keys, and <20 cycles/hash for keys
00041 // under 32-bytes.
00042 //
00043 //===----------------------------------------------------------------------===//
00044 
00045 #ifndef LLVM_ADT_HASHING_H
00046 #define LLVM_ADT_HASHING_H
00047 
00048 #include "llvm/Support/DataTypes.h"
00049 #include "llvm/Support/Host.h"
00050 #include "llvm/Support/SwapByteOrder.h"
00051 #include "llvm/Support/type_traits.h"
00052 #include <algorithm>
00053 #include <cassert>
00054 #include <cstring>
00055 #include <iterator>
00056 #include <utility>
00057 
00058 namespace llvm {
00059 
00060 /// \brief An opaque object representing a hash code.
00061 ///
00062 /// This object represents the result of hashing some entity. It is intended to
00063 /// be used to implement hashtables or other hashing-based data structures.
00064 /// While it wraps and exposes a numeric value, this value should not be
00065 /// trusted to be stable or predictable across processes or executions.
00066 ///
00067 /// In order to obtain the hash_code for an object 'x':
00068 /// \code
00069 ///   using llvm::hash_value;
00070 ///   llvm::hash_code code = hash_value(x);
00071 /// \endcode
00072 class hash_code {
00073   size_t value;
00074 
00075 public:
00076   /// \brief Default construct a hash_code.
00077   /// Note that this leaves the value uninitialized.
00078   hash_code() {}
00079 
00080   /// \brief Form a hash code directly from a numerical value.
00081   hash_code(size_t value) : value(value) {}
00082 
00083   /// \brief Convert the hash code to its numerical value for use.
00084   /*explicit*/ operator size_t() const { return value; }
00085 
00086   friend bool operator==(const hash_code &lhs, const hash_code &rhs) {
00087     return lhs.value == rhs.value;
00088   }
00089   friend bool operator!=(const hash_code &lhs, const hash_code &rhs) {
00090     return lhs.value != rhs.value;
00091   }
00092 
00093   /// \brief Allow a hash_code to be directly run through hash_value.
00094   friend size_t hash_value(const hash_code &code) { return code.value; }
00095 };
00096 
00097 /// \brief Compute a hash_code for any integer value.
00098 ///
00099 /// Note that this function is intended to compute the same hash_code for
00100 /// a particular value without regard to the pre-promotion type. This is in
00101 /// contrast to hash_combine which may produce different hash_codes for
00102 /// differing argument types even if they would implicit promote to a common
00103 /// type without changing the value.
00104 template <typename T>
00105 typename std::enable_if<is_integral_or_enum<T>::value, hash_code>::type
00106 hash_value(T value);
00107 
00108 /// \brief Compute a hash_code for a pointer's address.
00109 ///
00110 /// N.B.: This hashes the *address*. Not the value and not the type.
00111 template <typename T> hash_code hash_value(const T *ptr);
00112 
00113 /// \brief Compute a hash_code for a pair of objects.
00114 template <typename T, typename U>
00115 hash_code hash_value(const std::pair<T, U> &arg);
00116 
00117 /// \brief Compute a hash_code for a standard string.
00118 template <typename T>
00119 hash_code hash_value(const std::basic_string<T> &arg);
00120 
00121 
00122 /// \brief Override the execution seed with a fixed value.
00123 ///
00124 /// This hashing library uses a per-execution seed designed to change on each
00125 /// run with high probability in order to ensure that the hash codes are not
00126 /// attackable and to ensure that output which is intended to be stable does
00127 /// not rely on the particulars of the hash codes produced.
00128 ///
00129 /// That said, there are use cases where it is important to be able to
00130 /// reproduce *exactly* a specific behavior. To that end, we provide a function
00131 /// which will forcibly set the seed to a fixed value. This must be done at the
00132 /// start of the program, before any hashes are computed. Also, it cannot be
00133 /// undone. This makes it thread-hostile and very hard to use outside of
00134 /// immediately on start of a simple program designed for reproducible
00135 /// behavior.
00136 void set_fixed_execution_hash_seed(size_t fixed_value);
00137 
00138 
00139 // All of the implementation details of actually computing the various hash
00140 // code values are held within this namespace. These routines are included in
00141 // the header file mainly to allow inlining and constant propagation.
00142 namespace hashing {
00143 namespace detail {
00144 
00145 inline uint64_t fetch64(const char *p) {
00146   uint64_t result;
00147   memcpy(&result, p, sizeof(result));
00148   if (sys::IsBigEndianHost)
00149     sys::swapByteOrder(result);
00150   return result;
00151 }
00152 
00153 inline uint32_t fetch32(const char *p) {
00154   uint32_t result;
00155   memcpy(&result, p, sizeof(result));
00156   if (sys::IsBigEndianHost)
00157     sys::swapByteOrder(result);
00158   return result;
00159 }
00160 
00161 /// Some primes between 2^63 and 2^64 for various uses.
00162 static const uint64_t k0 = 0xc3a5c85c97cb3127ULL;
00163 static const uint64_t k1 = 0xb492b66fbe98f273ULL;
00164 static const uint64_t k2 = 0x9ae16a3b2f90404fULL;
00165 static const uint64_t k3 = 0xc949d7c7509e6557ULL;
00166 
00167 /// \brief Bitwise right rotate.
00168 /// Normally this will compile to a single instruction, especially if the
00169 /// shift is a manifest constant.
00170 inline uint64_t rotate(uint64_t val, size_t shift) {
00171   // Avoid shifting by 64: doing so yields an undefined result.
00172   return shift == 0 ? val : ((val >> shift) | (val << (64 - shift)));
00173 }
00174 
00175 inline uint64_t shift_mix(uint64_t val) {
00176   return val ^ (val >> 47);
00177 }
00178 
00179 inline uint64_t hash_16_bytes(uint64_t low, uint64_t high) {
00180   // Murmur-inspired hashing.
00181   const uint64_t kMul = 0x9ddfea08eb382d69ULL;
00182   uint64_t a = (low ^ high) * kMul;
00183   a ^= (a >> 47);
00184   uint64_t b = (high ^ a) * kMul;
00185   b ^= (b >> 47);
00186   b *= kMul;
00187   return b;
00188 }
00189 
00190 inline uint64_t hash_1to3_bytes(const char *s, size_t len, uint64_t seed) {
00191   uint8_t a = s[0];
00192   uint8_t b = s[len >> 1];
00193   uint8_t c = s[len - 1];
00194   uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8);
00195   uint32_t z = len + (static_cast<uint32_t>(c) << 2);
00196   return shift_mix(y * k2 ^ z * k3 ^ seed) * k2;
00197 }
00198 
00199 inline uint64_t hash_4to8_bytes(const char *s, size_t len, uint64_t seed) {
00200   uint64_t a = fetch32(s);
00201   return hash_16_bytes(len + (a << 3), seed ^ fetch32(s + len - 4));
00202 }
00203 
00204 inline uint64_t hash_9to16_bytes(const char *s, size_t len, uint64_t seed) {
00205   uint64_t a = fetch64(s);
00206   uint64_t b = fetch64(s + len - 8);
00207   return hash_16_bytes(seed ^ a, rotate(b + len, len)) ^ b;
00208 }
00209 
00210 inline uint64_t hash_17to32_bytes(const char *s, size_t len, uint64_t seed) {
00211   uint64_t a = fetch64(s) * k1;
00212   uint64_t b = fetch64(s + 8);
00213   uint64_t c = fetch64(s + len - 8) * k2;
00214   uint64_t d = fetch64(s + len - 16) * k0;
00215   return hash_16_bytes(rotate(a - b, 43) + rotate(c ^ seed, 30) + d,
00216                        a + rotate(b ^ k3, 20) - c + len + seed);
00217 }
00218 
00219 inline uint64_t hash_33to64_bytes(const char *s, size_t len, uint64_t seed) {
00220   uint64_t z = fetch64(s + 24);
00221   uint64_t a = fetch64(s) + (len + fetch64(s + len - 16)) * k0;
00222   uint64_t b = rotate(a + z, 52);
00223   uint64_t c = rotate(a, 37);
00224   a += fetch64(s + 8);
00225   c += rotate(a, 7);
00226   a += fetch64(s + 16);
00227   uint64_t vf = a + z;
00228   uint64_t vs = b + rotate(a, 31) + c;
00229   a = fetch64(s + 16) + fetch64(s + len - 32);
00230   z = fetch64(s + len - 8);
00231   b = rotate(a + z, 52);
00232   c = rotate(a, 37);
00233   a += fetch64(s + len - 24);
00234   c += rotate(a, 7);
00235   a += fetch64(s + len - 16);
00236   uint64_t wf = a + z;
00237   uint64_t ws = b + rotate(a, 31) + c;
00238   uint64_t r = shift_mix((vf + ws) * k2 + (wf + vs) * k0);
00239   return shift_mix((seed ^ (r * k0)) + vs) * k2;
00240 }
00241 
00242 inline uint64_t hash_short(const char *s, size_t length, uint64_t seed) {
00243   if (length >= 4 && length <= 8)
00244     return hash_4to8_bytes(s, length, seed);
00245   if (length > 8 && length <= 16)
00246     return hash_9to16_bytes(s, length, seed);
00247   if (length > 16 && length <= 32)
00248     return hash_17to32_bytes(s, length, seed);
00249   if (length > 32)
00250     return hash_33to64_bytes(s, length, seed);
00251   if (length != 0)
00252     return hash_1to3_bytes(s, length, seed);
00253 
00254   return k2 ^ seed;
00255 }
00256 
00257 /// \brief The intermediate state used during hashing.
00258 /// Currently, the algorithm for computing hash codes is based on CityHash and
00259 /// keeps 56 bytes of arbitrary state.
00260 struct hash_state {
00261   uint64_t h0, h1, h2, h3, h4, h5, h6;
00262 
00263   /// \brief Create a new hash_state structure and initialize it based on the
00264   /// seed and the first 64-byte chunk.
00265   /// This effectively performs the initial mix.
00266   static hash_state create(const char *s, uint64_t seed) {
00267     hash_state state = {
00268       0, seed, hash_16_bytes(seed, k1), rotate(seed ^ k1, 49),
00269       seed * k1, shift_mix(seed), 0 };
00270     state.h6 = hash_16_bytes(state.h4, state.h5);
00271     state.mix(s);
00272     return state;
00273   }
00274 
00275   /// \brief Mix 32-bytes from the input sequence into the 16-bytes of 'a'
00276   /// and 'b', including whatever is already in 'a' and 'b'.
00277   static void mix_32_bytes(const char *s, uint64_t &a, uint64_t &b) {
00278     a += fetch64(s);
00279     uint64_t c = fetch64(s + 24);
00280     b = rotate(b + a + c, 21);
00281     uint64_t d = a;
00282     a += fetch64(s + 8) + fetch64(s + 16);
00283     b += rotate(a, 44) + d;
00284     a += c;
00285   }
00286 
00287   /// \brief Mix in a 64-byte buffer of data.
00288   /// We mix all 64 bytes even when the chunk length is smaller, but we
00289   /// record the actual length.
00290   void mix(const char *s) {
00291     h0 = rotate(h0 + h1 + h3 + fetch64(s + 8), 37) * k1;
00292     h1 = rotate(h1 + h4 + fetch64(s + 48), 42) * k1;
00293     h0 ^= h6;
00294     h1 += h3 + fetch64(s + 40);
00295     h2 = rotate(h2 + h5, 33) * k1;
00296     h3 = h4 * k1;
00297     h4 = h0 + h5;
00298     mix_32_bytes(s, h3, h4);
00299     h5 = h2 + h6;
00300     h6 = h1 + fetch64(s + 16);
00301     mix_32_bytes(s + 32, h5, h6);
00302     std::swap(h2, h0);
00303   }
00304 
00305   /// \brief Compute the final 64-bit hash code value based on the current
00306   /// state and the length of bytes hashed.
00307   uint64_t finalize(size_t length) {
00308     return hash_16_bytes(hash_16_bytes(h3, h5) + shift_mix(h1) * k1 + h2,
00309                          hash_16_bytes(h4, h6) + shift_mix(length) * k1 + h0);
00310   }
00311 };
00312 
00313 
00314 /// \brief A global, fixed seed-override variable.
00315 ///
00316 /// This variable can be set using the \see llvm::set_fixed_execution_seed
00317 /// function. See that function for details. Do not, under any circumstances,
00318 /// set or read this variable.
00319 extern size_t fixed_seed_override;
00320 
00321 inline size_t get_execution_seed() {
00322   // FIXME: This needs to be a per-execution seed. This is just a placeholder
00323   // implementation. Switching to a per-execution seed is likely to flush out
00324   // instability bugs and so will happen as its own commit.
00325   //
00326   // However, if there is a fixed seed override set the first time this is
00327   // called, return that instead of the per-execution seed.
00328   const uint64_t seed_prime = 0xff51afd7ed558ccdULL;
00329   static size_t seed = fixed_seed_override ? fixed_seed_override
00330                                            : (size_t)seed_prime;
00331   return seed;
00332 }
00333 
00334 
00335 /// \brief Trait to indicate whether a type's bits can be hashed directly.
00336 ///
00337 /// A type trait which is true if we want to combine values for hashing by
00338 /// reading the underlying data. It is false if values of this type must
00339 /// first be passed to hash_value, and the resulting hash_codes combined.
00340 //
00341 // FIXME: We want to replace is_integral_or_enum and is_pointer here with
00342 // a predicate which asserts that comparing the underlying storage of two
00343 // values of the type for equality is equivalent to comparing the two values
00344 // for equality. For all the platforms we care about, this holds for integers
00345 // and pointers, but there are platforms where it doesn't and we would like to
00346 // support user-defined types which happen to satisfy this property.
00347 template <typename T> struct is_hashable_data
00348   : std::integral_constant<bool, ((is_integral_or_enum<T>::value ||
00349                                    std::is_pointer<T>::value) &&
00350                                   64 % sizeof(T) == 0)> {};
00351 
00352 // Special case std::pair to detect when both types are viable and when there
00353 // is no alignment-derived padding in the pair. This is a bit of a lie because
00354 // std::pair isn't truly POD, but it's close enough in all reasonable
00355 // implementations for our use case of hashing the underlying data.
00356 template <typename T, typename U> struct is_hashable_data<std::pair<T, U> >
00357   : std::integral_constant<bool, (is_hashable_data<T>::value &&
00358                                   is_hashable_data<U>::value &&
00359                                   (sizeof(T) + sizeof(U)) ==
00360                                    sizeof(std::pair<T, U>))> {};
00361 
00362 /// \brief Helper to get the hashable data representation for a type.
00363 /// This variant is enabled when the type itself can be used.
00364 template <typename T>
00365 typename std::enable_if<is_hashable_data<T>::value, T>::type
00366 get_hashable_data(const T &value) {
00367   return value;
00368 }
00369 /// \brief Helper to get the hashable data representation for a type.
00370 /// This variant is enabled when we must first call hash_value and use the
00371 /// result as our data.
00372 template <typename T>
00373 typename std::enable_if<!is_hashable_data<T>::value, size_t>::type
00374 get_hashable_data(const T &value) {
00375   using ::llvm::hash_value;
00376   return hash_value(value);
00377 }
00378 
00379 /// \brief Helper to store data from a value into a buffer and advance the
00380 /// pointer into that buffer.
00381 ///
00382 /// This routine first checks whether there is enough space in the provided
00383 /// buffer, and if not immediately returns false. If there is space, it
00384 /// copies the underlying bytes of value into the buffer, advances the
00385 /// buffer_ptr past the copied bytes, and returns true.
00386 template <typename T>
00387 bool store_and_advance(char *&buffer_ptr, char *buffer_end, const T& value,
00388                        size_t offset = 0) {
00389   size_t store_size = sizeof(value) - offset;
00390   if (buffer_ptr + store_size > buffer_end)
00391     return false;
00392   const char *value_data = reinterpret_cast<const char *>(&value);
00393   memcpy(buffer_ptr, value_data + offset, store_size);
00394   buffer_ptr += store_size;
00395   return true;
00396 }
00397 
00398 /// \brief Implement the combining of integral values into a hash_code.
00399 ///
00400 /// This overload is selected when the value type of the iterator is
00401 /// integral. Rather than computing a hash_code for each object and then
00402 /// combining them, this (as an optimization) directly combines the integers.
00403 template <typename InputIteratorT>
00404 hash_code hash_combine_range_impl(InputIteratorT first, InputIteratorT last) {
00405   const size_t seed = get_execution_seed();
00406   char buffer[64], *buffer_ptr = buffer;
00407   char *const buffer_end = std::end(buffer);
00408   while (first != last && store_and_advance(buffer_ptr, buffer_end,
00409                                             get_hashable_data(*first)))
00410     ++first;
00411   if (first == last)
00412     return hash_short(buffer, buffer_ptr - buffer, seed);
00413   assert(buffer_ptr == buffer_end);
00414 
00415   hash_state state = state.create(buffer, seed);
00416   size_t length = 64;
00417   while (first != last) {
00418     // Fill up the buffer. We don't clear it, which re-mixes the last round
00419     // when only a partial 64-byte chunk is left.
00420     buffer_ptr = buffer;
00421     while (first != last && store_and_advance(buffer_ptr, buffer_end,
00422                                               get_hashable_data(*first)))
00423       ++first;
00424 
00425     // Rotate the buffer if we did a partial fill in order to simulate doing
00426     // a mix of the last 64-bytes. That is how the algorithm works when we
00427     // have a contiguous byte sequence, and we want to emulate that here.
00428     std::rotate(buffer, buffer_ptr, buffer_end);
00429 
00430     // Mix this chunk into the current state.
00431     state.mix(buffer);
00432     length += buffer_ptr - buffer;
00433   };
00434 
00435   return state.finalize(length);
00436 }
00437 
00438 /// \brief Implement the combining of integral values into a hash_code.
00439 ///
00440 /// This overload is selected when the value type of the iterator is integral
00441 /// and when the input iterator is actually a pointer. Rather than computing
00442 /// a hash_code for each object and then combining them, this (as an
00443 /// optimization) directly combines the integers. Also, because the integers
00444 /// are stored in contiguous memory, this routine avoids copying each value
00445 /// and directly reads from the underlying memory.
00446 template <typename ValueT>
00447 typename std::enable_if<is_hashable_data<ValueT>::value, hash_code>::type
00448 hash_combine_range_impl(ValueT *first, ValueT *last) {
00449   const size_t seed = get_execution_seed();
00450   const char *s_begin = reinterpret_cast<const char *>(first);
00451   const char *s_end = reinterpret_cast<const char *>(last);
00452   const size_t length = std::distance(s_begin, s_end);
00453   if (length <= 64)
00454     return hash_short(s_begin, length, seed);
00455 
00456   const char *s_aligned_end = s_begin + (length & ~63);
00457   hash_state state = state.create(s_begin, seed);
00458   s_begin += 64;
00459   while (s_begin != s_aligned_end) {
00460     state.mix(s_begin);
00461     s_begin += 64;
00462   }
00463   if (length & 63)
00464     state.mix(s_end - 64);
00465 
00466   return state.finalize(length);
00467 }
00468 
00469 } // namespace detail
00470 } // namespace hashing
00471 
00472 
00473 /// \brief Compute a hash_code for a sequence of values.
00474 ///
00475 /// This hashes a sequence of values. It produces the same hash_code as
00476 /// 'hash_combine(a, b, c, ...)', but can run over arbitrary sized sequences
00477 /// and is significantly faster given pointers and types which can be hashed as
00478 /// a sequence of bytes.
00479 template <typename InputIteratorT>
00480 hash_code hash_combine_range(InputIteratorT first, InputIteratorT last) {
00481   return ::llvm::hashing::detail::hash_combine_range_impl(first, last);
00482 }
00483 
00484 
00485 // Implementation details for hash_combine.
00486 namespace hashing {
00487 namespace detail {
00488 
00489 /// \brief Helper class to manage the recursive combining of hash_combine
00490 /// arguments.
00491 ///
00492 /// This class exists to manage the state and various calls involved in the
00493 /// recursive combining of arguments used in hash_combine. It is particularly
00494 /// useful at minimizing the code in the recursive calls to ease the pain
00495 /// caused by a lack of variadic functions.
00496 struct hash_combine_recursive_helper {
00497   char buffer[64];
00498   hash_state state;
00499   const size_t seed;
00500 
00501 public:
00502   /// \brief Construct a recursive hash combining helper.
00503   ///
00504   /// This sets up the state for a recursive hash combine, including getting
00505   /// the seed and buffer setup.
00506   hash_combine_recursive_helper()
00507     : seed(get_execution_seed()) {}
00508 
00509   /// \brief Combine one chunk of data into the current in-flight hash.
00510   ///
00511   /// This merges one chunk of data into the hash. First it tries to buffer
00512   /// the data. If the buffer is full, it hashes the buffer into its
00513   /// hash_state, empties it, and then merges the new chunk in. This also
00514   /// handles cases where the data straddles the end of the buffer.
00515   template <typename T>
00516   char *combine_data(size_t &length, char *buffer_ptr, char *buffer_end, T data) {
00517     if (!store_and_advance(buffer_ptr, buffer_end, data)) {
00518       // Check for skew which prevents the buffer from being packed, and do
00519       // a partial store into the buffer to fill it. This is only a concern
00520       // with the variadic combine because that formation can have varying
00521       // argument types.
00522       size_t partial_store_size = buffer_end - buffer_ptr;
00523       memcpy(buffer_ptr, &data, partial_store_size);
00524 
00525       // If the store fails, our buffer is full and ready to hash. We have to
00526       // either initialize the hash state (on the first full buffer) or mix
00527       // this buffer into the existing hash state. Length tracks the *hashed*
00528       // length, not the buffered length.
00529       if (length == 0) {
00530         state = state.create(buffer, seed);
00531         length = 64;
00532       } else {
00533         // Mix this chunk into the current state and bump length up by 64.
00534         state.mix(buffer);
00535         length += 64;
00536       }
00537       // Reset the buffer_ptr to the head of the buffer for the next chunk of
00538       // data.
00539       buffer_ptr = buffer;
00540 
00541       // Try again to store into the buffer -- this cannot fail as we only
00542       // store types smaller than the buffer.
00543       if (!store_and_advance(buffer_ptr, buffer_end, data,
00544                              partial_store_size))
00545         abort();
00546     }
00547     return buffer_ptr;
00548   }
00549 
00550   /// \brief Recursive, variadic combining method.
00551   ///
00552   /// This function recurses through each argument, combining that argument
00553   /// into a single hash.
00554   template <typename T, typename ...Ts>
00555   hash_code combine(size_t length, char *buffer_ptr, char *buffer_end,
00556                     const T &arg, const Ts &...args) {
00557     buffer_ptr = combine_data(length, buffer_ptr, buffer_end, get_hashable_data(arg));
00558 
00559     // Recurse to the next argument.
00560     return combine(length, buffer_ptr, buffer_end, args...);
00561   }
00562 
00563   /// \brief Base case for recursive, variadic combining.
00564   ///
00565   /// The base case when combining arguments recursively is reached when all
00566   /// arguments have been handled. It flushes the remaining buffer and
00567   /// constructs a hash_code.
00568   hash_code combine(size_t length, char *buffer_ptr, char *buffer_end) {
00569     // Check whether the entire set of values fit in the buffer. If so, we'll
00570     // use the optimized short hashing routine and skip state entirely.
00571     if (length == 0)
00572       return hash_short(buffer, buffer_ptr - buffer, seed);
00573 
00574     // Mix the final buffer, rotating it if we did a partial fill in order to
00575     // simulate doing a mix of the last 64-bytes. That is how the algorithm
00576     // works when we have a contiguous byte sequence, and we want to emulate
00577     // that here.
00578     std::rotate(buffer, buffer_ptr, buffer_end);
00579 
00580     // Mix this chunk into the current state.
00581     state.mix(buffer);
00582     length += buffer_ptr - buffer;
00583 
00584     return state.finalize(length);
00585   }
00586 };
00587 
00588 } // namespace detail
00589 } // namespace hashing
00590 
00591 /// \brief Combine values into a single hash_code.
00592 ///
00593 /// This routine accepts a varying number of arguments of any type. It will
00594 /// attempt to combine them into a single hash_code. For user-defined types it
00595 /// attempts to call a \see hash_value overload (via ADL) for the type. For
00596 /// integer and pointer types it directly combines their data into the
00597 /// resulting hash_code.
00598 ///
00599 /// The result is suitable for returning from a user's hash_value
00600 /// *implementation* for their user-defined type. Consumers of a type should
00601 /// *not* call this routine, they should instead call 'hash_value'.
00602 template <typename ...Ts> hash_code hash_combine(const Ts &...args) {
00603   // Recursively hash each argument using a helper class.
00604   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
00605   return helper.combine(0, helper.buffer, helper.buffer + 64, args...);
00606 }
00607 
00608 // Implementation details for implementations of hash_value overloads provided
00609 // here.
00610 namespace hashing {
00611 namespace detail {
00612 
00613 /// \brief Helper to hash the value of a single integer.
00614 ///
00615 /// Overloads for smaller integer types are not provided to ensure consistent
00616 /// behavior in the presence of integral promotions. Essentially,
00617 /// "hash_value('4')" and "hash_value('0' + 4)" should be the same.
00618 inline hash_code hash_integer_value(uint64_t value) {
00619   // Similar to hash_4to8_bytes but using a seed instead of length.
00620   const uint64_t seed = get_execution_seed();
00621   const char *s = reinterpret_cast<const char *>(&value);
00622   const uint64_t a = fetch32(s);
00623   return hash_16_bytes(seed + (a << 3), fetch32(s + 4));
00624 }
00625 
00626 } // namespace detail
00627 } // namespace hashing
00628 
00629 // Declared and documented above, but defined here so that any of the hashing
00630 // infrastructure is available.
00631 template <typename T>
00632 typename std::enable_if<is_integral_or_enum<T>::value, hash_code>::type
00633 hash_value(T value) {
00634   return ::llvm::hashing::detail::hash_integer_value(value);
00635 }
00636 
00637 // Declared and documented above, but defined here so that any of the hashing
00638 // infrastructure is available.
00639 template <typename T> hash_code hash_value(const T *ptr) {
00640   return ::llvm::hashing::detail::hash_integer_value(
00641     reinterpret_cast<uintptr_t>(ptr));
00642 }
00643 
00644 // Declared and documented above, but defined here so that any of the hashing
00645 // infrastructure is available.
00646 template <typename T, typename U>
00647 hash_code hash_value(const std::pair<T, U> &arg) {
00648   return hash_combine(arg.first, arg.second);
00649 }
00650 
00651 // Declared and documented above, but defined here so that any of the hashing
00652 // infrastructure is available.
00653 template <typename T>
00654 hash_code hash_value(const std::basic_string<T> &arg) {
00655   return hash_combine_range(arg.begin(), arg.end());
00656 }
00657 
00658 } // namespace llvm
00659 
00660 #endif