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