diff --git a/CMakeLists.txt b/CMakeLists.txt index 0343801..1f9f49d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -39,6 +39,12 @@ if (WIN32) endif() include_directories(third_party/llvm/include) +include_directories(third_party/swift/include) +add_definitions( + -DLLVM_DISABLE_ABI_BREAKING_CHECKS_ENFORCING=1 + -DSWIFT_SUPPORT_OLD_MANGLING=1 + -DSWIFT_STDLIB_HAS_TYPE_PRINTING=1 +) add_executable(demumble demumble.cc third_party/llvm/lib/Demangle/Demangle.cpp @@ -47,6 +53,17 @@ add_executable(demumble third_party/llvm/lib/Demangle/MicrosoftDemangle.cpp third_party/llvm/lib/Demangle/MicrosoftDemangleNodes.cpp third_party/llvm/lib/Demangle/RustDemangle.cpp + third_party/swift/lib/Demangling/Context.cpp + third_party/swift/lib/Demangling/CrashReporter.cpp + third_party/swift/lib/Demangling/Demangler.cpp + third_party/swift/lib/Demangling/Errors.cpp + third_party/swift/lib/Demangling/ManglingUtils.cpp + third_party/swift/lib/Demangling/NodeDumper.cpp + third_party/swift/lib/Demangling/NodePrinter.cpp + third_party/swift/lib/Demangling/OldDemangler.cpp + third_party/swift/lib/Demangling/OldRemangler.cpp + third_party/swift/lib/Demangling/Punycode.cpp + third_party/swift/lib/Demangling/Remangler.cpp ) set_target_properties(demumble PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED ON) diff --git a/demumble.cc b/demumble.cc index bea3163..21e2902 100644 --- a/demumble.cc +++ b/demumble.cc @@ -5,6 +5,7 @@ #include #include "llvm/Demangle/Demangle.h" +#include "swift/Demangling/Demangle.h" const char kDemumbleVersion[] = "1.2.3.git"; @@ -33,6 +34,14 @@ static void print_demangled(const char* format, std::string_view s, } else if (char* ms = llvm::microsoftDemangle(s, n_used, NULL)) { printf(format, ms, (int)s.size(), s.data()); free(ms); + } else if (swift::Demangle::isSwiftSymbol(s)) { + swift::Demangle::DemangleOptions options; + options.SynthesizeSugarOnTypes = true; + std::string swift = swift::Demangle::demangleSymbolAsString(s, options); + if (swift == s) + printf("%.*s", (int)s.size(), s.data()); // Not a mangled name + else + printf(format, swift.c_str(), (int)s.size(), s.data()); } else { printf("%.*s", (int)s.size(), s.data()); } @@ -49,6 +58,12 @@ static bool is_mangle_char_rust(char c) { (c >= '0' && c <= '9') || c == '_'; } +static bool is_mangle_char_swift(char c) { + // https://github.com/swiftlang/swift/blob/main/docs/ABI/Mangling.rst + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '_' || c == '$'; +} + static bool is_mangle_char_win(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || strchr("?_@$", c); @@ -68,6 +83,18 @@ static bool is_plausible_rust_prefix(char* s) { return s[0] == '_' && s[1] == 'R'; } +static bool is_plausible_swift_prefix(char* s) { + // https://github.com/swiftlang/swift/blob/main/docs/ABI/Mangling.rst + // But also swift/test/Demangle/Inputs/manglings.txt, which has + // _Tt, _TF etc as prefix. + + // FIXME: This is missing prefix `@__swiftmacro_`. + return + (s[0] == '$' && s[1] == 's') || + (s[0] == '_' && s[1] == 'T') || + (s[0] == '$' && s[1] == 'S'); +} + static char buf[8192]; int main(int argc, char* argv[]) { enum { kPrintAll, kPrintMatching } print_mode = kPrintAll; @@ -119,7 +146,7 @@ int main(int argc, char* argv[]) { char* end = cur + strlen(cur); while (cur != end) { - size_t offset_to_possible_symbol = strcspn(cur, "_?"); + size_t offset_to_possible_symbol = strcspn(cur, "_?$"); if (print_mode == kPrintAll) printf("%.*s", static_cast(offset_to_possible_symbol), cur); else if (need_separator) @@ -139,6 +166,9 @@ int main(int argc, char* argv[]) { else if (is_plausible_rust_prefix(cur)) while (cur + n_sym != end && is_mangle_char_rust(cur[n_sym])) ++n_sym; + else if (is_plausible_swift_prefix(cur)) + while (cur + n_sym != end && is_mangle_char_swift(cur[n_sym])) + ++n_sym; else { if (print_mode == kPrintAll) printf("_"); diff --git a/demumble_test.py b/demumble_test.py index c7d6242..6ed3533 100755 --- a/demumble_test.py +++ b/demumble_test.py @@ -9,6 +9,10 @@ 'std::mem::align_of::\nmylib::foo::bar\n'), ('demumble < _RINvNtC3std3mem8align_ofdE _RNvNvC5mylib3foo3bar', 'std::mem::align_of::\nmylib::foo::bar\n'), + ('demumble _TtP3foo3bar_', 'foo.bar\n'), + ('demumble < _TtP3foo3bar_', 'foo.bar\n'), + ('demumble $sSS5countSivg', 'Swift.String.count.getter : Swift.Int\n'), + ('demumble < $sSS5countSivg', 'Swift.String.count.getter : Swift.Int\n'), ('demumble ?Fxi@@YAHP6AHH@Z@Z', 'int __cdecl Fxi(int (__cdecl *)(int))\n'), ('demumble ??0S@@QEAA@$$QEAU0@@Z', 'public: __cdecl S::S(struct S &&)\n'), ('demumble ??_C@_02PCEFGMJL@hi?$AA@', '"hi"\n'), diff --git a/scripts/copy-swift-demangle.sh b/scripts/copy-swift-demangle.sh new file mode 100755 index 0000000..f3cf787 --- /dev/null +++ b/scripts/copy-swift-demangle.sh @@ -0,0 +1,84 @@ +#!/bin/bash + +# Swift's demangler is much less hermetic than LLVM's. This copies all the +# code needed by Swift's demangler into this repository. + +set -eu + +# Adopt these three to match your local swift checkout and your local +# llvm checkout and build dir: + +LLVM_SRC=$HOME/src/llvm-project/llvm +SWIFT_SRC=$HOME/src/swift +LLVM_HEADER_GEN_SRC=$HOME/src/llvm-project/out/gn/gen/llvm/include/llvm + +# The rest only needs updating if the set of needed files changes: + +cd "$(dirname "$0")"/.. + +LLVM_INC_SRC=$LLVM_SRC/include/llvm +LLVM_DST=third_party/llvm +LLVM_INC_DST=$LLVM_DST/include/llvm + +SWIFT_INC_SRC=$SWIFT_SRC/include/swift +SWIFT_DST=third_party/swift +SWIFT_INC_DST=$SWIFT_DST/include/swift + +rm -rf $LLVM_INC_DST/ADT +rm -rf $LLVM_INC_DST/Config +rm -rf $LLVM_INC_DST/Support +rm -rf $LLVM_DST/include/llvm-c +rm -rf $SWIFT_DST + +mkdir -p $LLVM_INC_DST/ADT +cp "$LLVM_INC_SRC"/ADT/ADL.h $LLVM_INC_DST/ADT +cp "$LLVM_INC_SRC"/ADT/DenseMapInfo.h $LLVM_INC_DST/ADT +cp "$LLVM_INC_SRC"/ADT/Hashing.h $LLVM_INC_DST/ADT +cp "$LLVM_INC_SRC"/ADT/STLExtras.h $LLVM_INC_DST/ADT +cp "$LLVM_INC_SRC"/ADT/STLForwardCompat.h $LLVM_INC_DST/ADT +cp "$LLVM_INC_SRC"/ADT/STLFunctionalExtras.h $LLVM_INC_DST/ADT +cp "$LLVM_INC_SRC"/ADT/StringRef.h $LLVM_INC_DST/ADT +cp "$LLVM_INC_SRC"/ADT/StringSwitch.h $LLVM_INC_DST/ADT +cp "$LLVM_INC_SRC"/ADT/bit.h $LLVM_INC_DST/ADT +cp "$LLVM_INC_SRC"/ADT/iterator.h $LLVM_INC_DST/ADT +cp "$LLVM_INC_SRC"/ADT/iterator_range.h $LLVM_INC_DST/ADT + +mkdir -p $LLVM_INC_DST/Config +cp "$LLVM_HEADER_GEN_SRC"/Config/abi-breaking.h $LLVM_INC_DST/Config +cp "$LLVM_HEADER_GEN_SRC"/Config/llvm-config.h $LLVM_INC_DST/Config + +mkdir -p $LLVM_INC_DST/Support +cp "$LLVM_INC_SRC"/Support/Casting.h $LLVM_INC_DST/Support +cp "$LLVM_INC_SRC"/Support/Compiler.h $LLVM_INC_DST/Support +cp "$LLVM_INC_SRC"/Support/DataTypes.h $LLVM_INC_DST/Support +cp "$LLVM_INC_SRC"/Support/ErrorHandling.h $LLVM_INC_DST/Support +cp "$LLVM_INC_SRC"/Support/SwapByteOrder.h $LLVM_INC_DST/Support +cp "$LLVM_INC_SRC"/Support/type_traits.h $LLVM_INC_DST/Support + +mkdir -p $LLVM_DST/include/llvm-c +cp "$LLVM_SRC"/include/llvm-c/DataTypes.h $LLVM_DST/include/llvm-c + +mkdir -p $SWIFT_DST +cp "$SWIFT_SRC"/LICENSE.txt $SWIFT_DST + +mkdir -p $SWIFT_INC_DST +cp -R "$SWIFT_INC_SRC"/Demangling $SWIFT_INC_DST +cp "$SWIFT_INC_SRC"/Strings.h $SWIFT_INC_DST + +mkdir -p $SWIFT_INC_DST/ABI +cp "$SWIFT_INC_SRC"/ABI/InvertibleProtocols.def $SWIFT_INC_DST/ABI + +mkdir -p $SWIFT_INC_DST/AST +cp "$SWIFT_INC_SRC"/AST/Ownership.h $SWIFT_INC_DST/AST +cp "$SWIFT_INC_SRC"/AST/ReferenceStorage.def $SWIFT_INC_DST/AST + +mkdir -p $SWIFT_INC_DST/Basic +cp "$SWIFT_INC_SRC"/Basic/Assertions.h $SWIFT_INC_DST/Basic +cp "$SWIFT_INC_SRC"/Basic/InlineBitfield.h $SWIFT_INC_DST/Basic +cp "$SWIFT_INC_SRC"/Basic/LLVM.h $SWIFT_INC_DST/Basic +cp "$SWIFT_INC_SRC"/Basic/MacroRoles.def $SWIFT_INC_DST/Basic +cp "$SWIFT_INC_SRC"/Basic/STLExtras.h $SWIFT_INC_DST/Basic + +mkdir -p $SWIFT_DST/lib +cp -R "$SWIFT_SRC"/lib/Demangling $SWIFT_DST/lib +rm $SWIFT_DST/lib/Demangling/CMakeLists.txt diff --git a/third_party/llvm/include/llvm-c/DataTypes.h b/third_party/llvm/include/llvm-c/DataTypes.h new file mode 100644 index 0000000..4eb0ac9 --- /dev/null +++ b/third_party/llvm/include/llvm-c/DataTypes.h @@ -0,0 +1,80 @@ +/*===-- include/llvm-c/DataTypes.h - Define fixed size types ------*- C -*-===*\ +|* *| +|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| +|* Exceptions. *| +|* See https://llvm.org/LICENSE.txt for license information. *| +|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This file contains definitions to figure out the size of _HOST_ data types.*| +|* This file is important because different host OS's define different macros,*| +|* which makes portability tough. This file exports the following *| +|* definitions: *| +|* *| +|* [u]int(32|64)_t : typedefs for signed and unsigned 32/64 bit system types*| +|* [U]INT(8|16|32|64)_(MIN|MAX) : Constants for the min and max values. *| +|* *| +|* No library is required when using these functions. *| +|* *| +|*===----------------------------------------------------------------------===*/ + +/* Please leave this file C-compatible. */ + +#ifndef LLVM_C_DATATYPES_H +#define LLVM_C_DATATYPES_H + +#include +#include + +#ifndef _MSC_VER + +#if !defined(UINT32_MAX) +# error "The standard header is not C++11 compliant. Must #define "\ + "__STDC_LIMIT_MACROS before #including llvm-c/DataTypes.h" +#endif + +#if !defined(UINT32_C) +# error "The standard header is not C++11 compliant. Must #define "\ + "__STDC_CONSTANT_MACROS before #including llvm-c/DataTypes.h" +#endif + +/* Note that includes , if this is a C99 system. */ +#include + +#ifdef _AIX +// GCC is strict about defining large constants: they must have LL modifier. +#undef INT64_MAX +#undef INT64_MIN +#endif + +#else /* _MSC_VER */ +#ifdef __cplusplus +#include +#include +#else +#include +#include +#endif +#include + +#if defined(_WIN64) +typedef signed __int64 ssize_t; +#else +typedef signed int ssize_t; +#endif /* _WIN64 */ + +#endif /* _MSC_VER */ + +/* Set defaults for constants which we cannot find. */ +#if !defined(INT64_MAX) +# define INT64_MAX 9223372036854775807LL +#endif +#if !defined(INT64_MIN) +# define INT64_MIN ((-INT64_MAX)-1) +#endif +#if !defined(UINT64_MAX) +# define UINT64_MAX 0xffffffffffffffffULL +#endif + +#endif /* LLVM_C_DATATYPES_H */ diff --git a/third_party/llvm/include/llvm/ADT/ADL.h b/third_party/llvm/include/llvm/ADT/ADL.h new file mode 100644 index 0000000..812d9a4 --- /dev/null +++ b/third_party/llvm/include/llvm/ADT/ADL.h @@ -0,0 +1,135 @@ +//===- llvm/ADT/ADL.h - Argument dependent lookup utilities -----*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_ADT_ADL_H +#define LLVM_ADT_ADL_H + +#include +#include +#include + +namespace llvm { + +// Only used by compiler if both template types are the same. Useful when +// using SFINAE to test for the existence of member functions. +template struct SameType; + +namespace adl_detail { + +using std::begin; + +template +constexpr auto begin_impl(RangeT &&range) + -> decltype(begin(std::forward(range))) { + return begin(std::forward(range)); +} + +using std::end; + +template +constexpr auto end_impl(RangeT &&range) + -> decltype(end(std::forward(range))) { + return end(std::forward(range)); +} + +using std::rbegin; + +template +constexpr auto rbegin_impl(RangeT &&range) + -> decltype(rbegin(std::forward(range))) { + return rbegin(std::forward(range)); +} + +using std::rend; + +template +constexpr auto rend_impl(RangeT &&range) + -> decltype(rend(std::forward(range))) { + return rend(std::forward(range)); +} + +using std::swap; + +template +constexpr void swap_impl(T &&lhs, + T &&rhs) noexcept(noexcept(swap(std::declval(), + std::declval()))) { + swap(std::forward(lhs), std::forward(rhs)); +} + +using std::size; + +template +constexpr auto size_impl(RangeT &&range) + -> decltype(size(std::forward(range))) { + return size(std::forward(range)); +} + +} // end namespace adl_detail + +/// Returns the begin iterator to \p range using `std::begin` and +/// function found through Argument-Dependent Lookup (ADL). +template +constexpr auto adl_begin(RangeT &&range) + -> decltype(adl_detail::begin_impl(std::forward(range))) { + return adl_detail::begin_impl(std::forward(range)); +} + +/// Returns the end iterator to \p range using `std::end` and +/// functions found through Argument-Dependent Lookup (ADL). +template +constexpr auto adl_end(RangeT &&range) + -> decltype(adl_detail::end_impl(std::forward(range))) { + return adl_detail::end_impl(std::forward(range)); +} + +/// Returns the reverse-begin iterator to \p range using `std::rbegin` and +/// function found through Argument-Dependent Lookup (ADL). +template +constexpr auto adl_rbegin(RangeT &&range) + -> decltype(adl_detail::rbegin_impl(std::forward(range))) { + return adl_detail::rbegin_impl(std::forward(range)); +} + +/// Returns the reverse-end iterator to \p range using `std::rend` and +/// functions found through Argument-Dependent Lookup (ADL). +template +constexpr auto adl_rend(RangeT &&range) + -> decltype(adl_detail::rend_impl(std::forward(range))) { + return adl_detail::rend_impl(std::forward(range)); +} + +/// Swaps \p lhs with \p rhs using `std::swap` and functions found through +/// Argument-Dependent Lookup (ADL). +template +constexpr void adl_swap(T &&lhs, T &&rhs) noexcept( + noexcept(adl_detail::swap_impl(std::declval(), std::declval()))) { + adl_detail::swap_impl(std::forward(lhs), std::forward(rhs)); +} + +/// Returns the size of \p range using `std::size` and functions found through +/// Argument-Dependent Lookup (ADL). +template +constexpr auto adl_size(RangeT &&range) + -> decltype(adl_detail::size_impl(std::forward(range))) { + return adl_detail::size_impl(std::forward(range)); +} + +namespace detail { + +template +using IterOfRange = decltype(adl_begin(std::declval())); + +template +using ValueOfRange = + std::remove_reference_t()))>; + +} // namespace detail +} // namespace llvm + +#endif // LLVM_ADT_ADL_H diff --git a/third_party/llvm/include/llvm/ADT/DenseMapInfo.h b/third_party/llvm/include/llvm/ADT/DenseMapInfo.h new file mode 100644 index 0000000..07c37e3 --- /dev/null +++ b/third_party/llvm/include/llvm/ADT/DenseMapInfo.h @@ -0,0 +1,325 @@ +//===- llvm/ADT/DenseMapInfo.h - Type traits for DenseMap -------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// This file defines DenseMapInfo traits for DenseMap. +/// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_ADT_DENSEMAPINFO_H +#define LLVM_ADT_DENSEMAPINFO_H + +#include +#include +#include +#include +#include +#include + +namespace llvm { + +namespace densemap::detail { +// A bit mixer with very low latency using one multiplications and one +// xor-shift. The constant is from splitmix64. +inline uint64_t mix(uint64_t x) { + x *= 0xbf58476d1ce4e5b9u; + x ^= x >> 31; + return x; +} +} // namespace densemap::detail + +namespace detail { + +/// Simplistic combination of 32-bit hash values into 32-bit hash values. +inline unsigned combineHashValue(unsigned a, unsigned b) { + uint64_t x = (uint64_t)a << 32 | (uint64_t)b; + return (unsigned)densemap::detail::mix(x); +} + +} // end namespace detail + +/// An information struct used to provide DenseMap with the various necessary +/// components for a given value type `T`. `Enable` is an optional additional +/// parameter that is used to support SFINAE (generally using std::enable_if_t) +/// in derived DenseMapInfo specializations; in non-SFINAE use cases this should +/// just be `void`. +template +struct DenseMapInfo { + //static inline T getEmptyKey(); + //static inline T getTombstoneKey(); + //static unsigned getHashValue(const T &Val); + //static bool isEqual(const T &LHS, const T &RHS); +}; + +// Provide DenseMapInfo for all pointers. Come up with sentinel pointer values +// that are aligned to alignof(T) bytes, but try to avoid requiring T to be +// complete. This allows clients to instantiate DenseMap with forward +// declared key types. Assume that no pointer key type requires more than 4096 +// bytes of alignment. +template +struct DenseMapInfo { + // The following should hold, but it would require T to be complete: + // static_assert(alignof(T) <= (1 << Log2MaxAlign), + // "DenseMap does not support pointer keys requiring more than " + // "Log2MaxAlign bits of alignment"); + static constexpr uintptr_t Log2MaxAlign = 12; + + static inline T* getEmptyKey() { + uintptr_t Val = static_cast(-1); + Val <<= Log2MaxAlign; + return reinterpret_cast(Val); + } + + static inline T* getTombstoneKey() { + uintptr_t Val = static_cast(-2); + Val <<= Log2MaxAlign; + return reinterpret_cast(Val); + } + + static unsigned getHashValue(const T *PtrVal) { + return (unsigned((uintptr_t)PtrVal) >> 4) ^ + (unsigned((uintptr_t)PtrVal) >> 9); + } + + static bool isEqual(const T *LHS, const T *RHS) { return LHS == RHS; } +}; + +// Provide DenseMapInfo for chars. +template<> struct DenseMapInfo { + static inline char getEmptyKey() { return ~0; } + static inline char getTombstoneKey() { return ~0 - 1; } + static unsigned getHashValue(const char& Val) { return Val * 37U; } + + static bool isEqual(const char &LHS, const char &RHS) { + return LHS == RHS; + } +}; + +// Provide DenseMapInfo for unsigned chars. +template <> struct DenseMapInfo { + static inline unsigned char getEmptyKey() { return ~0; } + static inline unsigned char getTombstoneKey() { return ~0 - 1; } + static unsigned getHashValue(const unsigned char &Val) { return Val * 37U; } + + static bool isEqual(const unsigned char &LHS, const unsigned char &RHS) { + return LHS == RHS; + } +}; + +// Provide DenseMapInfo for unsigned shorts. +template <> struct DenseMapInfo { + static inline unsigned short getEmptyKey() { return 0xFFFF; } + static inline unsigned short getTombstoneKey() { return 0xFFFF - 1; } + static unsigned getHashValue(const unsigned short &Val) { return Val * 37U; } + + static bool isEqual(const unsigned short &LHS, const unsigned short &RHS) { + return LHS == RHS; + } +}; + +// Provide DenseMapInfo for unsigned ints. +template<> struct DenseMapInfo { + static inline unsigned getEmptyKey() { return ~0U; } + static inline unsigned getTombstoneKey() { return ~0U - 1; } + static unsigned getHashValue(const unsigned& Val) { return Val * 37U; } + + static bool isEqual(const unsigned& LHS, const unsigned& RHS) { + return LHS == RHS; + } +}; + +// Provide DenseMapInfo for unsigned longs. +template<> struct DenseMapInfo { + static inline unsigned long getEmptyKey() { return ~0UL; } + static inline unsigned long getTombstoneKey() { return ~0UL - 1L; } + + static unsigned getHashValue(const unsigned long& Val) { + if constexpr (sizeof(Val) == 4) + return DenseMapInfo::getHashValue(Val); + else + return densemap::detail::mix(Val); + } + + static bool isEqual(const unsigned long& LHS, const unsigned long& RHS) { + return LHS == RHS; + } +}; + +// Provide DenseMapInfo for unsigned long longs. +template<> struct DenseMapInfo { + static inline unsigned long long getEmptyKey() { return ~0ULL; } + static inline unsigned long long getTombstoneKey() { return ~0ULL - 1ULL; } + + static unsigned getHashValue(const unsigned long long& Val) { + return densemap::detail::mix(Val); + } + + static bool isEqual(const unsigned long long& LHS, + const unsigned long long& RHS) { + return LHS == RHS; + } +}; + +// Provide DenseMapInfo for shorts. +template <> struct DenseMapInfo { + static inline short getEmptyKey() { return 0x7FFF; } + static inline short getTombstoneKey() { return -0x7FFF - 1; } + static unsigned getHashValue(const short &Val) { return Val * 37U; } + static bool isEqual(const short &LHS, const short &RHS) { return LHS == RHS; } +}; + +// Provide DenseMapInfo for ints. +template<> struct DenseMapInfo { + static inline int getEmptyKey() { return 0x7fffffff; } + static inline int getTombstoneKey() { return -0x7fffffff - 1; } + static unsigned getHashValue(const int& Val) { return (unsigned)(Val * 37U); } + + static bool isEqual(const int& LHS, const int& RHS) { + return LHS == RHS; + } +}; + +// Provide DenseMapInfo for longs. +template<> struct DenseMapInfo { + static inline long getEmptyKey() { + return (1UL << (sizeof(long) * 8 - 1)) - 1UL; + } + + static inline long getTombstoneKey() { return getEmptyKey() - 1L; } + + static unsigned getHashValue(const long& Val) { + return (unsigned)(Val * 37UL); + } + + static bool isEqual(const long& LHS, const long& RHS) { + return LHS == RHS; + } +}; + +// Provide DenseMapInfo for long longs. +template<> struct DenseMapInfo { + static inline long long getEmptyKey() { return 0x7fffffffffffffffLL; } + static inline long long getTombstoneKey() { return -0x7fffffffffffffffLL-1; } + + static unsigned getHashValue(const long long& Val) { + return (unsigned)(Val * 37ULL); + } + + static bool isEqual(const long long& LHS, + const long long& RHS) { + return LHS == RHS; + } +}; + +// Provide DenseMapInfo for all pairs whose members have info. +template +struct DenseMapInfo> { + using Pair = std::pair; + using FirstInfo = DenseMapInfo; + using SecondInfo = DenseMapInfo; + + static inline Pair getEmptyKey() { + return std::make_pair(FirstInfo::getEmptyKey(), + SecondInfo::getEmptyKey()); + } + + static inline Pair getTombstoneKey() { + return std::make_pair(FirstInfo::getTombstoneKey(), + SecondInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const Pair& PairVal) { + return detail::combineHashValue(FirstInfo::getHashValue(PairVal.first), + SecondInfo::getHashValue(PairVal.second)); + } + + // Expose an additional function intended to be used by other + // specializations of DenseMapInfo without needing to know how + // to combine hash values manually + static unsigned getHashValuePiecewise(const T &First, const U &Second) { + return detail::combineHashValue(FirstInfo::getHashValue(First), + SecondInfo::getHashValue(Second)); + } + + static bool isEqual(const Pair &LHS, const Pair &RHS) { + return FirstInfo::isEqual(LHS.first, RHS.first) && + SecondInfo::isEqual(LHS.second, RHS.second); + } +}; + +// Provide DenseMapInfo for all tuples whose members have info. +template struct DenseMapInfo> { + using Tuple = std::tuple; + + static inline Tuple getEmptyKey() { + return Tuple(DenseMapInfo::getEmptyKey()...); + } + + static inline Tuple getTombstoneKey() { + return Tuple(DenseMapInfo::getTombstoneKey()...); + } + + template + static unsigned getHashValueImpl(const Tuple &values, std::false_type) { + using EltType = std::tuple_element_t; + std::integral_constant atEnd; + return detail::combineHashValue( + DenseMapInfo::getHashValue(std::get(values)), + getHashValueImpl(values, atEnd)); + } + + template + static unsigned getHashValueImpl(const Tuple &, std::true_type) { + return 0; + } + + static unsigned getHashValue(const std::tuple &values) { + std::integral_constant atEnd; + return getHashValueImpl<0>(values, atEnd); + } + + template + static bool isEqualImpl(const Tuple &lhs, const Tuple &rhs, std::false_type) { + using EltType = std::tuple_element_t; + std::integral_constant atEnd; + return DenseMapInfo::isEqual(std::get(lhs), std::get(rhs)) && + isEqualImpl(lhs, rhs, atEnd); + } + + template + static bool isEqualImpl(const Tuple &, const Tuple &, std::true_type) { + return true; + } + + static bool isEqual(const Tuple &lhs, const Tuple &rhs) { + std::integral_constant atEnd; + return isEqualImpl<0>(lhs, rhs, atEnd); + } +}; + +// Provide DenseMapInfo for enum classes. +template +struct DenseMapInfo>> { + using UnderlyingType = std::underlying_type_t; + using Info = DenseMapInfo; + + static Enum getEmptyKey() { return static_cast(Info::getEmptyKey()); } + + static Enum getTombstoneKey() { + return static_cast(Info::getTombstoneKey()); + } + + static unsigned getHashValue(const Enum &Val) { + return Info::getHashValue(static_cast(Val)); + } + + static bool isEqual(const Enum &LHS, const Enum &RHS) { return LHS == RHS; } +}; +} // end namespace llvm + +#endif // LLVM_ADT_DENSEMAPINFO_H diff --git a/third_party/llvm/include/llvm/ADT/Hashing.h b/third_party/llvm/include/llvm/ADT/Hashing.h new file mode 100644 index 0000000..1099662 --- /dev/null +++ b/third_party/llvm/include/llvm/ADT/Hashing.h @@ -0,0 +1,680 @@ +//===-- llvm/ADT/Hashing.h - Utilities for hashing --------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements the newly proposed standard C++ interfaces for hashing +// arbitrary data and building hash functions for user-defined types. This +// interface was originally proposed in N3333[1] and is currently under review +// for inclusion in a future TR and/or standard. +// +// The primary interfaces provide are comprised of one type and three functions: +// +// -- 'hash_code' class is an opaque type representing the hash code for some +// data. It is the intended product of hashing, and can be used to implement +// hash tables, checksumming, and other common uses of hashes. It is not an +// integer type (although it can be converted to one) because it is risky +// to assume much about the internals of a hash_code. In particular, each +// execution of the program has a high probability of producing a different +// hash_code for a given input. Thus their values are not stable to save or +// persist, and should only be used during the execution for the +// construction of hashing datastructures. +// +// -- 'hash_value' is a function designed to be overloaded for each +// user-defined type which wishes to be used within a hashing context. It +// should be overloaded within the user-defined type's namespace and found +// via ADL. Overloads for primitive types are provided by this library. +// +// -- 'hash_combine' and 'hash_combine_range' are functions designed to aid +// programmers in easily and intuitively combining a set of data into +// a single hash_code for their object. They should only logically be used +// within the implementation of a 'hash_value' routine or similar context. +// +// Note that 'hash_combine_range' contains very special logic for hashing +// a contiguous array of integers or pointers. This logic is *extremely* fast, +// on a modern Intel "Gainestown" Xeon (Nehalem uarch) @2.2 GHz, these were +// benchmarked at over 6.5 GiB/s for large keys, and <20 cycles/hash for keys +// under 32-bytes. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_ADT_HASHING_H +#define LLVM_ADT_HASHING_H + +#include "llvm/Config/abi-breaking.h" +#include "llvm/Support/DataTypes.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/SwapByteOrder.h" +#include "llvm/Support/type_traits.h" +#include +#include +#include +#include +#include +#include +#include + +namespace llvm { +template struct DenseMapInfo; + +/// An opaque object representing a hash code. +/// +/// This object represents the result of hashing some entity. It is intended to +/// be used to implement hashtables or other hashing-based data structures. +/// While it wraps and exposes a numeric value, this value should not be +/// trusted to be stable or predictable across processes or executions. +/// +/// In order to obtain the hash_code for an object 'x': +/// \code +/// using llvm::hash_value; +/// llvm::hash_code code = hash_value(x); +/// \endcode +class hash_code { + size_t value; + +public: + /// Default construct a hash_code. + /// Note that this leaves the value uninitialized. + hash_code() = default; + + /// Form a hash code directly from a numerical value. + hash_code(size_t value) : value(value) {} + + /// Convert the hash code to its numerical value for use. + /*explicit*/ operator size_t() const { return value; } + + friend bool operator==(const hash_code &lhs, const hash_code &rhs) { + return lhs.value == rhs.value; + } + friend bool operator!=(const hash_code &lhs, const hash_code &rhs) { + return lhs.value != rhs.value; + } + + /// Allow a hash_code to be directly run through hash_value. + friend size_t hash_value(const hash_code &code) { return code.value; } +}; + +/// Compute a hash_code for any integer value. +/// +/// Note that this function is intended to compute the same hash_code for +/// a particular value without regard to the pre-promotion type. This is in +/// contrast to hash_combine which may produce different hash_codes for +/// differing argument types even if they would implicit promote to a common +/// type without changing the value. +template +std::enable_if_t::value, hash_code> hash_value(T value); + +/// Compute a hash_code for a pointer's address. +/// +/// N.B.: This hashes the *address*. Not the value and not the type. +template hash_code hash_value(const T *ptr); + +/// Compute a hash_code for a pair of objects. +template +hash_code hash_value(const std::pair &arg); + +/// Compute a hash_code for a tuple. +template +hash_code hash_value(const std::tuple &arg); + +/// Compute a hash_code for a standard string. +template +hash_code hash_value(const std::basic_string &arg); + +/// Compute a hash_code for a standard string. +template hash_code hash_value(const std::optional &arg); + +// All of the implementation details of actually computing the various hash +// code values are held within this namespace. These routines are included in +// the header file mainly to allow inlining and constant propagation. +namespace hashing { +namespace detail { + +inline uint64_t fetch64(const char *p) { + uint64_t result; + memcpy(&result, p, sizeof(result)); + if (sys::IsBigEndianHost) + sys::swapByteOrder(result); + return result; +} + +inline uint32_t fetch32(const char *p) { + uint32_t result; + memcpy(&result, p, sizeof(result)); + if (sys::IsBigEndianHost) + sys::swapByteOrder(result); + return result; +} + +/// Some primes between 2^63 and 2^64 for various uses. +static constexpr uint64_t k0 = 0xc3a5c85c97cb3127ULL; +static constexpr uint64_t k1 = 0xb492b66fbe98f273ULL; +static constexpr uint64_t k2 = 0x9ae16a3b2f90404fULL; +static constexpr uint64_t k3 = 0xc949d7c7509e6557ULL; + +/// Bitwise right rotate. +/// Normally this will compile to a single instruction, especially if the +/// shift is a manifest constant. +inline uint64_t rotate(uint64_t val, size_t shift) { + // Avoid shifting by 64: doing so yields an undefined result. + return shift == 0 ? val : ((val >> shift) | (val << (64 - shift))); +} + +inline uint64_t shift_mix(uint64_t val) { + return val ^ (val >> 47); +} + +inline uint64_t hash_16_bytes(uint64_t low, uint64_t high) { + // Murmur-inspired hashing. + const uint64_t kMul = 0x9ddfea08eb382d69ULL; + uint64_t a = (low ^ high) * kMul; + a ^= (a >> 47); + uint64_t b = (high ^ a) * kMul; + b ^= (b >> 47); + b *= kMul; + return b; +} + +inline uint64_t hash_1to3_bytes(const char *s, size_t len, uint64_t seed) { + uint8_t a = s[0]; + uint8_t b = s[len >> 1]; + uint8_t c = s[len - 1]; + uint32_t y = static_cast(a) + (static_cast(b) << 8); + uint32_t z = static_cast(len) + (static_cast(c) << 2); + return shift_mix(y * k2 ^ z * k3 ^ seed) * k2; +} + +inline uint64_t hash_4to8_bytes(const char *s, size_t len, uint64_t seed) { + uint64_t a = fetch32(s); + return hash_16_bytes(len + (a << 3), seed ^ fetch32(s + len - 4)); +} + +inline uint64_t hash_9to16_bytes(const char *s, size_t len, uint64_t seed) { + uint64_t a = fetch64(s); + uint64_t b = fetch64(s + len - 8); + return hash_16_bytes(seed ^ a, rotate(b + len, len)) ^ b; +} + +inline uint64_t hash_17to32_bytes(const char *s, size_t len, uint64_t seed) { + uint64_t a = fetch64(s) * k1; + uint64_t b = fetch64(s + 8); + uint64_t c = fetch64(s + len - 8) * k2; + uint64_t d = fetch64(s + len - 16) * k0; + return hash_16_bytes(llvm::rotr(a - b, 43) + + llvm::rotr(c ^ seed, 30) + d, + a + llvm::rotr(b ^ k3, 20) - c + len + seed); +} + +inline uint64_t hash_33to64_bytes(const char *s, size_t len, uint64_t seed) { + uint64_t z = fetch64(s + 24); + uint64_t a = fetch64(s) + (len + fetch64(s + len - 16)) * k0; + uint64_t b = llvm::rotr(a + z, 52); + uint64_t c = llvm::rotr(a, 37); + a += fetch64(s + 8); + c += llvm::rotr(a, 7); + a += fetch64(s + 16); + uint64_t vf = a + z; + uint64_t vs = b + llvm::rotr(a, 31) + c; + a = fetch64(s + 16) + fetch64(s + len - 32); + z = fetch64(s + len - 8); + b = llvm::rotr(a + z, 52); + c = llvm::rotr(a, 37); + a += fetch64(s + len - 24); + c += llvm::rotr(a, 7); + a += fetch64(s + len - 16); + uint64_t wf = a + z; + uint64_t ws = b + llvm::rotr(a, 31) + c; + uint64_t r = shift_mix((vf + ws) * k2 + (wf + vs) * k0); + return shift_mix((seed ^ (r * k0)) + vs) * k2; +} + +inline uint64_t hash_short(const char *s, size_t length, uint64_t seed) { + if (length >= 4 && length <= 8) + return hash_4to8_bytes(s, length, seed); + if (length > 8 && length <= 16) + return hash_9to16_bytes(s, length, seed); + if (length > 16 && length <= 32) + return hash_17to32_bytes(s, length, seed); + if (length > 32) + return hash_33to64_bytes(s, length, seed); + if (length != 0) + return hash_1to3_bytes(s, length, seed); + + return k2 ^ seed; +} + +/// The intermediate state used during hashing. +/// Currently, the algorithm for computing hash codes is based on CityHash and +/// keeps 56 bytes of arbitrary state. +struct hash_state { + uint64_t h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0; + + /// Create a new hash_state structure and initialize it based on the + /// seed and the first 64-byte chunk. + /// This effectively performs the initial mix. + static hash_state create(const char *s, uint64_t seed) { + hash_state state = {0, + seed, + hash_16_bytes(seed, k1), + llvm::rotr(seed ^ k1, 49), + seed * k1, + shift_mix(seed), + 0}; + state.h6 = hash_16_bytes(state.h4, state.h5); + state.mix(s); + return state; + } + + /// Mix 32-bytes from the input sequence into the 16-bytes of 'a' + /// and 'b', including whatever is already in 'a' and 'b'. + static void mix_32_bytes(const char *s, uint64_t &a, uint64_t &b) { + a += fetch64(s); + uint64_t c = fetch64(s + 24); + b = llvm::rotr(b + a + c, 21); + uint64_t d = a; + a += fetch64(s + 8) + fetch64(s + 16); + b += llvm::rotr(a, 44) + d; + a += c; + } + + /// Mix in a 64-byte buffer of data. + /// We mix all 64 bytes even when the chunk length is smaller, but we + /// record the actual length. + void mix(const char *s) { + h0 = llvm::rotr(h0 + h1 + h3 + fetch64(s + 8), 37) * k1; + h1 = llvm::rotr(h1 + h4 + fetch64(s + 48), 42) * k1; + h0 ^= h6; + h1 += h3 + fetch64(s + 40); + h2 = llvm::rotr(h2 + h5, 33) * k1; + h3 = h4 * k1; + h4 = h0 + h5; + mix_32_bytes(s, h3, h4); + h5 = h2 + h6; + h6 = h1 + fetch64(s + 16); + mix_32_bytes(s + 32, h5, h6); + std::swap(h2, h0); + } + + /// Compute the final 64-bit hash code value based on the current + /// state and the length of bytes hashed. + uint64_t finalize(size_t length) { + return hash_16_bytes(hash_16_bytes(h3, h5) + shift_mix(h1) * k1 + h2, + hash_16_bytes(h4, h6) + shift_mix(length) * k1 + h0); + } +}; + +/// In LLVM_ENABLE_ABI_BREAKING_CHECKS builds, the seed is non-deterministic +/// per process (address of a function in LLVMSupport) to prevent having users +/// depend on the particular hash values. On platforms without ASLR, this is +/// still likely non-deterministic per build. +inline uint64_t get_execution_seed() { + // Work around x86-64 negative offset folding for old Clang -fno-pic + // https://reviews.llvm.org/D93931 +#if LLVM_ENABLE_ABI_BREAKING_CHECKS && \ + (!defined(__clang__) || __clang_major__ > 11) + return static_cast( + reinterpret_cast(&install_fatal_error_handler)); +#else + return 0xff51afd7ed558ccdULL; +#endif +} + + +/// Trait to indicate whether a type's bits can be hashed directly. +/// +/// A type trait which is true if we want to combine values for hashing by +/// reading the underlying data. It is false if values of this type must +/// first be passed to hash_value, and the resulting hash_codes combined. +// +// FIXME: We want to replace is_integral_or_enum and is_pointer here with +// a predicate which asserts that comparing the underlying storage of two +// values of the type for equality is equivalent to comparing the two values +// for equality. For all the platforms we care about, this holds for integers +// and pointers, but there are platforms where it doesn't and we would like to +// support user-defined types which happen to satisfy this property. +template struct is_hashable_data + : std::integral_constant::value || + std::is_pointer::value) && + 64 % sizeof(T) == 0)> {}; + +// Special case std::pair to detect when both types are viable and when there +// is no alignment-derived padding in the pair. This is a bit of a lie because +// std::pair isn't truly POD, but it's close enough in all reasonable +// implementations for our use case of hashing the underlying data. +template struct is_hashable_data > + : std::integral_constant::value && + is_hashable_data::value && + (sizeof(T) + sizeof(U)) == + sizeof(std::pair))> {}; + +/// Helper to get the hashable data representation for a type. +/// This variant is enabled when the type itself can be used. +template +std::enable_if_t::value, T> +get_hashable_data(const T &value) { + return value; +} +/// Helper to get the hashable data representation for a type. +/// This variant is enabled when we must first call hash_value and use the +/// result as our data. +template +std::enable_if_t::value, size_t> +get_hashable_data(const T &value) { + using ::llvm::hash_value; + return hash_value(value); +} + +/// Helper to store data from a value into a buffer and advance the +/// pointer into that buffer. +/// +/// This routine first checks whether there is enough space in the provided +/// buffer, and if not immediately returns false. If there is space, it +/// copies the underlying bytes of value into the buffer, advances the +/// buffer_ptr past the copied bytes, and returns true. +template +bool store_and_advance(char *&buffer_ptr, char *buffer_end, const T& value, + size_t offset = 0) { + size_t store_size = sizeof(value) - offset; + if (buffer_ptr + store_size > buffer_end) + return false; + const char *value_data = reinterpret_cast(&value); + memcpy(buffer_ptr, value_data + offset, store_size); + buffer_ptr += store_size; + return true; +} + +/// Implement the combining of integral values into a hash_code. +/// +/// This overload is selected when the value type of the iterator is +/// integral. Rather than computing a hash_code for each object and then +/// combining them, this (as an optimization) directly combines the integers. +template +hash_code hash_combine_range_impl(InputIteratorT first, InputIteratorT last) { + const uint64_t seed = get_execution_seed(); + char buffer[64], *buffer_ptr = buffer; + char *const buffer_end = std::end(buffer); + while (first != last && store_and_advance(buffer_ptr, buffer_end, + get_hashable_data(*first))) + ++first; + if (first == last) + return hash_short(buffer, buffer_ptr - buffer, seed); + assert(buffer_ptr == buffer_end); + + hash_state state = state.create(buffer, seed); + size_t length = 64; + while (first != last) { + // Fill up the buffer. We don't clear it, which re-mixes the last round + // when only a partial 64-byte chunk is left. + buffer_ptr = buffer; + while (first != last && store_and_advance(buffer_ptr, buffer_end, + get_hashable_data(*first))) + ++first; + + // Rotate the buffer if we did a partial fill in order to simulate doing + // a mix of the last 64-bytes. That is how the algorithm works when we + // have a contiguous byte sequence, and we want to emulate that here. + std::rotate(buffer, buffer_ptr, buffer_end); + + // Mix this chunk into the current state. + state.mix(buffer); + length += buffer_ptr - buffer; + }; + + return state.finalize(length); +} + +/// Implement the combining of integral values into a hash_code. +/// +/// This overload is selected when the value type of the iterator is integral +/// and when the input iterator is actually a pointer. Rather than computing +/// a hash_code for each object and then combining them, this (as an +/// optimization) directly combines the integers. Also, because the integers +/// are stored in contiguous memory, this routine avoids copying each value +/// and directly reads from the underlying memory. +template +std::enable_if_t::value, hash_code> +hash_combine_range_impl(ValueT *first, ValueT *last) { + const uint64_t seed = get_execution_seed(); + const char *s_begin = reinterpret_cast(first); + const char *s_end = reinterpret_cast(last); + const size_t length = std::distance(s_begin, s_end); + if (length <= 64) + return hash_short(s_begin, length, seed); + + const char *s_aligned_end = s_begin + (length & ~63); + hash_state state = state.create(s_begin, seed); + s_begin += 64; + while (s_begin != s_aligned_end) { + state.mix(s_begin); + s_begin += 64; + } + if (length & 63) + state.mix(s_end - 64); + + return state.finalize(length); +} + +} // namespace detail +} // namespace hashing + + +/// Compute a hash_code for a sequence of values. +/// +/// This hashes a sequence of values. It produces the same hash_code as +/// 'hash_combine(a, b, c, ...)', but can run over arbitrary sized sequences +/// and is significantly faster given pointers and types which can be hashed as +/// a sequence of bytes. +template +hash_code hash_combine_range(InputIteratorT first, InputIteratorT last) { + return ::llvm::hashing::detail::hash_combine_range_impl(first, last); +} + + +// Implementation details for hash_combine. +namespace hashing { +namespace detail { + +/// Helper class to manage the recursive combining of hash_combine +/// arguments. +/// +/// This class exists to manage the state and various calls involved in the +/// recursive combining of arguments used in hash_combine. It is particularly +/// useful at minimizing the code in the recursive calls to ease the pain +/// caused by a lack of variadic functions. +struct hash_combine_recursive_helper { + char buffer[64] = {}; + hash_state state; + const uint64_t seed; + +public: + /// Construct a recursive hash combining helper. + /// + /// This sets up the state for a recursive hash combine, including getting + /// the seed and buffer setup. + hash_combine_recursive_helper() + : seed(get_execution_seed()) {} + + /// Combine one chunk of data into the current in-flight hash. + /// + /// This merges one chunk of data into the hash. First it tries to buffer + /// the data. If the buffer is full, it hashes the buffer into its + /// hash_state, empties it, and then merges the new chunk in. This also + /// handles cases where the data straddles the end of the buffer. + template + char *combine_data(size_t &length, char *buffer_ptr, char *buffer_end, T data) { + if (!store_and_advance(buffer_ptr, buffer_end, data)) { + // Check for skew which prevents the buffer from being packed, and do + // a partial store into the buffer to fill it. This is only a concern + // with the variadic combine because that formation can have varying + // argument types. + size_t partial_store_size = buffer_end - buffer_ptr; + memcpy(buffer_ptr, &data, partial_store_size); + + // If the store fails, our buffer is full and ready to hash. We have to + // either initialize the hash state (on the first full buffer) or mix + // this buffer into the existing hash state. Length tracks the *hashed* + // length, not the buffered length. + if (length == 0) { + state = state.create(buffer, seed); + length = 64; + } else { + // Mix this chunk into the current state and bump length up by 64. + state.mix(buffer); + length += 64; + } + // Reset the buffer_ptr to the head of the buffer for the next chunk of + // data. + buffer_ptr = buffer; + + // Try again to store into the buffer -- this cannot fail as we only + // store types smaller than the buffer. + if (!store_and_advance(buffer_ptr, buffer_end, data, + partial_store_size)) + llvm_unreachable("buffer smaller than stored type"); + } + return buffer_ptr; + } + + /// Recursive, variadic combining method. + /// + /// This function recurses through each argument, combining that argument + /// into a single hash. + template + hash_code combine(size_t length, char *buffer_ptr, char *buffer_end, + const T &arg, const Ts &...args) { + buffer_ptr = combine_data(length, buffer_ptr, buffer_end, get_hashable_data(arg)); + + // Recurse to the next argument. + return combine(length, buffer_ptr, buffer_end, args...); + } + + /// Base case for recursive, variadic combining. + /// + /// The base case when combining arguments recursively is reached when all + /// arguments have been handled. It flushes the remaining buffer and + /// constructs a hash_code. + hash_code combine(size_t length, char *buffer_ptr, char *buffer_end) { + // Check whether the entire set of values fit in the buffer. If so, we'll + // use the optimized short hashing routine and skip state entirely. + if (length == 0) + return hash_short(buffer, buffer_ptr - buffer, seed); + + // Mix the final buffer, rotating it if we did a partial fill in order to + // simulate doing a mix of the last 64-bytes. That is how the algorithm + // works when we have a contiguous byte sequence, and we want to emulate + // that here. + std::rotate(buffer, buffer_ptr, buffer_end); + + // Mix this chunk into the current state. + state.mix(buffer); + length += buffer_ptr - buffer; + + return state.finalize(length); + } +}; + +} // namespace detail +} // namespace hashing + +/// Combine values into a single hash_code. +/// +/// This routine accepts a varying number of arguments of any type. It will +/// attempt to combine them into a single hash_code. For user-defined types it +/// attempts to call a \see hash_value overload (via ADL) for the type. For +/// integer and pointer types it directly combines their data into the +/// resulting hash_code. +/// +/// The result is suitable for returning from a user's hash_value +/// *implementation* for their user-defined type. Consumers of a type should +/// *not* call this routine, they should instead call 'hash_value'. +template hash_code hash_combine(const Ts &...args) { + // Recursively hash each argument using a helper class. + ::llvm::hashing::detail::hash_combine_recursive_helper helper; + return helper.combine(0, helper.buffer, helper.buffer + 64, args...); +} + +// Implementation details for implementations of hash_value overloads provided +// here. +namespace hashing { +namespace detail { + +/// Helper to hash the value of a single integer. +/// +/// Overloads for smaller integer types are not provided to ensure consistent +/// behavior in the presence of integral promotions. Essentially, +/// "hash_value('4')" and "hash_value('0' + 4)" should be the same. +inline hash_code hash_integer_value(uint64_t value) { + // Similar to hash_4to8_bytes but using a seed instead of length. + const uint64_t seed = get_execution_seed(); + const char *s = reinterpret_cast(&value); + const uint64_t a = fetch32(s); + return hash_16_bytes(seed + (a << 3), fetch32(s + 4)); +} + +} // namespace detail +} // namespace hashing + +// Declared and documented above, but defined here so that any of the hashing +// infrastructure is available. +template +std::enable_if_t::value, hash_code> hash_value(T value) { + return ::llvm::hashing::detail::hash_integer_value( + static_cast(value)); +} + +// Declared and documented above, but defined here so that any of the hashing +// infrastructure is available. +template hash_code hash_value(const T *ptr) { + return ::llvm::hashing::detail::hash_integer_value( + reinterpret_cast(ptr)); +} + +// Declared and documented above, but defined here so that any of the hashing +// infrastructure is available. +template +hash_code hash_value(const std::pair &arg) { + return hash_combine(arg.first, arg.second); +} + +template hash_code hash_value(const std::tuple &arg) { + return std::apply([](const auto &...xs) { return hash_combine(xs...); }, arg); +} + +// Declared and documented above, but defined here so that any of the hashing +// infrastructure is available. +template +hash_code hash_value(const std::basic_string &arg) { + return hash_combine_range(arg.begin(), arg.end()); +} + +template hash_code hash_value(const std::optional &arg) { + return arg ? hash_combine(true, *arg) : hash_value(false); +} + +template <> struct DenseMapInfo { + static inline hash_code getEmptyKey() { return hash_code(-1); } + static inline hash_code getTombstoneKey() { return hash_code(-2); } + static unsigned getHashValue(hash_code val) { + return static_cast(size_t(val)); + } + static bool isEqual(hash_code LHS, hash_code RHS) { return LHS == RHS; } +}; + +} // namespace llvm + +/// Implement std::hash so that hash_code can be used in STL containers. +namespace std { + +template<> +struct hash { + size_t operator()(llvm::hash_code const& Val) const { + return Val; + } +}; + +} // namespace std; + +#endif diff --git a/third_party/llvm/include/llvm/ADT/STLExtras.h b/third_party/llvm/include/llvm/ADT/STLExtras.h new file mode 100644 index 0000000..e340685 --- /dev/null +++ b/third_party/llvm/include/llvm/ADT/STLExtras.h @@ -0,0 +1,2568 @@ +//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// This file contains some templates that are useful if you are working with +/// the STL at all. +/// +/// No library is required when using these functions. +/// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_ADT_STLEXTRAS_H +#define LLVM_ADT_STLEXTRAS_H + +#include "llvm/ADT/ADL.h" +#include "llvm/ADT/Hashing.h" +#include "llvm/ADT/STLForwardCompat.h" +#include "llvm/ADT/STLFunctionalExtras.h" +#include "llvm/ADT/iterator.h" +#include "llvm/ADT/iterator_range.h" +#include "llvm/Config/abi-breaking.h" +#include "llvm/Support/ErrorHandling.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef EXPENSIVE_CHECKS +#include // for std::mt19937 +#endif + +namespace llvm { + +//===----------------------------------------------------------------------===// +// Extra additions to +//===----------------------------------------------------------------------===// + +template struct make_const_ptr { + using type = std::add_pointer_t>; +}; + +template struct make_const_ref { + using type = std::add_lvalue_reference_t>; +}; + +namespace detail { +template class Op, class... Args> struct detector { + using value_t = std::false_type; +}; +template