Skip to content

match: Use an aggregate equality comparison for constant array/slice patterns - #155216

Open
jakubadamw wants to merge 16 commits into
rust-lang:mainfrom
jakubadamw:issue-110870-103073
Open

match: Use an aggregate equality comparison for constant array/slice patterns#155216
jakubadamw wants to merge 16 commits into
rust-lang:mainfrom
jakubadamw:issue-110870-103073

Conversation

@jakubadamw

@jakubadamw jakubadamw commented Apr 12, 2026

Copy link
Copy Markdown
Contributor

View all comments

When every element in an array or slice pattern is a constant and there is no .. subpattern, the match builder will now emit a single call to PartialEq::eq instead of comparing each element from the value one by one against the respective constant in the pattern.

This drastically reduces the number of MIR basic blocks for large constant-array matches – e.g. a 64-element [u8; 64] match previously generated 64 separate comparison blocks and now generates just one PartialEq::eq call that LLVM can lower to a memcmp(). The optimisation is gated on having at least two constant elements, meaning single-element arrays will still use a plain scalar comparison.

Example:

const FOO: [u8; 64] = *b"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

pub fn foo(x: &[u8; 64]) -> bool {
    // Before: 64 basic blocks, one per byte.
    // After:  a single `PartialEq::eq()` call.
    matches!(x, &FOO)
}

Closes #103073.
Closes #110870.

@rustbot

rustbot commented Apr 12, 2026

Copy link
Copy Markdown
Collaborator

Some changes occurred in match lowering

cc @Nadrieril

@rustbot rustbot added 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. labels Apr 12, 2026
@rustbot

rustbot commented Apr 12, 2026

Copy link
Copy Markdown
Collaborator

r? @JonathanBrouwer

rustbot has assigned @JonathanBrouwer.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

Why was this reviewer chosen?

The reviewer was selected based on:

  • Owners of files modified in this PR: compiler, mir
  • compiler, mir expanded to 69 candidates
  • Random selection from 12 candidates

@rust-log-analyzer

This comment has been minimized.

@jakubadamw
jakubadamw marked this pull request as draft April 12, 2026 23:12
@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 Apr 12, 2026
@jakubadamw
jakubadamw marked this pull request as ready for review April 12, 2026 23:50
@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 Apr 12, 2026
@JonathanBrouwer

Copy link
Copy Markdown
Member

@bors try @rust-timer queue

@rust-timer

This comment has been minimized.

@rust-bors

This comment has been minimized.

rust-bors Bot pushed a commit that referenced this pull request Apr 13, 2026
match: Use an aggregate equality comparison for constant array/slice patterns when possible
@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Apr 13, 2026
@rust-bors

rust-bors Bot commented Apr 13, 2026

Copy link
Copy Markdown
Contributor

☀️ Try build successful (CI)
Build commit: 5a6dba6 (5a6dba60b1150a8b57fc739b0829fa4a65c5b8b3, parent: 14196dbfa3eb7c30195251eac092b1b86c8a2d84)

@rust-timer

This comment has been minimized.

@rust-timer

Copy link
Copy Markdown
Collaborator

Finished benchmarking commit (5a6dba6): comparison URL.

Overall result: ❌✅ regressions and 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
@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
Regressions ❌
(secondary)
0.2% [0.2%, 0.2%] 1
Improvements ✅
(primary)
-0.4% [-0.4%, -0.4%] 1
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) -0.4% [-0.4%, -0.4%] 1

Max RSS (memory usage)

Results (primary -0.0%, 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.9% [1.0%, 2.8%] 2
Regressions ❌
(secondary)
2.7% [1.2%, 5.0%] 3
Improvements ✅
(primary)
-3.9% [-3.9%, -3.9%] 1
Improvements ✅
(secondary)
-1.8% [-2.2%, -1.6%] 3
All ❌✅ (primary) -0.0% [-3.9%, 2.8%] 3

Cycles

Results (primary -2.3%, secondary 14.4%)

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)
14.4% [2.4%, 26.4%] 2
Improvements ✅
(primary)
-2.3% [-3.1%, -1.7%] 4
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) -2.3% [-3.1%, -1.7%] 4

