[llvm] [ADT] Don't use getEmptyKey() when hashing std::optional (PR #202002)

Fangrui Song via llvm-commits llvm-commits at lists.llvm.org
Fri Jun 5 21:23:22 PDT 2026


https://github.com/MaskRay created https://github.com/llvm/llvm-project/pull/202002

DenseMapInfo<std::optional<T>>::getHashValue() calls T's getEmptyKey()
for the nullopt case. This blocks removing the now-unused getEmptyKey()
from DenseMapInfo specializations: a leaf type that drops getEmptyKey()
fails to compile wherever std::optional<T> is used as a DenseMap key
(e.g. DenseMapInfo<mlir::spirv::StorageClass>).

Compute the hash directly instead. Prerequisite for the getEmptyKey()
removal series; #201281 made getEmptyKey() unused by DenseMap.


>From f5c6ade0789f67e3f0b6426689649a3b00c77f1f Mon Sep 17 00:00:00 2001
From: Fangrui Song <i at maskray.me>
Date: Fri, 5 Jun 2026 21:22:37 -0700
Subject: [PATCH] [ADT] Don't use getEmptyKey() when hashing std::optional

DenseMapInfo<std::optional<T>>::getHashValue() calls T's getEmptyKey()
for the nullopt case. This blocks removing the now-unused getEmptyKey()
from DenseMapInfo specializations: a leaf type that drops getEmptyKey()
fails to compile wherever std::optional<T> is used as a DenseMap key
(e.g. DenseMapInfo<mlir::spirv::StorageClass>).

Compute the hash directly instead. Prerequisite for the getEmptyKey()
removal series; #201281 made getEmptyKey() unused by DenseMap.
---
 llvm/include/llvm/ADT/DenseMapInfo.h | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/llvm/include/llvm/ADT/DenseMapInfo.h b/llvm/include/llvm/ADT/DenseMapInfo.h
index e8e21e4a15e66..f5c60a70ea805 100644
--- a/llvm/include/llvm/ADT/DenseMapInfo.h
+++ b/llvm/include/llvm/ADT/DenseMapInfo.h
@@ -214,9 +214,9 @@ template <typename T> struct DenseMapInfo<std::optional<T>> {
   static constexpr Optional getEmptyKey() { return {Info::getEmptyKey()}; }
 
   static unsigned getHashValue(const Optional &OptionalVal) {
-    return detail::combineHashValue(
-        OptionalVal.has_value(),
-        Info::getHashValue(OptionalVal.value_or(Info::getEmptyKey())));
+    if (OptionalVal)
+      return detail::combineHashValue(1, Info::getHashValue(*OptionalVal));
+    return detail::combineHashValue(0, 0);
   }
 
   static bool isEqual(const Optional &LHS, const Optional &RHS) {



More information about the llvm-commits mailing list