Skip to content

Commit b82ca8c

Browse files
committed
Auto merge of #139018 - oli-obk:incremental-trait-impls, r=<try>
Decouple trait impls of different traits wrt incremental Adding a trait impl for `Foo` unconditionally affected all queries that are interested in a completely independent trait `Bar`. Let's see if perf has any effect on this. If not, we can land it and I poke further at it to see if we can decouple things further. We probably don't have a good perf test for it tho. r? `@ghost`
2 parents ecb170a + 9d05efb commit b82ca8c

File tree

18 files changed

+64
-39
lines changed

18 files changed

+64
-39
lines changed

compiler/rustc_hir_analysis/src/check/always_applicable.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,8 @@ use crate::hir::def_id::{DefId, LocalDefId};
3636
/// cannot do `struct S<T>; impl<T:Clone> Drop for S<T> { ... }`).
3737
pub(crate) fn check_drop_impl(
3838
tcx: TyCtxt<'_>,
39-
drop_impl_did: DefId,
39+
drop_impl_did: LocalDefId,
4040
) -> Result<(), ErrorGuaranteed> {
41-
let drop_impl_did = drop_impl_did.expect_local();
42-
4341
match tcx.impl_polarity(drop_impl_did) {
4442
ty::ImplPolarity::Positive => {}
4543
ty::ImplPolarity::Negative => {

compiler/rustc_hir_analysis/src/check/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -114,11 +114,11 @@ pub fn provide(providers: &mut Providers) {
114114
}
115115

116116
fn adt_destructor(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::Destructor> {
117-
tcx.calculate_dtor(def_id.to_def_id(), always_applicable::check_drop_impl)
117+
tcx.calculate_dtor(def_id, always_applicable::check_drop_impl)
118118
}
119119

120120
fn adt_async_destructor(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::AsyncDestructor> {
121-
tcx.calculate_async_dtor(def_id.to_def_id(), always_applicable::check_drop_impl)
121+
tcx.calculate_async_dtor(def_id, always_applicable::check_drop_impl)
122122
}
123123

124124
/// Given a `DefId` for an opaque type in return position, find its parent item's return

compiler/rustc_hir_analysis/src/coherence/mod.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -153,9 +153,12 @@ pub(crate) fn provide(providers: &mut Providers) {
153153
}
154154

155155
fn coherent_trait(tcx: TyCtxt<'_>, def_id: DefId) -> Result<(), ErrorGuaranteed> {
156+
let impls = tcx.local_trait_impls(def_id);
156157
// If there are no impls for the trait, then "all impls" are trivially coherent and we won't check anything
157158
// anyway. Thus we bail out even before the specialization graph, avoiding the dep_graph edge.
158-
let Some(impls) = tcx.all_local_trait_impls(()).get(&def_id) else { return Ok(()) };
159+
if impls.is_empty() {
160+
return Ok(());
161+
}
159162
// Trigger building the specialization graph for the trait. This will detect and report any
160163
// overlap errors.
161164
let mut res = tcx.ensure_ok().specialization_graph_of(def_id);

compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs

+2-8
Original file line numberDiff line numberDiff line change
@@ -330,14 +330,8 @@ provide! { tcx, def_id, other, cdata,
330330

331331
visibility => { cdata.get_visibility(def_id.index) }
332332
adt_def => { cdata.get_adt_def(def_id.index, tcx) }
333-
adt_destructor => {
334-
let _ = cdata;
335-
tcx.calculate_dtor(def_id, |_,_| Ok(()))
336-
}
337-
adt_async_destructor => {
338-
let _ = cdata;
339-
tcx.calculate_async_dtor(def_id, |_,_| Ok(()))
340-
}
333+
adt_destructor => { table }
334+
adt_async_destructor => { table }
341335
associated_item_def_ids => {
342336
tcx.arena.alloc_from_iter(cdata.get_associated_item_or_field_def_ids(def_id.index))
343337
}

compiler/rustc_metadata/src/rmeta/encoder.rs

+8
Original file line numberDiff line numberDiff line change
@@ -1633,6 +1633,14 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
16331633
record!(self.tables.fn_sig[variant.def_id] <- fn_sig);
16341634
}
16351635
}
1636+
1637+
if let Some(destructor) = tcx.adt_destructor(local_def_id) {
1638+
record!(self.tables.adt_destructor[def_id] <- destructor);
1639+
}
1640+
1641+
if let Some(destructor) = tcx.adt_async_destructor(local_def_id) {
1642+
record!(self.tables.adt_async_destructor[def_id] <- destructor);
1643+
}
16361644
}
16371645

16381646
#[instrument(level = "debug", skip(self))]

compiler/rustc_metadata/src/rmeta/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,8 @@ define_tables! {
446446
fn_arg_names: Table<DefIndex, LazyArray<Option<Ident>>>,
447447
coroutine_kind: Table<DefIndex, hir::CoroutineKind>,
448448
coroutine_for_closure: Table<DefIndex, RawDefId>,
449+
adt_destructor: Table<DefIndex, LazyValue<ty::Destructor>>,
450+
adt_async_destructor: Table<DefIndex, LazyValue<ty::AsyncDestructor>>,
449451
coroutine_by_move_body_def_id: Table<DefIndex, RawDefId>,
450452
eval_static_initializer: Table<DefIndex, LazyValue<mir::interpret::ConstAllocation<'static>>>,
451453
trait_def: Table<DefIndex, LazyValue<ty::TraitDef>>,

compiler/rustc_middle/src/hir/map.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -368,7 +368,7 @@ impl<'tcx> TyCtxt<'tcx> {
368368
}
369369

370370
pub fn hir_trait_impls(self, trait_did: DefId) -> &'tcx [LocalDefId] {
371-
self.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..])
371+
self.local_trait_impls(trait_did)
372372
}
373373

374374
/// Gets the attributes on the crate. This is preferable to

compiler/rustc_middle/src/hir/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,8 @@ pub fn provide(providers: &mut Providers) {
238238
}
239239
};
240240
providers.all_local_trait_impls = |tcx, ()| &tcx.resolutions(()).trait_impls;
241+
providers.local_trait_impls =
242+
|tcx, trait_id| tcx.resolutions(()).trait_impls.get(&trait_id).map_or(&[], |xs| &xs[..]);
241243
providers.expn_that_defined =
242244
|tcx, id| tcx.resolutions(()).expn_that_defined.get(&id).copied().unwrap_or(ExpnId::root());
243245
providers.in_scope_traits_map = |tcx, id| {

compiler/rustc_middle/src/query/mod.rs

+5
Original file line numberDiff line numberDiff line change
@@ -1502,6 +1502,11 @@ rustc_queries! {
15021502
desc { "finding local trait impls" }
15031503
}
15041504

1505+
/// Return all `impl` blocks of the given trait in the current crate.
1506+
query local_trait_impls(trait_id: DefId) -> &'tcx [LocalDefId] {
1507+
desc { "finding local trait impls of `{}`", tcx.def_path_str(trait_id) }
1508+
}
1509+
15051510
/// Given a trait `trait_id`, return all known `impl` blocks.
15061511
query trait_impls_of(trait_id: DefId) -> &'tcx ty::trait_def::TraitImpls {
15071512
arena_cache

compiler/rustc_middle/src/ty/parameterized.rs

+2
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,11 @@ trivially_parameterized_over_tcx! {
6565
crate::middle::lib_features::FeatureStability,
6666
crate::middle::resolve_bound_vars::ObjectLifetimeDefault,
6767
crate::mir::ConstQualifs,
68+
ty::AsyncDestructor,
6869
ty::AssocItemContainer,
6970
ty::Asyncness,
7071
ty::DeducedParamAttrs,
72+
ty::Destructor,
7173
ty::Generics,
7274
ty::ImplPolarity,
7375
ty::ImplTraitInTraitData,

compiler/rustc_middle/src/ty/util.rs

+24-14
Original file line numberDiff line numberDiff line change
@@ -389,24 +389,29 @@ impl<'tcx> TyCtxt<'tcx> {
389389
/// Calculate the destructor of a given type.
390390
pub fn calculate_dtor(
391391
self,
392-
adt_did: DefId,
393-
validate: impl Fn(Self, DefId) -> Result<(), ErrorGuaranteed>,
392+
adt_did: LocalDefId,
393+
validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
394394
) -> Option<ty::Destructor> {
395395
let drop_trait = self.lang_items().drop_trait()?;
396396
self.ensure_ok().coherent_trait(drop_trait).ok()?;
397397

398-
let ty = self.type_of(adt_did).instantiate_identity();
399398
let mut dtor_candidate = None;
400-
self.for_each_relevant_impl(drop_trait, ty, |impl_did| {
399+
// `Drop` impls can only be written in the same crate as the adt, and cannot be blanket impls
400+
for &impl_did in self.local_trait_impls(drop_trait) {
401+
let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
402+
if adt_def.did() != adt_did.to_def_id() {
403+
continue;
404+
}
405+
401406
if validate(self, impl_did).is_err() {
402407
// Already `ErrorGuaranteed`, no need to delay a span bug here.
403-
return;
408+
continue;
404409
}
405410

406411
let Some(item_id) = self.associated_item_def_ids(impl_did).first() else {
407412
self.dcx()
408413
.span_delayed_bug(self.def_span(impl_did), "Drop impl without drop function");
409-
return;
414+
continue;
410415
};
411416

412417
if let Some((old_item_id, _)) = dtor_candidate {
@@ -417,7 +422,7 @@ impl<'tcx> TyCtxt<'tcx> {
417422
}
418423

419424
dtor_candidate = Some((*item_id, self.impl_trait_header(impl_did).unwrap().constness));
420-
});
425+
}
421426

422427
let (did, constness) = dtor_candidate?;
423428
Some(ty::Destructor { did, constness })
@@ -426,26 +431,31 @@ impl<'tcx> TyCtxt<'tcx> {
426431
/// Calculate the async destructor of a given type.
427432
pub fn calculate_async_dtor(
428433
self,
429-
adt_did: DefId,
430-
validate: impl Fn(Self, DefId) -> Result<(), ErrorGuaranteed>,
434+
adt_did: LocalDefId,
435+
validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
431436
) -> Option<ty::AsyncDestructor> {
432437
let async_drop_trait = self.lang_items().async_drop_trait()?;
433438
self.ensure_ok().coherent_trait(async_drop_trait).ok()?;
434439

435-
let ty = self.type_of(adt_did).instantiate_identity();
436440
let mut dtor_candidate = None;
437-
self.for_each_relevant_impl(async_drop_trait, ty, |impl_did| {
441+
// `AsyncDrop` impls can only be written in the same crate as the adt, and cannot be blanket impls
442+
for &impl_did in self.local_trait_impls(async_drop_trait) {
443+
let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
444+
if adt_def.did() != adt_did.to_def_id() {
445+
continue;
446+
}
447+
438448
if validate(self, impl_did).is_err() {
439449
// Already `ErrorGuaranteed`, no need to delay a span bug here.
440-
return;
450+
continue;
441451
}
442452

443453
let [future, ctor] = self.associated_item_def_ids(impl_did) else {
444454
self.dcx().span_delayed_bug(
445455
self.def_span(impl_did),
446456
"AsyncDrop impl without async_drop function or Dropper type",
447457
);
448-
return;
458+
continue;
449459
};
450460

451461
if let Some((_, _, old_impl_did)) = dtor_candidate {
@@ -456,7 +466,7 @@ impl<'tcx> TyCtxt<'tcx> {
456466
}
457467

458468
dtor_candidate = Some((*future, *ctor, impl_did));
459-
});
469+
}
460470

461471
let (future, ctor, _) = dtor_candidate?;
462472
Some(ty::AsyncDestructor { future, ctor })

compiler/rustc_mir_transform/src/check_const_item_mutation.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,10 @@ impl<'tcx> ConstMutationChecker<'_, 'tcx> {
5353
//
5454
// #[const_mutation_allowed]
5555
// pub const LOG: Log = Log { msg: "" };
56-
match self.tcx.calculate_dtor(def_id, |_, _| Ok(())) {
57-
Some(_) => None,
58-
None => Some(def_id),
56+
match self.tcx.type_of(def_id).skip_binder().ty_adt_def().map(|adt| adt.has_dtor(self.tcx))
57+
{
58+
Some(true) => None,
59+
Some(false) | None => Some(def_id),
5960
}
6061
}
6162

compiler/rustc_monomorphize/messages.ftl

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ monomorphize_large_assignments =
4848
.note = The current maximum size is {$limit}, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]`
4949
5050
monomorphize_no_optimized_mir =
51-
missing optimized MIR for an item in the crate `{$crate_name}`
51+
missing optimized MIR for `{$instance}` in the crate `{$crate_name}`
5252
.note = missing optimized MIR for this item (was the crate `{$crate_name}` compiled with `--emit=metadata`?)
5353
5454
monomorphize_recursion_limit =

compiler/rustc_monomorphize/src/collector.rs

+1
Original file line numberDiff line numberDiff line change
@@ -989,6 +989,7 @@ fn should_codegen_locally<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) ->
989989
tcx.dcx().emit_fatal(NoOptimizedMir {
990990
span: tcx.def_span(def_id),
991991
crate_name: tcx.crate_name(def_id.krate),
992+
instance: instance.to_string(),
992993
});
993994
}
994995

compiler/rustc_monomorphize/src/errors.rs

+1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ pub(crate) struct NoOptimizedMir {
2424
#[note]
2525
pub span: Span,
2626
pub crate_name: Symbol,
27+
pub instance: String,
2728
}
2829

2930
#[derive(LintDiagnostic)]

src/tools/clippy/clippy_lints/src/derive.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -324,11 +324,9 @@ fn check_copy_clone<'tcx>(cx: &LateContext<'tcx>, item: &Item<'_>, trait_ref: &h
324324
// there's a Copy impl for any instance of the adt.
325325
if !is_copy(cx, ty) {
326326
if ty_subs.non_erasable_generics().next().is_some() {
327-
let has_copy_impl = cx.tcx.all_local_trait_impls(()).get(&copy_id).is_some_and(|impls| {
328-
impls.iter().any(|&id| {
329-
matches!(cx.tcx.type_of(id).instantiate_identity().kind(), ty::Adt(adt, _)
327+
let has_copy_impl = cx.tcx.local_trait_impls(copy_id).iter().any(|&id| {
328+
matches!(cx.tcx.type_of(id).instantiate_identity().kind(), ty::Adt(adt, _)
330329
if ty_adt.did() == adt.did())
331-
})
332330
});
333331
if !has_copy_impl {
334332
return;

tests/ui/rmeta/no_optitimized_mir.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,4 @@ fn main() {
1010
rmeta_meta::missing_optimized_mir();
1111
}
1212

13-
//~? ERROR missing optimized MIR for an item in the crate `rmeta_meta`
13+
//~? ERROR missing optimized MIR for `missing_optimized_mir` in the crate `rmeta_meta`

tests/ui/rmeta/no_optitimized_mir.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
error: missing optimized MIR for an item in the crate `rmeta_meta`
1+
error: missing optimized MIR for `missing_optimized_mir` in the crate `rmeta_meta`
22
|
33
note: missing optimized MIR for this item (was the crate `rmeta_meta` compiled with `--emit=metadata`?)
44
--> $DIR/auxiliary/rmeta-meta.rs:10:1

0 commit comments

Comments
 (0)