Skip to content

Optimize handling of exact-match types - #165795

Open
nnethercote wants to merge 3 commits into
rust-lang:mainfrom
nnethercote:exact-match
Open

nnethercote wants to merge 3 commits into
rust-lang:mainfrom
nnethercote:exact-match

Conversation

@nnethercote

@nnethercote nnethercote commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

View all comments

Details in individual commits. When looking at these changes, is_exact_match_ty is a good place to start.

r? @adwinwhite

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. WG-trait-system-refactor The Rustc Trait System Refactor Initiative (-Znext-solver) labels Nov 11, 2026
@nnethercote

Copy link
Copy Markdown
Contributor Author

@bors try @rust-timer queue

@rust-timer

This comment has been minimized.

@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Nov 11, 2026
rust-bors Bot pushed a commit that referenced this pull request Nov 11, 2026
Optimize handling of exact-match types
@rust-bors

This comment has been minimized.

@rust-bors

rust-bors Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

☀️ Try build successful (CI)
Build commit: 56f1bf8 (56f1bf8c3136ff52cb099e93ee0abd19c800112d)
Base parent: 9c56488 (9c5648833e5ceb667a708d53c00b83ecc9e610d5)

@rust-timer

This comment has been minimized.

@rust-timer

Copy link
Copy Markdown

Finished benchmarking commit (56f1bf8): comparison URL.

Overall result: ✅ improvements - no action needed

Benchmarking means the PR may be perf-sensitive. It's automatically marked not fit for rolling up. Overriding is possible but disadvised: it risks changing compiler perf.

@bors rollup=never rustc-perf
@rustbot label: -S-waiting-on-perf -perf-regression

Instruction count

Our most reliable metric. Used to determine the overall result above. However, even this metric can be noisy.

mean range count
Regressions ❌
(primary)
0.2% [0.2%, 0.3%] 3
Regressions ❌
(secondary)
- - 0
Improvements ✅
(primary)
-11.9% [-29.5%, -0.2%] 49
Improvements ✅
(secondary)
-13.1% [-33.7%, -0.0%] 14
All ❌✅ (primary) -11.2% [-29.5%, 0.3%] 52

Max RSS (memory usage)

