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