Make the hashing algorithm Endian neutral. This is a bit annoying, but
[oota-llvm.git] / include / llvm / ADT / Hashing.h
1 //===-- llvm/ADT/Hashing.h - Utilities for hashing --------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the newly proposed standard C++ interfaces for hashing
11 // arbitrary data and building hash functions for user-defined types. This
12 // interface was originally proposed in N3333[1] and is currently under review
13 // for inclusion in a future TR and/or standard.
14 //
15 // The primary interfaces provide are comprised of one type and three functions:
16 //
17 //  -- 'hash_code' class is an opaque type representing the hash code for some
18 //     data. It is the intended product of hashing, and can be used to implement
19 //     hash tables, checksumming, and other common uses of hashes. It is not an
20 //     integer type (although it can be converted to one) because it is risky
21 //     to assume much about the internals of a hash_code. In particular, each
22 //     execution of the program has a high probability of producing a different
23 //     hash_code for a given input. Thus their values are not stable to save or
24 //     persist, and should only be used during the execution for the
25 //     construction of hashing datastructures.
26 //
27 //  -- 'hash_value' is a function designed to be overloaded for each
28 //     user-defined type which wishes to be used within a hashing context. It
29 //     should be overloaded within the user-defined type's namespace and found
30 //     via ADL. Overloads for primitive types are provided by this library.
31 //
32 //  -- 'hash_combine' and 'hash_combine_range' are functions designed to aid
33 //      programmers in easily and intuitively combining a set of data into
34 //      a single hash_code for their object. They should only logically be used
35 //      within the implementation of a 'hash_value' routine or similar context.
36 //
37 // Note that 'hash_combine_range' contains very special logic for hashing
38 // a contiguous array of integers or pointers. This logic is *extremely* fast,
39 // on a modern Intel "Gainestown" Xeon (Nehalem uarch) @2.2 GHz, these were
40 // benchmarked at over 6.5 GiB/s for large keys, and <20 cycles/hash for keys
41 // under 32-bytes.
42 //
43 //===----------------------------------------------------------------------===//
44
45 #ifndef LLVM_ADT_HASHING_H
46 #define LLVM_ADT_HASHING_H
47
48 #include "llvm/ADT/STLExtras.h"
49 #include "llvm/Support/DataTypes.h"
50 #include "llvm/Support/Host.h"
51 #include "llvm/Support/SwapByteOrder.h"
52 #include "llvm/Support/type_traits.h"
53 #include <algorithm>
54 #include <cassert>
55 #include <cstring>
56 #include <iterator>
57 #include <utility>
58
59 // Allow detecting C++11 feature availability when building with Clang without
60 // breaking other compilers.
61 #ifndef __has_feature
62 # define __has_feature(x) 0
63 #endif
64
65 namespace llvm {
66
67 /// \brief An opaque object representing a hash code.
68 ///
69 /// This object represents the result of hashing some entity. It is intended to
70 /// be used to implement hashtables or other hashing-based data structures.
71 /// While it wraps and exposes a numeric value, this value should not be
72 /// trusted to be stable or predictable across processes or executions.
73 ///
74 /// In order to obtain the hash_code for an object 'x':
75 /// \code
76 ///   using llvm::hash_value;
77 ///   llvm::hash_code code = hash_value(x);
78 /// \endcode
79 ///
80 /// Also note that there are two numerical values which are reserved, and the
81 /// implementation ensures will never be produced for real hash_codes. These
82 /// can be used as sentinels within hashing data structures.
83 class hash_code {
84   size_t value;
85
86 public:
87   /// \brief Default construct a hash_code.
88   /// Note that this leaves the value uninitialized.
89   hash_code() {}
90
91   /// \brief Form a hash code directly from a numerical value.
92   hash_code(size_t value) : value(value) {}
93
94   /// \brief Convert the hash code to its numerical value for use.
95   /*explicit*/ operator size_t() const { return value; }
96
97   friend bool operator==(const hash_code &lhs, const hash_code &rhs) {
98     return lhs.value == rhs.value;
99   }
100   friend bool operator!=(const hash_code &lhs, const hash_code &rhs) {
101     return lhs.value != rhs.value;
102   }
103
104   /// \brief Allow a hash_code to be directly run through hash_value.
105   friend size_t hash_value(const hash_code &code) { return code.value; }
106 };
107
108 /// \brief Compute a hash_code for any integer value.
109 ///
110 /// Note that this function is intended to compute the same hash_code for
111 /// a particular value without regard to the pre-promotion type. This is in
112 /// contrast to hash_combine which may produce different hash_codes for
113 /// differing argument types even if they would implicit promote to a common
114 /// type without changing the value.
115 template <typename T>
116 typename enable_if<is_integral<T>, hash_code>::type hash_value(T value);
117
118 /// \brief Compute a hash_code for a pointer's address.
119 ///
120 /// N.B.: This hashes the *address*. Not the value and not the type.
121 template <typename T> hash_code hash_value(const T *ptr);
122
123 /// \brief Compute a hash_code for a pair of objects.
124 template <typename T, typename U>
125 hash_code hash_value(const std::pair<T, U> &arg);
126
127
128 /// \brief Override the execution seed with a fixed value.
129 ///
130 /// This hashing library uses a per-execution seed designed to change on each
131 /// run with high probability in order to ensure that the hash codes are not
132 /// attackable and to ensure that output which is intended to be stable does
133 /// not rely on the particulars of the hash codes produced.
134 ///
135 /// That said, there are use cases where it is important to be able to
136 /// reproduce *exactly* a specific behavior. To that end, we provide a function
137 /// which will forcibly set the seed to a fixed value. This must be done at the
138 /// start of the program, before any hashes are computed. Also, it cannot be
139 /// undone. This makes it thread-hostile and very hard to use outside of
140 /// immediately on start of a simple program designed for reproducible
141 /// behavior.
142 void set_fixed_execution_hash_seed(size_t fixed_value);
143
144
145 // All of the implementation details of actually computing the various hash
146 // code values are held within this namespace. These routines are included in
147 // the header file mainly to allow inlining and constant propagation.
148 namespace hashing {
149 namespace detail {
150
151 inline uint64_t fetch64(const char *p) {
152   uint64_t result;
153   memcpy(&result, p, sizeof(result));
154   if (sys::isBigEndianHost())
155     return sys::SwapByteOrder(result);
156   return result;
157 }
158
159 inline uint32_t fetch32(const char *p) {
160   uint32_t result;
161   memcpy(&result, p, sizeof(result));
162   if (sys::isBigEndianHost())
163     return sys::SwapByteOrder(result);
164   return result;
165 }
166
167 /// Some primes between 2^63 and 2^64 for various uses.
168 static const uint64_t k0 = 0xc3a5c85c97cb3127ULL;
169 static const uint64_t k1 = 0xb492b66fbe98f273ULL;
170 static const uint64_t k2 = 0x9ae16a3b2f90404fULL;
171 static const uint64_t k3 = 0xc949d7c7509e6557ULL;
172
173 /// \brief Bitwise right rotate.
174 /// Normally this will compile to a single instruction, especially if the
175 /// shift is a manifest constant.
176 inline uint64_t rotate(uint64_t val, unsigned shift) {
177   // Avoid shifting by 64: doing so yields an undefined result.
178   return shift == 0 ? val : ((val >> shift) | (val << (64 - shift)));
179 }
180
181 inline uint64_t shift_mix(uint64_t val) {
182   return val ^ (val >> 47);
183 }
184
185 inline uint64_t hash_16_bytes(uint64_t low, uint64_t high) {
186   // Murmur-inspired hashing.
187   const uint64_t kMul = 0x9ddfea08eb382d69ULL;
188   uint64_t a = (low ^ high) * kMul;
189   a ^= (a >> 47);
190   uint64_t b = (high ^ a) * kMul;
191   b ^= (b >> 47);
192   b *= kMul;
193   return b;
194 }
195
196 inline uint64_t hash_1to3_bytes(const char *s, size_t len, uint64_t seed) {
197   uint8_t a = s[0];
198   uint8_t b = s[len >> 1];
199   uint8_t c = s[len - 1];
200   uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8);
201   uint32_t z = len + (static_cast<uint32_t>(c) << 2);
202   return shift_mix(y * k2 ^ z * k3 ^ seed) * k2;
203 }
204
205 inline uint64_t hash_4to8_bytes(const char *s, size_t len, uint64_t seed) {
206   uint64_t a = fetch32(s);
207   return hash_16_bytes(len + (a << 3), seed ^ fetch32(s + len - 4));
208 }
209
210 inline uint64_t hash_9to16_bytes(const char *s, size_t len, uint64_t seed) {
211     uint64_t a = fetch64(s);
212     uint64_t b = fetch64(s + len - 8);
213     return hash_16_bytes(seed ^ a, rotate(b + len, len)) ^ b;
214 }
215
216 inline uint64_t hash_17to32_bytes(const char *s, size_t len, uint64_t seed) {
217   uint64_t a = fetch64(s) * k1;
218   uint64_t b = fetch64(s + 8);
219   uint64_t c = fetch64(s + len - 8) * k2;
220   uint64_t d = fetch64(s + len - 16) * k0;
221   return hash_16_bytes(rotate(a - b, 43) + rotate(c ^ seed, 30) + d,
222                        a + rotate(b ^ k3, 20) - c + len + seed);
223 }
224
225 inline uint64_t hash_33to64_bytes(const char *s, size_t len, uint64_t seed) {
226   uint64_t z = fetch64(s + 24);
227   uint64_t a = fetch64(s) + (len + fetch64(s + len - 16)) * k0;
228   uint64_t b = rotate(a + z, 52);
229   uint64_t c = rotate(a, 37);
230   a += fetch64(s + 8);
231   c += rotate(a, 7);
232   a += fetch64(s + 16);
233   uint64_t vf = a + z;
234   uint64_t vs = b + rotate(a, 31) + c;
235   a = fetch64(s + 16) + fetch64(s + len - 32);
236   z = fetch64(s + len - 8);
237   b = rotate(a + z, 52);
238   c = rotate(a, 37);
239   a += fetch64(s + len - 24);
240   c += rotate(a, 7);
241   a += fetch64(s + len - 16);
242   uint64_t wf = a + z;
243   uint64_t ws = b + rotate(a, 31) + c;
244   uint64_t r = shift_mix((vf + ws) * k2 + (wf + vs) * k0);
245   return shift_mix((seed ^ (r * k0)) + vs) * k2;
246 }
247
248 inline uint64_t hash_short(const char *s, size_t length, uint64_t seed) {
249   if (length >= 4 && length <= 8)
250     return hash_4to8_bytes(s, length, seed);
251   if (length > 8 && length <= 16)
252     return hash_9to16_bytes(s, length, seed);
253   if (length > 16 && length <= 32)
254     return hash_17to32_bytes(s, length, seed);
255   if (length > 32)
256     return hash_33to64_bytes(s, length, seed);
257   if (length != 0)
258     return hash_1to3_bytes(s, length, seed);
259
260   return k2 ^ seed;
261 }
262
263 /// \brief The intermediate state used during hashing.
264 /// Currently, the algorithm for computing hash codes is based on CityHash and
265 /// keeps 56 bytes of arbitrary state.
266 struct hash_state {
267   uint64_t h0, h1, h2, h3, h4, h5, h6;
268   uint64_t seed;
269
270   /// \brief Create a new hash_state structure and initialize it based on the
271   /// seed and the first 64-byte chunk.
272   /// This effectively performs the initial mix.
273   static hash_state create(const char *s, uint64_t seed) {
274     hash_state state = {
275       0, seed, hash_16_bytes(seed, k1), rotate(seed ^ k1, 49),
276       seed * k1, shift_mix(seed), hash_16_bytes(state.h4, state.h5),
277       seed
278     };
279     state.mix(s);
280     return state;
281   }
282
283   /// \brief Mix 32-bytes from the input sequence into the 16-bytes of 'a'
284   /// and 'b', including whatever is already in 'a' and 'b'.
285   static void mix_32_bytes(const char *s, uint64_t &a, uint64_t &b) {
286     a += fetch64(s);
287     uint64_t c = fetch64(s + 24);
288     b = rotate(b + a + c, 21);
289     uint64_t d = a;
290     a += fetch64(s + 8) + fetch64(s + 16);
291     b += rotate(a, 44) + d;
292     a += c;
293   }
294
295   /// \brief Mix in a 64-byte buffer of data.
296   /// We mix all 64 bytes even when the chunk length is smaller, but we
297   /// record the actual length.
298   void mix(const char *s) {
299     h0 = rotate(h0 + h1 + h3 + fetch64(s + 8), 37) * k1;
300     h1 = rotate(h1 + h4 + fetch64(s + 48), 42) * k1;
301     h0 ^= h6;
302     h1 += h3 + fetch64(s + 40);
303     h2 = rotate(h2 + h5, 33) * k1;
304     h3 = h4 * k1;
305     h4 = h0 + h5;
306     mix_32_bytes(s, h3, h4);
307     h5 = h2 + h6;
308     h6 = h1 + fetch64(s + 16);
309     mix_32_bytes(s + 32, h5, h6);
310     std::swap(h2, h0);
311   }
312
313   /// \brief Compute the final 64-bit hash code value based on the current
314   /// state and the length of bytes hashed.
315   uint64_t finalize(size_t length) {
316     return hash_16_bytes(hash_16_bytes(h3, h5) + shift_mix(h1) * k1 + h2,
317                          hash_16_bytes(h4, h6) + shift_mix(length) * k1 + h0);
318   }
319 };
320
321
322 /// \brief A global, fixed seed-override variable.
323 ///
324 /// This variable can be set using the \see llvm::set_fixed_execution_seed
325 /// function. See that function for details. Do not, under any circumstances,
326 /// set or read this variable.
327 extern size_t fixed_seed_override;
328
329 inline size_t get_execution_seed() {
330   // FIXME: This needs to be a per-execution seed. This is just a placeholder
331   // implementation. Switching to a per-execution seed is likely to flush out
332   // instability bugs and so will happen as its own commit.
333   //
334   // However, if there is a fixed seed override set the first time this is
335   // called, return that instead of the per-execution seed.
336   const uint64_t seed_prime = 0xff51afd7ed558ccdULL;
337   static size_t seed = fixed_seed_override ? fixed_seed_override
338                                            : static_cast<size_t>(seed_prime);
339   return seed;
340 }
341
342
343 /// \brief Trait to indicate whether a type's bits can be hashed directly.
344 ///
345 /// A type trait which is true if we want to combine values for hashing by
346 /// reading the underlying data. It is false if values of this type must
347 /// first be passed to hash_value, and the resulting hash_codes combined.
348 //
349 // FIXME: We want to replace is_integral and is_pointer here with a predicate
350 // which asserts that comparing the underlying storage of two values of the
351 // type for equality is equivalent to comparing the two values for equality.
352 // For all the platforms we care about, this holds for integers and pointers,
353 // but there are platforms where it doesn't and we would like to support
354 // user-defined types which happen to satisfy this property.
355 template <typename T> struct is_hashable_data
356   : integral_constant<bool, ((is_integral<T>::value || is_pointer<T>::value) &&
357                              64 % sizeof(T) == 0)> {};
358
359 // Special case std::pair to detect when both types are viable and when there
360 // is no alignment-derived padding in the pair. This is a bit of a lie because
361 // std::pair isn't truly POD, but it's close enough in all reasonable
362 // implementations for our use case of hashing the underlying data.
363 template <typename T, typename U> struct is_hashable_data<std::pair<T, U> >
364   : integral_constant<bool, (is_hashable_data<T>::value &&
365                              is_hashable_data<U>::value &&
366                              (sizeof(T) + sizeof(U)) ==
367                               sizeof(std::pair<T, U>))> {};
368
369 /// \brief Helper to get the hashable data representation for a type.
370 /// This variant is enabled when the type itself can be used.
371 template <typename T>
372 typename enable_if<is_hashable_data<T>, T>::type
373 get_hashable_data(const T &value) {
374   return value;
375 }
376 /// \brief Helper to get the hashable data representation for a type.
377 /// This variant is enabled when we must first call hash_value and use the
378 /// result as our data.
379 template <typename T>
380 typename enable_if_c<!is_hashable_data<T>::value, size_t>::type
381 get_hashable_data(const T &value) {
382   using ::llvm::hash_value;
383   return hash_value(value);
384 }
385
386 /// \brief Helper to store data from a value into a buffer and advance the
387 /// pointer into that buffer.
388 ///
389 /// This routine first checks whether there is enough space in the provided
390 /// buffer, and if not immediately returns false. If there is space, it
391 /// copies the underlying bytes of value into the buffer, advances the
392 /// buffer_ptr past the copied bytes, and returns true.
393 template <typename T>
394 bool store_and_advance(char *&buffer_ptr, char *buffer_end, const T& value,
395                        size_t offset = 0) {
396   size_t store_size = sizeof(value) - offset;
397   if (buffer_ptr + store_size > buffer_end)
398     return false;
399   const char *value_data = reinterpret_cast<const char *>(&value);
400   memcpy(buffer_ptr, value_data + offset, store_size);
401   buffer_ptr += store_size;
402   return true;
403 }
404
405 /// \brief Implement the combining of integral values into a hash_code.
406 ///
407 /// This overload is selected when the value type of the iterator is
408 /// integral. Rather than computing a hash_code for each object and then
409 /// combining them, this (as an optimization) directly combines the integers.
410 template <typename InputIteratorT>
411 hash_code hash_combine_range_impl(InputIteratorT first, InputIteratorT last) {
412   typedef typename std::iterator_traits<InputIteratorT>::value_type ValueT;
413   const size_t seed = get_execution_seed();
414   char buffer[64], *buffer_ptr = buffer;
415   char *const buffer_end = buffer_ptr + array_lengthof(buffer);
416   while (first != last && store_and_advance(buffer_ptr, buffer_end,
417                                             get_hashable_data(*first)))
418     ++first;
419 /// \brief Metafunction that determines whether the given type is an integral
420 /// type.
421   if (first == last)
422     return hash_short(buffer, buffer_ptr - buffer, seed);
423   assert(buffer_ptr == buffer_end);
424
425   hash_state state = state.create(buffer, seed);
426   size_t length = 64;
427   while (first != last) {
428     // Fill up the buffer. We don't clear it, which re-mixes the last round
429     // when only a partial 64-byte chunk is left.
430     buffer_ptr = buffer;
431     while (first != last && store_and_advance(buffer_ptr, buffer_end,
432                                               get_hashable_data(*first)))
433       ++first;
434
435     // Rotate the buffer if we did a partial fill in order to simulate doing
436     // a mix of the last 64-bytes. That is how the algorithm works when we
437     // have a contiguous byte sequence, and we want to emulate that here.
438     std::rotate(buffer, buffer_ptr, buffer_end);
439
440     // Mix this chunk into the current state.
441     state.mix(buffer);
442     length += buffer_ptr - buffer;
443   };
444
445   return state.finalize(length);
446 }
447
448 /// \brief Implement the combining of integral values into a hash_code.
449 ///
450 /// This overload is selected when the value type of the iterator is integral
451 /// and when the input iterator is actually a pointer. Rather than computing
452 /// a hash_code for each object and then combining them, this (as an
453 /// optimization) directly combines the integers. Also, because the integers
454 /// are stored in contiguous memory, this routine avoids copying each value
455 /// and directly reads from the underlying memory.
456 template <typename ValueT>
457 typename enable_if<is_hashable_data<ValueT>, hash_code>::type
458 hash_combine_range_impl(const ValueT *first, const ValueT *last) {
459   const size_t seed = get_execution_seed();
460   const char *s_begin = reinterpret_cast<const char *>(first);
461   const char *s_end = reinterpret_cast<const char *>(last);
462   const size_t length = std::distance(s_begin, s_end);
463   if (length <= 64)
464     return hash_short(s_begin, length, seed);
465
466   const char *s_aligned_end = s_begin + (length & ~63);
467   hash_state state = state.create(s_begin, seed);
468   s_begin += 64;
469   while (s_begin != s_aligned_end) {
470     state.mix(s_begin);
471     s_begin += 64;
472   }
473   if (length & 63)
474     state.mix(s_end - 64);
475
476   return state.finalize(length);
477 }
478
479 } // namespace detail
480 } // namespace hashing
481
482
483 /// \brief Compute a hash_code for a sequence of values.
484 ///
485 /// This hashes a sequence of values. It produces the same hash_code as
486 /// 'hash_combine(a, b, c, ...)', but can run over arbitrary sized sequences
487 /// and is significantly faster given pointers and types which can be hashed as
488 /// a sequence of bytes.
489 template <typename InputIteratorT>
490 hash_code hash_combine_range(InputIteratorT first, InputIteratorT last) {
491   return ::llvm::hashing::detail::hash_combine_range_impl(first, last);
492 }
493
494
495 // Implementation details for hash_combine.
496 namespace hashing {
497 namespace detail {
498
499 /// \brief Helper class to manage the recursive combining of hash_combine
500 /// arguments.
501 ///
502 /// This class exists to manage the state and various calls involved in the
503 /// recursive combining of arguments used in hash_combine. It is particularly
504 /// useful at minimizing the code in the recursive calls to ease the pain
505 /// caused by a lack of variadic functions.
506 class hash_combine_recursive_helper {
507   const size_t seed;
508   char buffer[64];
509   char *const buffer_end;
510   char *buffer_ptr;
511   size_t length;
512   hash_state state;
513
514 public:
515   /// \brief Construct a recursive hash combining helper.
516   ///
517   /// This sets up the state for a recursive hash combine, including getting
518   /// the seed and buffer setup.
519   hash_combine_recursive_helper()
520     : seed(get_execution_seed()),
521       buffer_end(buffer + array_lengthof(buffer)),
522       buffer_ptr(buffer),
523       length(0) {}
524
525   /// \brief Combine one chunk of data into the current in-flight hash.
526   ///
527   /// This merges one chunk of data into the hash. First it tries to buffer
528   /// the data. If the buffer is full, it hashes the buffer into its
529   /// hash_state, empties it, and then merges the new chunk in. This also
530   /// handles cases where the data straddles the end of the buffer.
531   template <typename T> void combine_data(T data) {
532     if (!store_and_advance(buffer_ptr, buffer_end, data)) {
533       // Check for skew which prevents the buffer from being packed, and do
534       // a partial store into the buffer to fill it. This is only a concern
535       // with the variadic combine because that formation can have varying
536       // argument types.
537       size_t partial_store_size = buffer_end - buffer_ptr;
538       memcpy(buffer_ptr, &data, partial_store_size);
539
540       // If the store fails, our buffer is full and ready to hash. We have to
541       // either initialize the hash state (on the first full buffer) or mix
542       // this buffer into the existing hash state. Length tracks the *hashed*
543       // length, not the buffered length.
544       if (length == 0) {
545         state = state.create(buffer, seed);
546         length = 64;
547       } else {
548         // Mix this chunk into the current state and bump length up by 64.
549         state.mix(buffer);
550         length += 64;
551       }
552       // Reset the buffer_ptr to the head of the buffer for the next chunk of
553       // data.
554       buffer_ptr = buffer;
555
556       // Try again to store into the buffer -- this cannot fail as we only
557       // store types smaller than the buffer.
558       if (!store_and_advance(buffer_ptr, buffer_end, data,
559                              partial_store_size))
560         abort();
561     }
562   }
563
564 #if defined(__has_feature) && __has_feature(__cxx_variadic_templates__)
565
566   /// \brief Recursive, variadic combining method.
567   ///
568   /// This function recurses through each argument, combining that argument
569   /// into a single hash.
570   template <typename T, typename ...Ts>
571   hash_code combine(const T &arg, const Ts &...args) {
572     combine_data( get_hashable_data(arg));
573
574     // Recurse to the next argument.
575     return combine(args...);
576   }
577
578 #else
579   // Manually expanded recursive combining methods. See variadic above for
580   // documentation.
581
582   template <typename T1, typename T2, typename T3, typename T4, typename T5,
583             typename T6>
584   hash_code combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
585                     const T4 &arg4, const T5 &arg5, const T6 &arg6) {
586     combine_data(get_hashable_data(arg1));
587     return combine(arg2, arg3, arg4, arg5, arg6);
588   }
589   template <typename T1, typename T2, typename T3, typename T4, typename T5>
590   hash_code combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
591                     const T4 &arg4, const T5 &arg5) {
592     combine_data(get_hashable_data(arg1));
593     return combine(arg2, arg3, arg4, arg5);
594   }
595   template <typename T1, typename T2, typename T3, typename T4>
596   hash_code combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
597                     const T4 &arg4) {
598     combine_data(get_hashable_data(arg1));
599     return combine(arg2, arg3, arg4);
600   }
601   template <typename T1, typename T2, typename T3>
602   hash_code combine(const T1 &arg1, const T2 &arg2, const T3 &arg3) {
603     combine_data(get_hashable_data(arg1));
604     return combine(arg2, arg3);
605   }
606   template <typename T1, typename T2>
607   hash_code combine(const T1 &arg1, const T2 &arg2) {
608     combine_data(get_hashable_data(arg1));
609     return combine(arg2);
610   }
611   template <typename T1>
612   hash_code combine(const T1 &arg1) {
613     combine_data(get_hashable_data(arg1));
614     return combine();
615   }
616
617 #endif
618
619   /// \brief Base case for recursive, variadic combining.
620   ///
621   /// The base case when combining arguments recursively is reached when all
622   /// arguments have been handled. It flushes the remaining buffer and
623   /// constructs a hash_code.
624   hash_code combine() {
625     // Check whether the entire set of values fit in the buffer. If so, we'll
626     // use the optimized short hashing routine and skip state entirely.
627     if (length == 0)
628       return hash_short(buffer, buffer_ptr - buffer, seed);
629
630     // Mix the final buffer, rotating it if we did a partial fill in order to
631     // simulate doing a mix of the last 64-bytes. That is how the algorithm
632     // works when we have a contiguous byte sequence, and we want to emulate
633     // that here.
634     std::rotate(buffer, buffer_ptr, buffer_end);
635
636     // Mix this chunk into the current state.
637     state.mix(buffer);
638     length += buffer_ptr - buffer;
639
640     return state.finalize(length);
641   }
642 };
643
644 } // namespace detail
645 } // namespace hashing
646
647
648 #if __has_feature(__cxx_variadic_templates__)
649
650 /// \brief Combine values into a single hash_code.
651 ///
652 /// This routine accepts a varying number of arguments of any type. It will
653 /// attempt to combine them into a single hash_code. For user-defined types it
654 /// attempts to call a \see hash_value overload (via ADL) for the type. For
655 /// integer and pointer types it directly combines their data into the
656 /// resulting hash_code.
657 ///
658 /// The result is suitable for returning from a user's hash_value
659 /// *implementation* for their user-defined type. Consumers of a type should
660 /// *not* call this routine, they should instead call 'hash_value'.
661 template <typename ...Ts> hash_code hash_combine(const Ts &...args) {
662   // Recursively hash each argument using a helper class.
663   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
664   return helper.combine(args...);
665 }
666
667 #else
668
669 // What follows are manually exploded overloads for each argument width. See
670 // the above variadic definition for documentation and specification.
671
672 template <typename T1, typename T2, typename T3, typename T4, typename T5,
673           typename T6>
674 hash_code hash_combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
675                   const T4 &arg4, const T5 &arg5, const T6 &arg6) {
676   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
677   return helper.combine(arg1, arg2, arg3, arg4, arg5, arg6);
678 }
679 template <typename T1, typename T2, typename T3, typename T4, typename T5>
680 hash_code hash_combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
681                   const T4 &arg4, const T5 &arg5) {
682   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
683   return helper.combine(arg1, arg2, arg3, arg4, arg5);
684 }
685 template <typename T1, typename T2, typename T3, typename T4>
686 hash_code hash_combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
687                   const T4 &arg4) {
688   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
689   return helper.combine(arg1, arg2, arg3, arg4);
690 }
691 template <typename T1, typename T2, typename T3>
692 hash_code hash_combine(const T1 &arg1, const T2 &arg2, const T3 &arg3) {
693   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
694   return helper.combine(arg1, arg2, arg3);
695 }
696 template <typename T1, typename T2>
697 hash_code hash_combine(const T1 &arg1, const T2 &arg2) {
698   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
699   return helper.combine(arg1, arg2);
700 }
701 template <typename T1>
702 hash_code hash_combine(const T1 &arg1) {
703   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
704   return helper.combine(arg1);
705 }
706
707 #endif
708
709
710 // Implementation details for implementatinos of hash_value overloads provided
711 // here.
712 namespace hashing {
713 namespace detail {
714
715 /// \brief Helper to hash the value of a single integer.
716 ///
717 /// Overloads for smaller integer types are not provided to ensure consistent
718 /// behavior in the presence of integral promotions. Essentially,
719 /// "hash_value('4')" and "hash_value('0' + 4)" should be the same.
720 inline hash_code hash_integer_value(uint64_t value) {
721   // Similar to hash_4to8_bytes but using a seed instead of length.
722   const uint64_t seed = get_execution_seed();
723   const char *s = reinterpret_cast<const char *>(&value);
724   const uint64_t a = fetch32(s);
725   return hash_16_bytes(seed + (a << 3), fetch32(s + 4));
726 }
727
728 } // namespace detail
729 } // namespace hashing
730
731 // Declared and documented above, but defined here so that any of the hashing
732 // infrastructure is available.
733 template <typename T>
734 typename enable_if<is_integral<T>, hash_code>::type hash_value(T value) {
735   return ::llvm::hashing::detail::hash_integer_value(value);
736 }
737
738 // Declared and documented above, but defined here so that any of the hashing
739 // infrastructure is available.
740 template <typename T> hash_code hash_value(const T *ptr) {
741   return ::llvm::hashing::detail::hash_integer_value(
742     reinterpret_cast<uintptr_t>(ptr));
743 }
744
745 // Declared and documented above, but defined here so that any of the hashing
746 // infrastructure is available.
747 template <typename T, typename U>
748 hash_code hash_value(const std::pair<T, U> &arg) {
749   return hash_combine(arg.first, arg.second);
750 }
751
752 } // namespace llvm
753
754 #endif