Skip to content

Commit 22d489b

Browse files
Let a portion of DefPathHash uniquely identify the DefPath's crate.
This allows to directly map from a DefPathHash to the crate it originates from, without constructing side tables to do that mapping. It also allows to reliably and cheaply check for DefPathHash collisions.
1 parent a3ed564 commit 22d489b

File tree

12 files changed

+181
-27
lines changed

12 files changed

+181
-27
lines changed

compiler/rustc_ast/src/lib.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ pub mod util {
4141

4242
pub mod ast;
4343
pub mod attr;
44-
pub mod crate_disambiguator;
4544
pub mod entry;
4645
pub mod expand;
4746
pub mod mut_visit;

compiler/rustc_data_structures/src/fingerprint.rs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,30 @@ use std::hash::{Hash, Hasher};
77
use std::mem::{self, MaybeUninit};
88

99
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Copy)]
10+
#[repr(C)]
1011
pub struct Fingerprint(u64, u64);
1112

1213
impl Fingerprint {
1314
pub const ZERO: Fingerprint = Fingerprint(0, 0);
1415

16+
#[inline]
17+
pub fn new(_0: u64, _1: u64) -> Fingerprint {
18+
Fingerprint(_0, _1)
19+
}
20+
1521
#[inline]
1622
pub fn from_smaller_hash(hash: u64) -> Fingerprint {
1723
Fingerprint(hash, hash)
1824
}
1925

2026
#[inline]
2127
pub fn to_smaller_hash(&self) -> u64 {
22-
self.0
28+
// Even though both halves of the fingerprint are expected to be good
29+
// quality hash values, let's still combine the two values because the
30+
// Fingerprints in DefPathHash have the StableCrateId portion which is
31+
// the same for all DefPathHashes from the same crate. Combining the
32+
// two halfs makes sure we get a good quality hash in such cases too.
33+
self.0.wrapping_mul(3).wrapping_add(self.1)
2334
}
2435

2536
#[inline]
@@ -93,7 +104,7 @@ impl FingerprintHasher for crate::unhash::Unhasher {
93104
#[inline]
94105
fn write_fingerprint(&mut self, fingerprint: &Fingerprint) {
95106
// `Unhasher` only wants a single `u64`
96-
self.write_u64(fingerprint.0);
107+
self.write_u64(fingerprint.0.wrapping_add(fingerprint.1));
97108
}
98109
}
99110

compiler/rustc_hir/src/definitions.rs

Lines changed: 41 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,16 @@
55
//! expressions) that are mostly just leftovers.
66
77
pub use crate::def_id::DefPathHash;
8-
use crate::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
8+
use crate::def_id::{
9+
CrateNum, DefId, DefIndex, LocalDefId, StableCrateId, CRATE_DEF_INDEX, LOCAL_CRATE,
10+
};
911
use crate::hir;
1012

11-
use rustc_ast::crate_disambiguator::CrateDisambiguator;
1213
use rustc_data_structures::fx::FxHashMap;
1314
use rustc_data_structures::stable_hasher::StableHasher;
15+
use rustc_data_structures::unhash::UnhashMap;
1416
use rustc_index::vec::IndexVec;
17+
use rustc_span::crate_disambiguator::CrateDisambiguator;
1518
use rustc_span::hygiene::ExpnId;
1619
use rustc_span::symbol::{kw, sym, Symbol};
1720

@@ -27,6 +30,7 @@ use tracing::debug;
2730
pub struct DefPathTable {
2831
index_to_key: IndexVec<DefIndex, DefKey>,
2932
def_path_hashes: IndexVec<DefIndex, DefPathHash>,
33+
def_path_hash_to_index: UnhashMap<DefPathHash, DefIndex>,
3034
}
3135

3236
impl DefPathTable {
@@ -39,6 +43,25 @@ impl DefPathTable {
3943
};
4044
self.def_path_hashes.push(def_path_hash);
4145
debug_assert!(self.def_path_hashes.len() == self.index_to_key.len());
46+
47+
// Check for hash collisions of DefPathHashes. These should be
48+
// exceedingly rare.
49+
if let Some(existing) = self.def_path_hash_to_index.insert(def_path_hash, index) {
50+
let def_path1 = DefPath::make(LOCAL_CRATE, existing, |idx| self.def_key(idx));
51+
let def_path2 = DefPath::make(LOCAL_CRATE, index, |idx| self.def_key(idx));
52+
53+
// Continuing with colliding DefPathHashes can lead to correctness
54+
// issues. We must abort compilation.
55+
panic!("Found DefPathHash collsion between {:?} and {:?}", def_path1, def_path2);
56+
}
57+
58+
// Assert that all DefPathHashes correctly contain the local crate's
59+
// StableCrateId
60+
#[cfg(debug_assertions)]
61+
if let Some(root) = self.def_path_hashes.get(CRATE_DEF_INDEX) {
62+
assert!(def_path_hash.stable_crate_id() == root.stable_crate_id());
63+
}
64+
4265
index
4366
}
4467

@@ -108,13 +131,10 @@ pub struct DefKey {
108131
}
109132

110133
impl DefKey {
111-
fn compute_stable_hash(&self, parent_hash: DefPathHash) -> DefPathHash {
134+
fn compute_stable_hash(&self, parent: DefPathHash) -> DefPathHash {
112135
let mut hasher = StableHasher::new();
113136

114-
// We hash a `0u8` here to disambiguate between regular `DefPath` hashes,
115-
// and the special "root_parent" below.
116-
0u8.hash(&mut hasher);
117-
parent_hash.hash(&mut hasher);
137+
parent.hash(&mut hasher);
118138

119139
let DisambiguatedDefPathData { ref data, disambiguator } = self.disambiguated_data;
120140

@@ -127,19 +147,13 @@ impl DefKey {
127147

128148
disambiguator.hash(&mut hasher);
129149

130-
DefPathHash(hasher.finish())
131-
}
150+
let local_hash: u64 = hasher.finish();
132151

133-
fn root_parent_stable_hash(
134-
crate_name: &str,
135-
crate_disambiguator: CrateDisambiguator,
136-
) -> DefPathHash {
137-
let mut hasher = StableHasher::new();
138-
// Disambiguate this from a regular `DefPath` hash; see `compute_stable_hash()` above.
139-
1u8.hash(&mut hasher);
140-
crate_name.hash(&mut hasher);
141-
crate_disambiguator.hash(&mut hasher);
142-
DefPathHash(hasher.finish())
152+
// Construct the new DefPathHash, making sure that the `crate_id`
153+
// portion of the hash is properly copied from the parent. This way the
154+
// `crate_id` part will be recursively propagated from the root to all
155+
// DefPathHashes in this DefPathTable.
156+
DefPathHash::new(parent.stable_crate_id(), local_hash)
143157
}
144158
}
145159

@@ -295,6 +309,12 @@ impl Definitions {
295309
self.table.def_path_hash(id.local_def_index)
296310
}
297311

312+
#[inline]
313+
pub fn def_path_hash_to_def_id(&self, def_path_hash: DefPathHash) -> LocalDefId {
314+
let local_def_index = self.table.def_path_hash_to_index[&def_path_hash];
315+
LocalDefId { local_def_index }
316+
}
317+
298318
/// Returns the path from the crate root to `index`. The root
299319
/// nodes are not included in the path (i.e., this will be an
300320
/// empty vector for the crate root). For an inlined item, this
@@ -332,7 +352,8 @@ impl Definitions {
332352
},
333353
};
334354

335-
let parent_hash = DefKey::root_parent_stable_hash(crate_name, crate_disambiguator);
355+
let stable_crate_id = StableCrateId::new(crate_name, crate_disambiguator);
356+
let parent_hash = DefPathHash::new(stable_crate_id, 0);
336357
let def_path_hash = key.compute_stable_hash(parent_hash);
337358

338359
// Create the root definition.

compiler/rustc_metadata/src/creader.rs

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@ use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob
66

77
use rustc_ast::expand::allocator::AllocatorKind;
88
use rustc_ast::{self as ast, *};
9-
use rustc_data_structures::fx::FxHashSet;
9+
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
1010
use rustc_data_structures::svh::Svh;
1111
use rustc_data_structures::sync::Lrc;
1212
use rustc_expand::base::SyntaxExtension;
13-
use rustc_hir::def_id::{CrateNum, LocalDefId, LOCAL_CRATE};
13+
use rustc_hir::def_id::{CrateNum, LocalDefId, StableCrateId, LOCAL_CRATE};
1414
use rustc_hir::definitions::Definitions;
1515
use rustc_index::vec::IndexVec;
1616
use rustc_middle::middle::cstore::{CrateDepKind, CrateSource, ExternCrate};
@@ -40,6 +40,10 @@ pub struct CStore {
4040
allocator_kind: Option<AllocatorKind>,
4141
/// This crate has a `#[global_allocator]` item.
4242
has_global_allocator: bool,
43+
44+
/// This map is used to verify we get no hash conflicts between
45+
/// `StableCrateId` values.
46+
stable_crate_ids: FxHashMap<StableCrateId, CrateNum>,
4347
}
4448

4549
pub struct CrateLoader<'a> {
@@ -192,6 +196,11 @@ impl<'a> CrateLoader<'a> {
192196
metadata_loader: &'a MetadataLoaderDyn,
193197
local_crate_name: &str,
194198
) -> Self {
199+
let local_crate_stable_id =
200+
StableCrateId::new(local_crate_name, sess.local_crate_disambiguator());
201+
let mut stable_crate_ids = FxHashMap::default();
202+
stable_crate_ids.insert(local_crate_stable_id, LOCAL_CRATE);
203+
195204
CrateLoader {
196205
sess,
197206
metadata_loader,
@@ -205,6 +214,7 @@ impl<'a> CrateLoader<'a> {
205214
injected_panic_runtime: None,
206215
allocator_kind: None,
207216
has_global_allocator: false,
217+
stable_crate_ids,
208218
},
209219
used_extern_options: Default::default(),
210220
}
@@ -311,6 +321,20 @@ impl<'a> CrateLoader<'a> {
311321
res
312322
}
313323

324+
fn verify_no_stable_crate_id_hash_conflicts(
325+
&mut self,
326+
root: &CrateRoot<'_>,
327+
cnum: CrateNum,
328+
) -> Result<(), CrateError> {
329+
if let Some(existing) = self.cstore.stable_crate_ids.insert(root.stable_crate_id(), cnum) {
330+
let crate_name0 = root.name();
331+
let crate_name1 = self.cstore.get_crate_data(existing).name();
332+
return Err(CrateError::StableCrateIdCollision(crate_name0, crate_name1));
333+
}
334+
335+
Ok(())
336+
}
337+
314338
fn register_crate(
315339
&mut self,
316340
host_lib: Option<Library>,
@@ -332,6 +356,8 @@ impl<'a> CrateLoader<'a> {
332356
// Claim this crate number and cache it
333357
let cnum = self.cstore.alloc_new_crate_num();
334358

359+
self.verify_no_stable_crate_id_hash_conflicts(&crate_root, cnum)?;
360+
335361
info!(
336362
"register crate `{}` (cnum = {}. private_dep = {})",
337363
crate_root.name(),

compiler/rustc_metadata/src/locator.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -888,6 +888,7 @@ crate enum CrateError {
888888
MultipleMatchingCrates(Symbol, FxHashMap<Svh, Library>),
889889
SymbolConflictsCurrent(Symbol),
890890
SymbolConflictsOthers(Symbol),
891+
StableCrateIdCollision(Symbol, Symbol),
891892
DlOpen(String),
892893
DlSym(String),
893894
LocatorCombined(CombinedLocatorError),
@@ -970,6 +971,13 @@ impl CrateError {
970971
`-C metadata`. This will result in symbol conflicts between the two.",
971972
root_name,
972973
),
974+
CrateError::StableCrateIdCollision(crate_name0, crate_name1) => {
975+
let msg = format!(
976+
"found crates (`{}` and `{}`) with colliding StableCrateId values.",
977+
crate_name0, crate_name1
978+
);
979+
sess.struct_span_err(span, &msg)
980+
}
973981
CrateError::DlOpen(s) | CrateError::DlSym(s) => sess.struct_span_err(span, &s),
974982
CrateError::LocatorCombined(locator) => {
975983
let crate_name = locator.crate_name;

compiler/rustc_metadata/src/rmeta/decoder.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,10 @@ impl CrateRoot<'_> {
635635
self.hash
636636
}
637637

638+
crate fn stable_crate_id(&self) -> StableCrateId {
639+
self.stable_crate_id
640+
}
641+
638642
crate fn triple(&self) -> &TargetTriple {
639643
&self.triple
640644
}

compiler/rustc_metadata/src/rmeta/encoder.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -651,6 +651,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
651651
triple: tcx.sess.opts.target_triple.clone(),
652652
hash: tcx.crate_hash(LOCAL_CRATE),
653653
disambiguator: tcx.sess.local_crate_disambiguator(),
654+
stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
654655
panic_strategy: tcx.sess.panic_strategy(),
655656
edition: tcx.sess.edition(),
656657
has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),

compiler/rustc_metadata/src/rmeta/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_data_structures::svh::Svh;
77
use rustc_data_structures::sync::MetadataRef;
88
use rustc_hir as hir;
99
use rustc_hir::def::{CtorKind, DefKind};
10-
use rustc_hir::def_id::{DefId, DefIndex, DefPathHash};
10+
use rustc_hir::def_id::{DefId, DefIndex, DefPathHash, StableCrateId};
1111
use rustc_hir::definitions::DefKey;
1212
use rustc_hir::lang_items;
1313
use rustc_index::{bit_set::FiniteBitSet, vec::IndexVec};
@@ -203,6 +203,7 @@ crate struct CrateRoot<'tcx> {
203203
extra_filename: String,
204204
hash: Svh,
205205
disambiguator: CrateDisambiguator,
206+
stable_crate_id: StableCrateId,
206207
panic_strategy: PanicStrategy,
207208
edition: Edition,
208209
has_global_allocator: bool,

compiler/rustc_session/src/session.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ use crate::parse::ParseSess;
88
use crate::search_paths::{PathKind, SearchPath};
99

1010
pub use rustc_ast::attr::MarkedAttrs;
11-
pub use rustc_ast::crate_disambiguator::CrateDisambiguator;
1211
pub use rustc_ast::Attribute;
1312
use rustc_data_structures::flock;
1413
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
@@ -23,6 +22,7 @@ use rustc_errors::json::JsonEmitter;
2322
use rustc_errors::registry::Registry;
2423
use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, DiagnosticId, ErrorReported};
2524
use rustc_lint_defs::FutureBreakage;
25+
pub use rustc_span::crate_disambiguator::CrateDisambiguator;
2626
use rustc_span::edition::Edition;
2727
use rustc_span::source_map::{FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
2828
use rustc_span::{sym, SourceFileHashAlgorithm, Symbol};

0 commit comments

Comments
 (0)