From ac070493aa79620d1ef44b89d0df379a8422af6e Mon Sep 17 00:00:00 2001 From: Zalathar Date: Mon, 26 Oct 2026 12:28:42 +1100 Subject: [PATCH] Avoid stdlib's `impl Hash for Discriminant` for stable hashing --- Cargo.lock | 1 + .../rustc_data_structures/src/stable_hash.rs | 36 +++++++++++----- compiler/rustc_macros/src/stable_hash.rs | 43 +++++++++++++++++-- compiler/rustc_symbol_mangling/Cargo.toml | 1 + compiler/rustc_symbol_mangling/src/legacy.rs | 20 ++++++++- compiler/rustc_type_ir/src/region_kind.rs | 26 ++++++++--- compiler/rustc_type_ir/src/ty_kind.rs | 25 +++++++++-- tests/codegen-llvm/remap_path_prefix/main.rs | 2 +- tests/debuginfo/function-names.rs | 2 +- 9 files changed, 130 insertions(+), 26 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 41c82c989becc..2608e1b51ebd3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4905,6 +4905,7 @@ dependencies = [ "rustc_data_structures", "rustc_hashes", "rustc_hir", + "rustc_macros", "rustc_middle", "rustc_session", "rustc_span", diff --git a/compiler/rustc_data_structures/src/stable_hash.rs b/compiler/rustc_data_structures/src/stable_hash.rs index 91578b9fd4308..57f5901656827 100644 --- a/compiler/rustc_data_structures/src/stable_hash.rs +++ b/compiler/rustc_data_structures/src/stable_hash.rs @@ -1,6 +1,5 @@ use std::hash::{BuildHasher, Hash, Hasher}; use std::marker::PhantomData; -use std::mem; use std::num::NonZero; use rustc_index::bit_set::{self, DenseBitSet}; @@ -533,10 +532,20 @@ where { #[inline] fn stable_hash(&self, hcx: &mut Hcx, hasher: &mut StableHasher) { - mem::discriminant(self).stable_hash(hcx, hasher); + #[derive(StableHash)] + enum Tag { + Ok, + Err, + } match *self { - Ok(ref x) => x.stable_hash(hcx, hasher), - Err(ref x) => x.stable_hash(hcx, hasher), + Ok(ref x) => { + Tag::Ok.stable_hash(hcx, hasher); + x.stable_hash(hcx, hasher); + } + Err(ref x) => { + Tag::Err.stable_hash(hcx, hasher); + x.stable_hash(hcx, hasher); + } } } } @@ -551,12 +560,19 @@ where } } -impl StableHash for ::std::mem::Discriminant { - #[inline] - fn stable_hash(&self, _: &mut Hcx, hasher: &mut StableHasher) { - ::std::hash::Hash::hash(self, hasher); - } -} +/// There is no way to stable-hash a `Discriminant` without leaking unstable +/// details of how the host compiler chooses and hashes discriminants. +/// +/// That would be bad, because stable hashes must be consistent between +/// the stage1 compiler (built with the bootstrap compiler/stdlib) +/// and the stage2 compiler (built with the in-tree compiler/stdlib). +/// +/// See for more context. +/// +/// If you need to manually stable-hash a discriminant, instead derive `StableHash` +/// on a dedicated "tag" enum, and then hash the appropriate tag for each variant. +/// For an example, see the impl of `StableHash for Result`. +impl !StableHash for std::mem::Discriminant {} impl StableHash for ::std::range::RangeInclusive where diff --git a/compiler/rustc_macros/src/stable_hash.rs b/compiler/rustc_macros/src/stable_hash.rs index 07c5a271d1087..ba570dd008e77 100644 --- a/compiler/rustc_macros/src/stable_hash.rs +++ b/compiler/rustc_macros/src/stable_hash.rs @@ -1,5 +1,5 @@ use proc_macro2::Ident; -use quote::quote; +use quote::{ToTokens, quote}; struct Attributes { ignore: bool, @@ -96,9 +96,44 @@ fn stable_hash_derive_with_mode( fn stable_hash_discriminant(s: &mut synstructure::Structure<'_>) -> proc_macro2::TokenStream { match s.ast().data { - syn::Data::Enum(_) => quote! { - ::std::mem::discriminant(self).stable_hash(__hcx, __hasher); - }, + syn::Data::Enum(_) => { + // For stable hashing, use a fake discriminant based on the syntactic + // ordering of enum variants, not the actual runtime discriminant. + // This helps to keep stable hashes consistent between stage1 and stage2. + let n_variants = s.variants().len(); + + // If this enum has no variants (and is therefore uninhabited), + // matching on `self` will cause the compiler to realise that all + // subsequent code is unreachable, triggering unhelpful warnings. + if n_variants == 0 { + return quote! {}; + } + + let mut match_arms = proc_macro2::TokenStream::new(); + + // Use a u8 discriminant, as it's measurably faster than usize. + // If support for larger enums is needed, take care to still use u8 + // when possible, to avoid regressions. + assert!( + n_variants <= 256, + "deriving StableHash for an enum with more than 256 variants is unsupported \ + (was: {n_variants})" + ); + for (discriminant, variant) in (0u8..).zip(s.variants()) { + let pat = variant.pat(); + + quote! { + #pat => #discriminant.stable_hash(__hcx, __hasher), + } + .to_tokens(&mut match_arms); + } + + quote! { + match *self { + #match_arms + } + } + } syn::Data::Struct(_) => quote! {}, syn::Data::Union(_) => panic!("cannot derive on union"), } diff --git a/compiler/rustc_symbol_mangling/Cargo.toml b/compiler/rustc_symbol_mangling/Cargo.toml index 1e078015257d7..ffef3e42c1008 100644 --- a/compiler/rustc_symbol_mangling/Cargo.toml +++ b/compiler/rustc_symbol_mangling/Cargo.toml @@ -12,6 +12,7 @@ rustc_attr_ir = { path = "../rustc_attr_ir" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_hashes = { path = "../rustc_hashes" } rustc_hir = { path = "../rustc_hir" } +rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index b95082d9dbe71..f9f3013ddd6c4 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -1,10 +1,11 @@ use std::fmt::{self, Write}; -use std::mem::{self, discriminant}; +use std::mem; use rustc_data_structures::stable_hash::{StableHash, StableHasher}; use rustc_hashes::Hash64; use rustc_hir::def_id::{CrateNum, DefId}; use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; +use rustc_macros::StableHash; use rustc_middle::ty::print::{PrettyPrinter, Print, PrintError, Printer}; use rustc_middle::ty::{ self, GenericArg, GenericArgKind, Instance, ReifyReason, Ty, TyCtxt, TypeVisitableExt, @@ -170,7 +171,22 @@ fn get_symbol_hash<'tcx>( // We want to avoid accidental collision between different types of instances. // Especially, `VTableShim`s and `ReifyShim`s may overlap with their original // instances without this. - discriminant(&instance.def).stable_hash(hcx, &mut hasher); + #[derive(StableHash)] + enum Tag { + Item, + Intrinsic, + LlvmIntrinsic, + Virtual, + Shim, + } + match instance.def { + ty::InstanceKind::Item(_) => Tag::Item, + ty::InstanceKind::Intrinsic(_) => Tag::Intrinsic, + ty::InstanceKind::LlvmIntrinsic(_) => Tag::LlvmIntrinsic, + ty::InstanceKind::Virtual(_, _) => Tag::Virtual, + ty::InstanceKind::Shim(_) => Tag::Shim, + } + .stable_hash(hcx, &mut hasher); }); // 64 bits should be enough to avoid collisions. diff --git a/compiler/rustc_type_ir/src/region_kind.rs b/compiler/rustc_type_ir/src/region_kind.rs index 5c14a5072910a..4b5712f09d234 100644 --- a/compiler/rustc_type_ir/src/region_kind.rs +++ b/compiler/rustc_type_ir/src/region_kind.rs @@ -4,7 +4,7 @@ use derive_where::derive_where; #[cfg(feature = "nightly")] use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher}; #[cfg(feature = "nightly")] -use rustc_macros::{Decodable_NoContext, Encodable_NoContext}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, StableHash}; use rustc_type_ir_macros::GenericTypeVisitable; use self::RegionKind::*; @@ -226,22 +226,38 @@ where { #[inline] fn stable_hash(&self, hcx: &mut Hcx, hasher: &mut StableHasher) { - std::mem::discriminant(self).stable_hash(hcx, hasher); + #[derive(StableHash)] + enum Tag { + ReErased, + ReStatic, + ReError, + ReBound, + ReEarlyParam, + ReLateParam, + RePlaceholder, + } + match self { - ReErased | ReStatic | ReError(_) => { - // No variant fields to hash for these ... - } + // No variant fields to hash for these ... + ReErased => Tag::ReErased.stable_hash(hcx, hasher), + ReStatic => Tag::ReStatic.stable_hash(hcx, hasher), + ReError(_) => Tag::ReError.stable_hash(hcx, hasher), + ReBound(d, r) => { + Tag::ReBound.stable_hash(hcx, hasher); d.stable_hash(hcx, hasher); r.stable_hash(hcx, hasher); } ReEarlyParam(r) => { + Tag::ReEarlyParam.stable_hash(hcx, hasher); r.stable_hash(hcx, hasher); } ReLateParam(r) => { + Tag::ReLateParam.stable_hash(hcx, hasher); r.stable_hash(hcx, hasher); } RePlaceholder(r) => { + Tag::RePlaceholder.stable_hash(hcx, hasher); r.stable_hash(hcx, hasher); } ReVar(_) => { diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index e996f6684515a..77d8ea006972a 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -8,7 +8,7 @@ use rustc_ast_ir::Mutability; #[cfg(feature = "nightly")] use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher}; #[cfg(feature = "nightly")] -use rustc_macros::{Decodable_NoContext, Encodable_NoContext, StableHash_NoContext}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, StableHash, StableHash_NoContext}; use rustc_type_ir::data_structures::{NoError, UnifyKey, UnifyValue}; use rustc_type_ir_macros::{ GenericTypeVisitable, Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic, @@ -857,12 +857,31 @@ impl UnifyKey for FloatVid { impl StableHash for InferTy { fn stable_hash(&self, hcx: &mut Hcx, hasher: &mut StableHasher) { use InferTy::*; - std::mem::discriminant(self).stable_hash(hcx, hasher); + + #[derive(StableHash)] + enum Tag { + FreshTy, + FreshIntTy, + FreshFloatTy, + } + match self { TyVar(_) | IntVar(_) | FloatVar(_) => { panic!("type variables should not be hashed: {self:?}") } - FreshTy(v) | FreshIntTy(v) | FreshFloatTy(v) => v.stable_hash(hcx, hasher), + + FreshTy(v) => { + Tag::FreshTy.stable_hash(hcx, hasher); + v.stable_hash(hcx, hasher); + } + FreshIntTy(v) => { + Tag::FreshIntTy.stable_hash(hcx, hasher); + v.stable_hash(hcx, hasher); + } + FreshFloatTy(v) => { + Tag::FreshFloatTy.stable_hash(hcx, hasher); + v.stable_hash(hcx, hasher); + } } } } diff --git a/tests/codegen-llvm/remap_path_prefix/main.rs b/tests/codegen-llvm/remap_path_prefix/main.rs index 7d17b3b67cfa2..27ce99e0b590e 100644 --- a/tests/codegen-llvm/remap_path_prefix/main.rs +++ b/tests/codegen-llvm/remap_path_prefix/main.rs @@ -12,7 +12,7 @@ mod aux_mod; include!("aux_mod.rs"); // Here we check that the expansion of the file!() macro is mapped. -// CHECK: @alloc_5761061597a97f66e13ef2ff92712c4b = private unnamed_addr constant [34 x i8] c"/the/src/remap_path_prefix/main.rs" +// CHECK: @alloc_{{([0-9a-f]{32})}} = private unnamed_addr constant [34 x i8] c"/the/src/remap_path_prefix/main.rs" pub static FILE_PATH: &'static str = file!(); fn main() { diff --git a/tests/debuginfo/function-names.rs b/tests/debuginfo/function-names.rs index 38921743130f0..ff30ea6a7040d 100644 --- a/tests/debuginfo/function-names.rs +++ b/tests/debuginfo/function-names.rs @@ -39,7 +39,7 @@ // Const generic parameter //@ gdb-command:info functions -q function_names::const_generic_fn.* //@ gdb-check:[...]static fn function_names::const_generic_fn_bool(); -//@ gdb-check:[...]static fn function_names::const_generic_fn_non_int<{CONST#68cf9e429c783d36}>(); +//@ gdb-check:[...]static fn function_names::const_generic_fn_non_int<{CONST#[...]}>(); //@ gdb-check:[...]static fn function_names::const_generic_fn_signed_int<-7>(); //@ gdb-check:[...]static fn function_names::const_generic_fn_unsigned_int<14>();