Binary size

Results (primary -0.1%, secondary 0.1%)

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

mean range count
Regressions ❌
(primary)
0.1% [0.1%, 0.1%] 1
Regressions ❌
(secondary)
0.1% [0.1%, 0.1%] 2
Improvements ✅
(primary)
-0.2% [-0.2%, -0.1%] 4
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) -0.1% [-0.2%, 0.1%] 5

Bootstrap: 491.114s -> 490.988s (-0.03%)
Artifact size: 394.23 MiB -> 394.33 MiB (0.03%)

@rustbot rustbot removed the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Apr 13, 2026
@JonathanBrouwer

Copy link
Copy Markdown
Member

@rustbot reroll
Not familiar enough with this code to comfortably review this, but from a quick glance this looks great, thanks <3

@rustbot rustbot assigned jackh726 and unassigned JonathanBrouwer Apr 15, 2026
Comment thread compiler/rustc_mir_build/src/builder/matches/match_pair.rs Outdated
Comment thread compiler/rustc_mir_build/src/builder/matches/match_pair.rs
Comment on lines +32 to +36
if let PatKind::Constant { value } = pat.kind {
Some(ty::Const::new_value(tcx, value.valtree, value.ty))
} else {
None
}

@dianne dianne Apr 17, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It might also be worth reconstructing aggregate constants for arrays/slices of arrays of constants, etc.? I'm not a specialization expert, but it looks like arrays of bytewise-comparable things are also bytewise-comparable, at least for common array lengths1. Since array and slice equality are specialized based on their element types' bytewise-comparability, we should be able to get better codegen for nested array patterns too (as long as the inner arrays are of one of those common lengths), I think?

View changes since the review

Footnotes

  1. https://github.com/rust-lang/rust/blob/f29256dd1420dc681bf4956e3012ffe9eccdc7e7/library/core/src/cmp/bytewise.rs#L74-L85

@jakubadamw jakubadamw Apr 26, 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.

@dianne, interesting. I’ll look into this next! 🙂

Comment on lines +322 to +326
// When there is no `..`, all elements are constants, and
// there are at least two of them, collapse the individual
// element subpairs into a single aggregate comparison that
// is performed after the length check.
if slice.is_none()

@dianne dianne Apr 17, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

An additional possibility: even if there is a .., the comparisons for the sub-slices before and after the .. could be done via aggregate equality when applicable. Credit to #121540, which I think did this?

Edit: assuming prefixes and suffixes are typically small and hand-written, it's probably not worth the trouble to use aggregate equality for them.

Even if only handling the case with no .., it might be worth moving the special-casing into prefix_slice_suffix to share it between PatKind::Slice and PatKind::Array, since that's where the commonalities live.

Edit: after prefix_slice_suffix's cleanup in #154943, I don't think it makes much sense to put this in there. I still think the logic for deciding whether to use aggregate equality is complex enough that it could be worth factoring out, but that's probably not the way to do it.

View changes since the review

@rust-bors

This comment has been minimized.

Comment thread compiler/rustc_mir_build/src/builder/matches/match_pair.rs
@jackh726

Copy link
Copy Markdown
Member

@dianne do you want to take over review here?

@dianne dianne left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't have much context on the ctfe or const traits side of things to evaluate the approach. cc @oli-obk maybe? It feels like we have to make some sort of compromise here to avoid calling anything const-unstable. Possibly we could block on const_cmp stabilizing, or possibly we could have some workaround until then if we want to land this first.