Results (primary -2.4%, secondary 0.5%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
1.4% [1.2%, 1.5%] 2
Regressions ❌
(secondary)
2.6% [2.2%, 3.0%] 3
Improvements ✅
(primary)
-3.4% [-4.8%, -2.1%] 7
Improvements ✅
(secondary)
-5.9% [-5.9%, -5.9%] 1
All ❌✅ (primary) -2.4% [-4.8%, 1.5%] 9

Cycles

Results (primary -7.4%, secondary -7.1%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
3.2% [3.2%, 3.2%] 1
Improvements ✅
(primary)
-7.4% [-12.9%, -2.1%] 30
Improvements ✅
(secondary)
-8.3% [-16.8%, -5.2%] 9
All ❌✅ (primary) -7.4% [-12.9%, -2.1%] 30

Binary size

This perf run didn't have relevant results for this metric.

Bootstrap: 482.775s -> 485.777s (0.62%)
Artifact size: 406.47 MiB -> 406.43 MiB (-0.01%)

@rustbot rustbot removed the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Nov 11, 2026
@nnethercote

Copy link
Copy Markdown
Contributor Author

LLM disclosure: I use LLM analysis to help with this. I wrote the code and text myself.

@nnethercote

Copy link
Copy Markdown
Contributor Author

Perf results are very good:

  • instruction count improvements of up to 33%, mostly on bitmaps and typenum. (Locally I see -46% for hybrid-array-0.4.13, which isn't part of rustc-perf.)
  • cycle count/wall-time improvements of up to 16%. (Locally I see -27% for hybrid-array-0.4.13.)
    • Possibly these reductions are smaller than the instruction count reduction because this PR eliminated some very hot loops that probably have good memory locality.

Ironically I set out to improve performance of the new solver relative to the old solver, but I ended up improving both roughly equally, so the new solver vs. old solver relative comparison isn't any better.

The code is in good shape but I need to write tests. Before I do that I want to get feedback from trait solver experts on whether this is a reasonable idea, given that this code adds a moderate level of complexity.

cc @lcnr @ShoyuVanilla @jdonszelmann

@ShoyuVanilla

ShoyuVanilla commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Wow, this is a huge win! I'll also ping @adwinwhite, who knows the solver better than I do 😅

@nnethercote
nnethercote marked this pull request as ready for review November 18, 2026 00:37
@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Nov 18, 2026
@nnethercote

Copy link
Copy Markdown
Contributor Author

I moved it out of draft status because I think the compiler code is in good enough shape.

@adwinwhite

Copy link
Copy Markdown
Contributor

The perf is really nice. I'll get to this tomorrow.

@adwinwhite adwinwhite left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The complexity feels acceptable to me.
I guess the main perf win comes from the query cache?

View changes since this review

Comment on lines +316 to +317
/// property to skip uninteresting cases. Useful for candidate assembly, but not for auto-trait
/// existence checks, for example.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So if we use for_each_candidate_impl in disqualify_auto_trait_candidate_due_to_possible_impl, some tests would fail? 🤔

I wonder whether we can replace for_each_relevant_impl completely. Having two similar but slightly different methods doesn't look good :3

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given that a type is not exact-match if it contains Param, #84857 wouldn't happen again due to this change? 🤔

Besides, we can properly reject this:

struct Foo<T>(T);

unsafe impl Send for Foo<u8> {}

trait WithAssoc { type Output; }
impl<T: Send> WithAssoc for T { type Output = Self; }
impl WithAssoc for Foo<u32> { type Output = Box<i32>; }

We can look into this separately though.

@nnethercote nnethercote Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So if we use for_each_candidate_impl in disqualify_auto_trait_candidate_due_to_possible_impl, some tests would fail?

It's likely that no tests would fail because, as written, the exact-match optimization doesn't kick in unless there are 16 or more impls in one simp bucket. But I think it would be possible to write a test where doing that would fail.

Having two similar but slightly different methods doesn't look good

The difference between the two functions is basically "could unify?" vs "exists for this root".

Given that a type is not exact-match if it contains Param, #84857 wouldn't happen again due to this change?

I think that's correct. Any type containing Param should be entirely unaffected by this PR.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The difference between the two functions is basically "could unify?" vs "exists for this root".

I think the two aren't cleanly distinguishable semantically, since the optimization in for_each_candidate_impl is only triggered sometimes.

Given that completely removing the old one is risky and requires more careful consideration, we can tackle it separately and land this as is.

Comment on lines +174 to +185
/// The following types are "exact-match":
/// - Scalar types: `bool`, `char`, integers, floats, `str`, and `!`.
/// - Certain aggregate types (ADTs, tuples, arrays, slices) that satisfy the following:
/// - Any type parameters must themselves be exact-match types.
/// - Any const parameters must be trivial `usize` leaf consts.
/// - No region parameters are allowed.
///
/// The crucial thing that follows is that we can trivially test if two exact-match `Ty`s unify via
/// equality: they unify iff they are equal. This property is used to optimize candidate selection,
/// most notably in cases where a single generic ADT is instantiated many times. E.g. `bitmaps` has
/// a type `BitsImpl<N>` that is instantiated over 1024 distinct values of `N`, all of which impl a
/// single trait `Bits`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about we start with the definition of exact_match types and then list what it currently consists of :>

My understanding is that the list follows from the principle that a Ty is exact-match if its unification with another type implies equality. (Mainly, this means an exact-match type doesn't contain types that could be further resolved or instantiated.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Comment on lines +247 to +248
// because it's possible for consts with different types but equal values (e.g. `5usize`
// and `5u64`) to unify. `usize` is the type that shows up in various real-world crates

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the unification really possible? The const type is already determined by ADT's DefId so that we can't have both struct A<const N: usize> and struct A<const N: u64> 🤔

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I think you are right. I thought this was possible because structurally_relate_consts doesn't consider the type when comparing two leaf values, but I guess we can't ever get to that point if the types are different?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, it should be impossible so we don't check the types in structurally_relate_consts

@adwinwhite adwinwhite Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comments here need to be updated?

Comment on lines +157 to +161
let exact_match_self_tys =
tcx.trait_impl_exact_match_self_tys((trait_def_id, simp));
assert_eq!(impls_for_type.len(), exact_match_self_tys.len());
for (&impl_def_id, &exact_match_self_ty) in
iter::zip(impls_for_type, exact_match_self_tys)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can directly return impl_def_id from the query trait_impl_exact_match_self_tys instead of zip here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok. More data to store in the query table, but less zipping... probably makes little difference to perf overall.

@adwinwhite

Copy link
Copy Markdown
Contributor

@rustbot author

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Nov 20, 2026
@rustbot

rustbot commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

Reminder, once the PR becomes ready for a review, use @rustbot ready.

`simplify_type` simplifies a type (if possible) to its outermost
injective layer, which lets us partition types into small sets of
possibly unifiable types. This works well for performance except for one
case: ADTs with generic params and many instances. For example,
`bitmaps` has `impl Bits for BitsImpl<N>` for 1024 distinct const values
of `N`, all of which need to be proved distinct the expensive way.

This commit adds a mechanism to make these cases cheaper. It introduces
the concept of an "exact-match" type, which is one where simple `Ty`
equality is enough to determine if two types unify. When exact-match
types are involved, we can do various checks much more quickly.

This requires:
- a new visitor that determines if a type is exact-match
- a new query
- some new methods, most notably `for_each_candidate_impl`, which is an
  optimized version of the existing `for_each_relevant_impl`

This gives big wins on benchmarks that stress the trait solver (new and
old) such as `bitmaps`, `typenum`, `hybrid-array`, `arraystring`.
When inserting into the specialization graph, we can use exact-match
status to avoid some expensive overlap checks.
- Remove unnecessary `usize` const restriction
- Store `DefId` for each entry in the `trait_impl_exact_match_self_tys`
  query.
- Comment improvements
@rustbot

rustbot commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed.

Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers.

@nnethercote

Copy link
Copy Markdown
Contributor Author

I have added a new commit to address the comments.

@rustbot ready

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Nov 23, 2026

@adwinwhite adwinwhite left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

r=me after fixing comments

View changes since this review

Comment on lines +247 to +248
// because it's possible for consts with different types but equal values (e.g. `5usize`
// and `5u64`) to unify. `usize` is the type that shows up in various real-world crates

@adwinwhite adwinwhite Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comments here need to be updated?

Comment on lines +316 to +317
/// property to skip uninteresting cases. Useful for candidate assembly, but not for auto-trait
/// existence checks, for example.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The difference between the two functions is basically "could unify?" vs "exists for this root".

I think the two aren't cleanly distinguishable semantically, since the optimization in for_each_candidate_impl is only triggered sometimes.

Given that completely removing the old one is risky and requires more careful consideration, we can tackle it separately and land this as is.

@lcnr lcnr left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's subtle that for_each_candidate_impl must not be used for the auto trait check

fn disqualify_auto_trait_candidate_due_to_possible_impl(
&mut self,
goal: Goal<I, TraitClause<I>>,
) -> Option<Result<Candidate<I>, NoSolutionOrRerunNonErased>> {
let self_ty = goal.predicate.self_ty();
let check_impls = || {
let mut disqualifying_impl = None;
self.cx().for_each_relevant_impl(goal.predicate.trait_ref, |impl_def_id| {
disqualifying_impl = Some(impl_def_id);
});
if let Some(def_id) = disqualifying_impl {
trace!(?def_id, ?goal, "disqualified auto-trait implementation");
// No need to actually consider the candidate here,
// since we do that in `consider_impl_candidate`.
return Some(Err(NoSolution.into()));
} else {
None
}
};

A few more thoughts:

"exact match" feels confusing to me. We tend to use "structural identity" here. As in "self_ty_structural_identity". "exact match" is a new terminology and got me to think of pattern matching or StructuralPartialEq.

"types with exact structural equality" feels like maybe how i would talk about it


I dislike having both for_each_candidate_impl and for_each_relevant_impl. In a way there's for_each_impl_reject_via_self_ty and for_each_impl_reject_via_self_ty_shallow/for_each_impl_reject_via_simplified_self_ty 🤔 that makes it a lot clearer what's going on


If we make this a TypeFlag we could change the DeepRejectCtxt to also have a "typeflag set for both types, if so, deep reject if not structurally identical" fast path, which would be good for non-self types. Unsure how big of an effect it would have

View changes since this review

@lcnr

lcnr commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

I guess I do consider the first two considerations to be blocking I think 🤔

@rust-bors

rust-bors Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

☔ The latest upstream changes (presumably #166507) made this pull request unmergeable. Please resolve the merge conflicts by rebasing.

@nnethercote

Copy link
Copy Markdown
Contributor Author

I guess I do consider the first two considerations to be blocking I think 🤔

Which two are the first two? The for_/for_ split and the "exact-match" name?

it's subtle that for_each_candidate_impl must not be used for the auto trait check

I dislike having both for_each_candidate_impl and for_each_relevant_impl. In a way there's for_each_impl_reject_via_self_ty and for_each_impl_reject_via_self_ty_shallow/for_each_impl_reject_via_simplified_self_ty 🤔 that makes it a lot clearer what's going on

Is this objection just a question of naming (easy to fix), or is the presence of the split (harder)?

"exact match" feels confusing to me. We tend to use "structural identity" here. As in "self_ty_structural_identity". "exact match" is a new terminology and got me to think of pattern matching or StructuralPartialEq.

"types with exact structural equality" feels like maybe how i would talk about it

"Structural equality" means "two types are syntactically identical", right? That allows regions, and inference variables, etc.

"Semantic identity/equality" basically means "two types are equall even though they might not be syntactically identical".

Both of these are relationships between two types.

The "exact-match" concept applies to a single type. When comparing two exact-match types, syntactic equality is semantic equality.

It's a new concept so it deserves a new name. What do you think about "structurally-unifiable"? It's longer than "exact-match", but brings in the notion of structural equality without using "equality" (to avoid confusion with StructuralPartialEq).

If we make this a TypeFlag we could change the DeepRejectCtxt to also have a "typeflag set for both types, if so, deep reject if not structurally identical" fast path, which would be good for non-self types.

Interesting idea. Would be a good follow-up.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. WG-trait-system-refactor The Rustc Trait System Refactor Initiative (-Znext-solver)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants