| 1 | //===- Hash.cpp - Hash functions ---------------------------------------===// |
|---|---|
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file implements hash functions. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #include "llvm/Support/Hash.h" |
| 14 | #include "llvm/Support/xxhash.h" |
| 15 | |
| 16 | using namespace llvm; |
| 17 | |
| 18 | KCFIHashAlgorithm llvm::parseKCFIHashAlgorithm(StringRef Name) { |
| 19 | if (Name == "FNV-1a") |
| 20 | return KCFIHashAlgorithm::FNV1a; |
| 21 | // Default to xxHash64 for backward compatibility |
| 22 | return KCFIHashAlgorithm::xxHash64; |
| 23 | } |
| 24 | |
| 25 | StringRef llvm::stringifyKCFIHashAlgorithm(KCFIHashAlgorithm Algorithm) { |
| 26 | switch (Algorithm) { |
| 27 | case KCFIHashAlgorithm::xxHash64: |
| 28 | return "xxHash64"; |
| 29 | case KCFIHashAlgorithm::FNV1a: |
| 30 | return "FNV-1a"; |
| 31 | } |
| 32 | llvm_unreachable("Unknown KCFI hash algorithm"); |
| 33 | } |
| 34 | |
| 35 | uint32_t llvm::getKCFITypeID(StringRef MangledTypeName, |
| 36 | KCFIHashAlgorithm Algorithm) { |
| 37 | switch (Algorithm) { |
| 38 | case KCFIHashAlgorithm::xxHash64: |
| 39 | // Use lower 32 bits of xxHash64 |
| 40 | return static_cast<uint32_t>(xxHash64(Data: MangledTypeName)); |
| 41 | case KCFIHashAlgorithm::FNV1a: |
| 42 | // FNV-1a hash (32-bit) |
| 43 | uint32_t Hash = 2166136261u; // FNV offset basis |
| 44 | for (unsigned char C : MangledTypeName) { |
| 45 | Hash ^= C; |
| 46 | Hash *= 16777619u; // FNV prime |
| 47 | } |
| 48 | return Hash; |
| 49 | } |
| 50 | llvm_unreachable("Unknown KCFI hash algorithm"); |
| 51 | } |
| 52 |