I think I can handle the technical review, at least. Tentatively, r? me (though feel free to steal the assignment if that'd be easier ^^)

View changes since this review

Comment thread compiler/rustc_mir_build/src/builder/matches/test.rs Outdated
Comment thread compiler/rustc_mir_build/src/builder/matches/match_pair.rs
…ng it

Following the review feedback, `const_to_pat()` now records the original
constant value on the array and slice pattern nodes it expands, and match
lowering reads that value back instead of attempting to reconstruct an
aggregate constant from the individual element subpatterns.

This has two consequences. First, hand-written array and slice patterns
are no longer collapsed into aggregate comparisons; the user's intent to
match element by element is respected before the MIR boundary. Only
patterns that were expanded from an actual constant (a named constant or
a byte-string literal) use the aggregate `PartialEq::eq` comparison, and
for those the semantics of matching against a constant and comparing with
`PartialEq::eq` coincide. Second, nested constant arrays now benefit from
the aggregate comparison as well, since the recorded value covers the
whole constant, whereas the reconstruction required every immediate
element of the pattern to be a leaf constant.
Give the `PartialEq::eq` call emitted for constant array/slice patterns
`UnwindAction::Unreachable` instead of an unwind edge. The built-in
`PartialEq` implementations for arrays and slices can be trusted not to
panic, and the unwind edge would not be harmless: since the aggregate
comparison replaces a series of `SwitchInt` tests that could never
unwind, the extra edge would make borrow-checking stricter about the
drop order in unwinding code, turning previously accepted programs into
errors. The string equality tests keep their unwind edge, as they have
always had one.
@jakubadamw
jakubadamw force-pushed the issue-110870-103073 branch from 2ea4f27 to d2a16fb Compare August 23, 2026 19:09
@rustbot

rustbot commented Aug 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.

@jakubadamw

Copy link
Copy Markdown
Contributor Author

@dianne, thank you for your review, indeed. Apologies, it’s been a few busy weeks, but this is now ready for a re-review. I wonder if it’d make sense to do another perf run, seeing the LLVM 23 upgrade has taken place in the mean time.

@dianne

dianne commented Aug 24, 2026

Copy link
Copy Markdown
Member

no worries! I'll queue up another perf run. I'm not expecting much of a difference since (as far as I know) we don't have a stress test for big constant array/slice patterns as a benchmark, but best not to be surprised. the last perf run was on a version of the PR that used aggregate equality in more places too, so there's a small chance of the old results being off if a benchmark has big array/slice constant patterns of non-bytewise-comparable types.

@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 Aug 24, 2026
@rust-bors

This comment has been minimized.

rust-bors Bot pushed a commit that referenced this pull request Aug 24, 2026
match: Use an aggregate equality comparison for constant array/slice patterns
@rust-bors

rust-bors Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

☀️ Try build successful (CI)
Build commit: 950abd5 (950abd5388fe918da67b410a597cb425e519dc45)
Base parent: ac62df9 (ac62df9b49f9b9036af2a4957db70bf3850785e1)

@rust-timer

This comment has been minimized.

@rust-timer

Copy link
Copy Markdown
Collaborator

Finished benchmarking commit (950abd5): comparison URL.

Overall result: ❌✅ regressions and improvements - please read:

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.

Next, please: If you can, justify the regressions found in this try perf run in writing along with @rustbot label: +perf-regression-triaged. If not, fix the regressions and do another perf run. Neutral or positive results will clear the label automatically.

@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.3% [0.3%, 0.3%] 2
Regressions ❌
(secondary)
0.1% [0.1%, 0.1%] 2
Improvements ✅
(primary)
-0.2% [-0.3%, -0.1%] 3
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) -0.0% [-0.3%, 0.3%] 5

Max RSS (memory usage)

Results (primary -0.8%)

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

mean range count
Regressions ❌
(primary)
3.0% [3.0%, 3.0%] 1
Regressions ❌
(secondary)
- - 0
Improvements ✅
(primary)
-2.7% [-4.1%, -1.2%] 2
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) -0.8% [-4.1%, 3.0%] 3

Cycles

Results (primary -0.0%, secondary -3.0%)

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

mean range count
Regressions ❌
(primary)
2.3% [2.3%, 2.3%] 1
Regressions ❌
(secondary)
- - 0
Improvements ✅
(primary)
-2.4% [-2.4%, -2.4%] 1
Improvements ✅
(secondary)
-3.0% [-3.0%, -3.0%] 1
All ❌✅ (primary) -0.0% [-2.4%, 2.3%] 2

Binary size

Results (primary -0.1%)

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

mean range count
Regressions ❌
(primary)
1.0% [1.0%, 1.0%] 1
Regressions ❌
(secondary)
- - 0
Improvements ✅
(primary)
-0.3% [-0.8%, -0.1%] 7
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) -0.1% [-0.8%, 1.0%] 8

Bootstrap: 475.143s -> 469.292s (-1.23%)
Artifact size: 400.28 MiB -> 400.36 MiB (0.02%)

@rustbot rustbot added perf-regression Performance regression. and removed S-waiting-on-perf Status: Waiting on a perf run to be completed. labels Aug 24, 2026
@rust-bors

rust-bors Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

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

@dianne dianne left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Finally getting back around to this. Thanks for your patience!

Perf seems fine probably? I haven't tried profiling locally to see where the extra instructions are coming from, but at a glance I'm not seeing anything too relevant in the perf report. Considering nothing looks extreme and the prior run came back clean, I'm not too worried.

@rustbot author

View changes since this review


impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Check if we can use aggregate `PartialEq::eq` comparisons for constant array/slice patterns.
/// This is not possible in const contexts, because `PartialEq` is not const-stable yet.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
/// This is not possible in const contexts, because `PartialEq` is not const-stable yet.
/// This is not possible in const contexts, because `PartialEq` is not const-stable yet.
// FIXME(const_cmp): remove this restriction once `const_cmp` stabilizes

Not sure whether this will help make it easier to notice, but it can't hurt!

Comment on lines +16 to +19
/// Below this length, an array or slice pattern is compared element by element
/// rather than as a single aggregate, since the per-element comparisons are
/// unlikely to be more expensive than a `PartialEq::eq` call.
const AGGREGATE_EQ_MIN_LEN: usize = 4;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm not too picky here, but do you have numbers or codegen comparisons for this? Could be a nice simplification to get rid of the cutoff number if it's not impactful. I expect on the types we're doing this for, eq calls are pretty cheap.

Comment on lines +53 to +55
let (ty::Array(element_ty, _) | ty::Slice(element_ty)) = *pattern.ty.kind() else {
return None;
};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Since the expanded_const_value field is currently only added for arrays and slices, maybe this should be an assertion? Alternatively, we could always put the expanded const value in the THIR to keep all the logic for this in this function.

Comment on lines +432 to +435
// If this pattern was expanded from a constant, compare the
// whole slice against that constant at once via
// `PartialEq::eq` after the length check, rather than
// element by element.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

PartialEq::eq on slices should take length into account. Could we just do a TestableCase::Constant without an additional length check?

Comment on lines +184 to +186
// That is sound because they are only used for element types whose
// `PartialEq` impl compares the aggregates directly with the
// `compare_bytes` and `raw_eq` intrinsics, which cannot panic.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I wonder if there's a good way to assert that we get the monomorphization we expect, or at least test for it. Maybe with a codegen-units/item-collection/ test we could look for the mono-item we want? Not sure if there's a better approach. Unfortunately not my area of expertise.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe that'd be overkill for how much it'd give us. Not sure. I'm kind of wary about asserting that standard library functions can't unwind, so having some certainty that things are working as expected would be good. Maybe we should at least document in the standard library that we require those impls not to panic?

@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 Sep 9, 2026
@rustbot

rustbot commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator

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

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

Labels

perf-regression Performance regression. 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Large amount of generated code for match statements with large arrays Weird Match Statement Codegen With Byte Strings

10 participants