Commit Graph

651 Commits

Author SHA1 Message Date
Jonathan Brouwer
072427132d Rollup merge of #160886 - nnethercote:GoalStalledOn-stalled_maybe_info, r=lcnr
Trim `GoalStalledOn::Certainty`

It's always `Certainty::Maybe`, so we can trim it down to just the `MaybeInfo` that is within `Certainty::Maybe`.

r? @lcnr
2026-08-12 13:52:40 +02:00
Jonathan Brouwer
b6a4f6244d Rollup merge of #159987 - Dnreikronos:trait_solver/canonical_response_assumptions, r=lcnr
trait solver: Track canonical response universe assumptions

Fixes rust-lang/rust#159889

Canonical responses recreate universes for placeholders created while evaluating a query. Region constraints are handled inside the query, but opaque type constraints can still carry those placeholders back to the caller. Without an assumptions entry, eager placeholder handling hits the `unwrap()` in `get_placeholder_assumptions`.

Record empty assumptions when recreating response universes under `-Zassumptions-on-binders`. idk if empty assumptions is the final shape irl, but imo keeping this next to `create_next_universe` is the right local fix. It restores the invariant where the universe enters the caller and matches bookkeeping from other binder entry paths. fyi the issue repro now reports E0277 instead of ICEing.
2026-08-12 13:52:40 +02:00
bors
41fb9d4587 Auto merge of #160605 - nnethercote:four-new-solver-speedups, r=jdonszelmann
Three new-solver speedups



Details in individual commits.

r? @lcnr
2026-08-12 08:11:16 +00:00
Nicholas Nethercote
7fe7add225 Trim GoalStalledOn::stalled_certainty
It's always `Certainty::Maybe`, so we can trim it down to just the
`MaybeInfo` that is within `Certainty::Maybe`. And then the same change
can be made to the field of `RerunStalled::WontMakeProgress`, and
`goal_remains_stalled` can return a bool, and a hot `matches!` in
`try_evaluate_obligations` that never failed can be removed.
2026-08-12 09:25:03 +10:00
Nicholas Nethercote
3cf1de3004 Avoid another duplicate goal.predicate.alias.trait_ref(cx)
It's expensive and is called unconditionally in
`NormalizesTo::consider_impl_candidate`, which is always called within a
loop. The result is invariant across the loop, so this commit hoists the
call outside of `consider_impl_candidate` and passes the return value in.

Notes:

- At the hoist sites, the expression is `goal.predicate.trait_ref(cx)`;
  for `NormalizesTo` this dispatches to
  `goal.predicate.alias.trait_ref(cx)`.

- Two other `GoalKind` methods are affected, but this doesn't
  change perf because they can get the `goal_trait_ref` cheaply.
2026-08-12 07:31:53 +10:00
Nicholas Nethercote
6c28fdda79 Reorder assemble_impl_candidates checks
`impl_is_default` is moderately expensive. This commit moves the cheaper
`consider_impl_candidate` check (which does `args_may_unify`) ahead, for
a small perf win. (Note: this change makes the new solver match what the
old solver does in `assemble_candidates_from_impls`.)
2026-08-12 07:31:53 +10:00
Jana Dönszelmann
57cac28b92 fix 158441 and unify old and new solver code for ty_or_const_infer_var_changed. 2026-08-11 16:24:42 +02:00
Jana Dönszelmann
e1b5c1a8ff move TyOrConstInferVar to rustc_type_ir 2026-08-11 16:24:41 +02:00
bors
0e72e3266c Auto merge of #160879 - JonathanBrouwer:rollup-4zAylRT, r=JonathanBrouwer
Rollup of 7 pull requests

Successful merges:

 - rust-lang/rust#160629 ([Priroda] Add bootstrap test and check steps)
 - rust-lang/rust#160811 (Fix `visible_parent_map` fallback map merging perf regression)
 - rust-lang/rust#154329 (Diagnostics ICE when replaying proof trees with next-solver)
 - rust-lang/rust#157841 (Ensure inferred let pattern types are well-formed)
 - rust-lang/rust#159300 (Implement `to_string()` on `ByteStr` and `ByteString`)
 - rust-lang/rust#160858 (Add regression test for assoc const panic ICE in match)
 - rust-lang/rust#160864 (Rename `HostEffectPredicate` to `HostEffectClause`)
2026-08-11 01:10:47 +00:00
bors
fdda4c6a30 Auto merge of #160801 - nnethercote:new-solver-probes, r=jdonszelmann
Optimize new solver unification table ops

The current code uses the `ena` crate in sub-optimal ways. Improving this gives big speed wins for the new trait solver on some benchmarks. Details in individual commits.

r? @lcnr
2026-08-10 22:02:56 +00:00
Jonathan Brouwer
d3a5cbca18 Rollup merge of #160864 - ada4a:rename-HostEffectPredicate, r=oli-obk
Rename `HostEffectPredicate` to `HostEffectClause`

Part of https://github.com/rust-lang/rust/issues/107250

r? oli-obk
2026-08-10 23:43:33 +02:00
Jonathan Brouwer
ef94a79a3c Rollup merge of #154329 - VicenteGusmao:fix-bug-151304, r=lcnr
Diagnostics ICE when replaying proof trees with next-solver

When diagnostics replay proof tree state, rebuilding a canonical state can fail to match the current inference state. With -Znext-solver=globally, this could panic while reporting an error, avoiding the panic.

Make proof tree replay fallible in diagnostics and fall back to the current obligation when replay fails. Add a regression test for the higher-ranked PartialEq and PartialOrd case. Fixes rust-lang/rust#151304.
2026-08-10 23:43:31 +02:00
Joao Roberto
1f7c5a48e4 Improve canonical response assumptions regression coverage
Keep the original compile-fail reproducer as the ICE guard and add
check-pass coverage for a valid `Trait` implementation while clarifying
the assumptions workaround.
2026-08-10 15:37:21 -03:00
Ada Alakbarova
0bdc067f18 rename HostEffectPredicate to HostEffectClause 2026-08-10 19:50:57 +02:00
Jonathan Brouwer
c773ec0ba1 Rollup merge of #158404 - Dnreikronos:trait_solver/canonicalize_next_gen_regions, r=BoxyUwU,lcnr
trait_solver: normalize next-gen region constraints

fixes rust-lang/rust#157729

-zassumptions-on-binders can produce next-gen region constraints that mean the same thing but don't have the same shape. in this case object candidate merging stayed ambiguous and instance resolution later hit the ice. imo normalizing the constraint at the response boundary is the least weird place for this, because candidate selection shouldn't need to know which vtable looks nicer.

canonicalize and evaluate the next-gen region constraint before response canonicalization, then cover the dyn derived<p> supertrait case from the issue. lgtm locally with the focused test, tests/ui/traits/next-solver, and tests/ui/assumptions_on_binders. idk if there's a better home for the helper call, but ltm this keeps the fix pretty narrow.
2026-08-10 19:01:58 +02:00
Jana Dönszelmann
f3ff14ec35 rename small copy list to small copy set 2026-08-10 11:39:38 +02:00
Chris Denton
4641990929 Remove ensure_sufficient_stack 2026-08-09 19:58:29 +00:00
Nicholas Nethercote
a10854bd85 Optimize another unification table op
In this case we currently have something approximating this:
```
find(vid) != vid
```
which means "is this not a root var?"

This commit changes it to basically this:
```
!try_probe_value(vid).is_some()
```
which is equivalent but doesn't require any parent chasing.
2026-08-09 21:04:32 +10:00
bors
49c80b5a0d Auto merge of #160539 - obi1kenobi:pg/normalizes-to-reuse-ref, r=lcnr
[perf] Reuse existing trait reference instead of recreating it.

Effectively, do one step of common subexpression elimination, manually. We can reuse the existing interned reference made a few lines prior, without needing to recreate it.

r? @lcnr

**AI disclosure:** The optimization opportunity here was discovered as part of a systematic probe for missed optimizations using a combination of both traditional and AI tools. The code here was initially prototyped and vetted by AI tools, followed by additional manual work. I stand behind the quality of the code I'm submitting, and I vouch it's as good or better than if no AI tools were in the loop.
2026-08-08 01:44:34 +00:00
Jonathan Brouwer
88c37cebd6 Rollup merge of #160673 - nnethercote:improve-canonical-param-env-cache, r=lcnr
Improve `canonical_param_env_cache`

This function is messy and has been bothering me. Several cleanups, details in individual commits.

r? @lcnr
2026-08-08 00:38:20 +02:00
Nicholas Nethercote
f231e430bc Streamline canonicalize_param_env
There are two canonicalization steps done by `canonicalize_input` and
`canonicalize_param_env`: `env` (possible cached) and `rest`.

`canonicalize_param_env` does the `env` step. It returns several pieces
of a canonicalizer (either from the cache or by constructing a
canonicalizer) and then `canonicalize_input` uses those parts to
construct a second canonicalizer, which it uses for `rest`.

This commit changes things so that `canonicalize_param_env` does the
`env` part (if necessary) and then returns a canonicalizer that can do
the `rest` part. I find this easier to read. In particular, we no longer
construct an `env` canonicalizer when it's not necessary, we immediately
construct the `rest` canonicalizer.
2026-08-08 05:52:35 +10:00
Nicholas Nethercote
c1e08978b3 Optimize try_evaluate_obligations
This function is very sub-optimal, perf-wise: it takes
`self.obligations.pending` (with `mem::take`) and iterates over the
elements, checking each one. But most of the time no progress is made
and all the obligations get pushed back onto `self.obligations.pending`.
This drain + reconstruct approach is very expensive, mostly because the
new `pending` vec is built by pushing one element at a time, which
requires repeated reallocations. And this vec can have thousands of
elements in it, in extreme cases.

Also, `obligation` and `stalled_on` get passed by value to
`evaluate_root_goal` (`obligation` as `goal`), which then usually passes
the values back in the `GoalEvaluation` which is immediately
deconstructed. This is a lot of wasted value moves.

This commit optimizes things in two ways.

- It prioritizes the hot path. This involves checking in advance if
  there is an inspector (usually not) and adding `goal_remains_stalled`
  which takes `stalled_on` by reference. This hot path avoids all the
  value moves and `GoalEvaluation` construction/deconstruction and gets
  to the very common "nothing needed to be done" outcome as quickly as
  possible.

- It uses `retain_mut` to update `self.obligations.pending`. This
  requires some adjustments (e.g. handling recursion via the
  `overflowed` flag with some cleanup code after the `retain_mut` call,
  and cloning obligations in the error cases).
2026-08-07 19:25:34 +10:00
Nicholas Nethercote
87d95f53a7 Introduce Canonicalizer::new
It avoids some repetition.
2026-08-07 13:25:27 +10:00
Nicholas Nethercote
8ba2b46c78 Update a comment
I now understand what is happening here.
2026-08-07 13:25:27 +10:00
Nicholas Nethercote
93a46b6e96 Improve the canonical param env cache
Currently it is modified with the very clunky
`canonical_param_env_cache_get_or_insert` method, which takes two
closures.

This commit replaces that with `with_canonical_param_env_cache` a
simpler accessor that is very similar to the nearby `with_global_cache`.
This lets `canonicalize_param_env` use normal hash map operations.

The commit also:
- Introduces a dedicated `CanonicalParamEnvCache` newtype.
- Adds a helpful comment to `CanonicalizeParamEnvCacheEntry::param_env`.
2026-08-07 13:25:22 +10:00
Vicente Gusmão
4828030034 Diagnostics ICE when replaying proof trees with next-solver
When diagnostics replay proof tree state, rebuilding a canonical
state can fail to match the current inference state. With
-Znext-solver=globally, this could panic because inference
variables created to replay a canonical state were placed in the
wrong universe relative to placeholders bound by the same state.

Fix this by threading a `prev_universe` through proof tree replay:
`InspectGoal` now stores the caller-side universe at the time the
goal was created, and `instantiate_canonical_state` reuses that same
base universe (instead of recomputing it) when creating any
replay-only fresh variables and when reconstructing placeholders
from the canonical state, ensuring all canonical states for a single
goal share a consistent universe mapping.

Add a regression test for the higher-ranked PartialEq and PartialOrd
case.

Signed-off-by: Vicente Gusmão <vicente.gusmao@tecnico.ulisboa.pt>
2026-08-05 14:48:51 +01:00
Ada Alakbarova
c99698344d rename OutlivesPredicate to OutlivesClause 2026-08-05 11:07:35 +02:00
Predrag Gruevski
8d8e996da3 [perf] Reuse existing trait reference instead of recreating it. 2026-08-04 23:22:36 -04:00
addie.sh
dd17e77729 Next steps for FnDef binder changes (instantiate most FnDef binders) 2026-08-03 13:11:04 -04:00
Jacob Pratt
d4275bd8db Rollup merge of #160254 - adwinwhite:fix-fcw-missing, r=lcnr
Rerun the goal with doubled recursion limit even if the goal has ty vars

Fix the `bevy_render` regression and more in the next solver crater run.

The problem is that we don't rerun the root goal with doubled recursion limit if it contains ty vars.
But we actually need the evaluation response to resolve the ty vars. So the type inference fails.
2026-08-03 00:44:32 -04:00
Adwin White
1489e477b6 rerun even if the goal has ty vars 2026-08-03 11:30:24 +08:00
Jacob Pratt
bf97201f34 Rollup merge of #160162 - nia-e:per-arg-fundamental, r=jackh726
Make `#[fundamental]` only apply to the first argument of `Box`

Per a [discussion with lang](https://rust-lang.zulipchat.com/#narrow/channel/213817-t-lang/topic/.60.23.5Bfundamental.5D.60.20and.20.60Box.3CT.2C.20A.3E.60/with/613236766), it was decided that we want `Box<T, A>` to only be fundamental in `T`. ~~Given that `Box` is the only fundamental type with two generic params, simply make it so only the first param is considered for fundamentalness.~~ ~~`Tuple` is also fundamental, but has its own path in coherence checking and so isn't impacted by this; `Box` is the only thing that is.~~

Since this is just an internal detail and `#[fundamental]` is not in a rush to get stabilised, lang's opinion was that t-compiler has free rein on how to implement this so I figured I'd go with the most straightforward implementation for now. The main alternative I see would be supporting param-position `#[fundamental]` & have the semantics that:
```rust
#[fundamental]
struct Foo<T, U>(T, U);
```
is equivalent to
```rust
struct Foo<#[fundamental] T, #[fundamental] U>(T, U);
```
though given that there's no usecase for this right now, it seemed somewhat unnecessary.

r? compiler
2026-07-31 22:25:13 -04:00
Nia Deckers
4af1e41c24 Make #[fundamental] only apply to the first argument of Box
* fundamental only on first arg
* woo this made error messages nicer
* oh the test was misnamed lol
* special case only box
* rename tests

Co-authored-by: Nia Deckers <nia-e@haecceity.cc>
2026-07-31 15:31:27 +00:00
Joao Roberto
d9f9edc5b0 Add FIXME for opaque placeholder workaround 2026-07-29 09:20:14 -03:00
Jonathan Brouwer
0a1a25a0b6 Rollup merge of #159990 - nnethercote:predicate-to-clause, r=oli-obk
Many "predicate"-to-"clause" renamings

Lots of names weren't changed to account for the introduction of the `Clause` type as a specialized form of `Predicate`, presumably because it was tedious. This commit converts as many of them as I could find. It's mostly very tedious renamings of types, functions, variables, and queries. The more interesting ones are a couple of files (`predicates_of.rs`, `impossible_predicates.rs`) and a MIR pass (`ImpossiblePredicates`).

r? @oli-obk
2026-07-28 21:07:39 +02:00
Nicholas Nethercote
ff161b18b5 Many "predicate"-to-"clause" renamings
Lots of names weren't changed to account for the introduction of the
`Clause` type as a specialized form of `Predicate`, presumably because
it was tedious. This commit converts as many of them as I could find.
It's mostly very tedious renamings of types, functions, variables, and
queries. The more interesting ones are a couple of files
(`predicates_of.rs`, `impossible_predicates.rs`) and a MIR pass
(`ImpossiblePredicates`).
2026-07-28 11:48:45 +10:00
Nicholas Nethercote
94a8720a77 Shrink GoalStalledOn
`PendingObligations` is a `ThinVec` containing a pair
`(PredicateObligation<'tcx>, Option<GoalStalledOn<TyCtxt<'tcx>>>)`. This
pair is currently 136 bytes. This is more than 128 bytes, which means
that LLVM uses (slow) `memcpy` to move the elements.

This commit shrinks `GoalStalledOn` by changing its two `Vec` fields to
`ThinVec`. This shrinks the pair from 136 bytes to 104 bytes, under the
`memcpy` threshold.

The use of `ThinVec` in `GoalStalledOn` forces us to use `ThinVec` in a
number of other places. Some of these required the thin-vec `unstable`
feature for `may_dangle` support.

The commit also adds some size assertions, to prevent backsliding.
2026-07-28 09:23:37 +10:00
Jonathan Brouwer
fac44f9ca4 Rollup merge of #159772 - amirHdev:fix-lower-universe-const, r=lcnr
Fix lowering of resolved const inference variables

Fixes rust-lang/rust#159703
2026-07-27 19:24:47 +02:00
Jonathan Brouwer
ddef7e237e Rollup merge of #159649 - adwinwhite:norm-before-regionck, r=ShoyuVanilla
Normalize region obligations before regionck

We now normalize `TypeOutlives` predicates when evaluating them in the next solver.
So we don't need to normalize in regionck anymore.

r? @ShoyuVanilla
cc @lcnr
2026-07-27 11:58:07 +02:00
Joao Roberto
698320cb95 Track assumptions for canonical response universes
Canonical responses can return query-created placeholders through opaque type constraints. Record empty assumptions when recreating those universes in the caller so eager placeholder handling does not ICE.
2026-07-26 23:01:29 -03:00
bors
dc3f85158a Auto merge of #159224 - adwinwhite:cache-depth-fcw, r=lcnr
add a FCW for overflow errors with the next solver





The old solver doesn't check cache entry's depth requirement when looking up cache while the next solver correctly does so. It's necessary to behave correctly with respect to incremental compilation.
As a result, the next solver is more likely to run into overflow errors.

We try to catch such breakages by rerun the evaluation with doubled recursion limit and if that succeeds we emit a FCW.

This PR is being discussed on [zulip](https://rust-lang.zulipchat.com/#narrow/channel/364551-t-types.2Ftrait-system-refactor/topic/The.20old.20solver.20don.27t.20record.20required.20depth.20on.20cache/with/604756008) 

The lint issue is rust-lang/rust#159228

r? @lcnr
2026-07-26 20:11:32 +00:00
Dnreikronos
6d216c7a19 Normalize eagerly handled region constraints 2026-07-26 13:43:31 -03:00
Dnreikronos
c1ee079aa5 Normalize next-gen region constraints
Canonicalize and evaluate next-gen region constraints before query response canonicalization so equivalent constraints merge structurally.
2026-07-26 13:43:31 -03:00
Jacob Pratt
af9b4f2e15 Rollup merge of #155914 - lcnr:search-graph-bail-on-ambig, r=BoxyUwU
when bailing on ambiguity, don't force other results to ambig

A smaller version of rust-lang/rust#149904 which doesn't cause the perf issue in bevy, or at least in the minimization

While not necessarily necessary for https://github.com/rust-lang/trait-system-refactor-initiative/issues/257 due to rust-lang/rust#158643. This does fix the underlying issues there.

This change does affect `binius_field`, the remaining issues are tracked in https://github.com/rust-lang/trait-system-refactor-initiative/issues/274.

The core idea is that for
- A
  - B
    - A (cycle with initial result)
- B <---

We normally run A until we reach a fixpoint. We don't do so in case trying to do so encounters overflow or the result of `A` ends up ambiguous to avoid performance issues.

We want to generally keep the provisional cache entries which depend on A around. Evaluating these goals depends on the current provisional result of A. This means it is fine to keep them around if A reached a fixpoint. If we bail without reaching a fixpoint, the provisional result used while computing B differs from the final result of A. This means the entry for B is not valid and we'd need to discard it.

Discarding all nested provisional cache entries when not reaching a fixpoint causes perf issues. In case the final result of A is ambiguous, then this PR keeps nested cache entries which are ambiguous and don't have any inference constraints around. That is sound, as having more goals be ambiguous is never an issue, the trait solver can always say "🤷 idk". It also shouldn't cause any incorrect ambiguity errors issues, as changing the provisional result of A to be ambiguity should not change B to go from being ambiguous to something else.

The current implementation mutated the result of all nested provisional cache entries to be ambiguous, which resulted in incorrect ambiguity errors in https://github.com/rust-lang/trait-system-refactor-initiative/issues/257. This PR differs from that by dropping goals whose result isn't already ambiguous. That's means we don't keep quite as many cache entries around, which is potentially worse for perf, but from what I can tell this doens't cause issues in practice.

r? BoxyUwU
2026-07-26 00:21:51 -04:00
Jacob Pratt
a0b15f3bcf Rollup merge of #155388 - lcnr:norm-where-bounds-may-be-productive, r=BoxyUwU
stepping into where-clauses during normalization may be productive

fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/273, see that issue for more info.

Whether stepping into a where-clause is productive depends not on whether we're proving a `NormalizesTo` or `Trait` goal, but instead on how both the impl and the cycle rely on it.

In the example in tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive-2.rs this is just a productive use given the way @Nadrieril and I are thinking about it right now.

We're changing such cycles to be ambiguous for now, so this does not commit us to anything.

This previously caused a lot of breakage when normalizing where-clauses, e.g. https://github.com/rust-lang/trait-system-refactor-initiative/issues/176, however with rust-lang/rust#158643 that is no longer an issue. We will need to figure out what to do here if we want to properly fix `ParamEnv` normalization in the future

r? @BoxyUwU or @nikomatsakis
2026-07-26 00:21:50 -04:00
lcnr
158fdbf013 when bailing on ambiguity, don't force other results to ambig 2026-07-24 10:04:02 +02:00
Jacob Pratt
9da519c2ab Rollup merge of #158362 - Dnreikronos:trait_solver/placeholder_universe_bounds, r=BoxyUwU
trait solver: account for universes from replace_bound_vars

Fixes rust-lang/rust#157840.

The ICE was not really because eager placeholder handling looked at too many universes. Boxy was right: with `-Zassumptions-on-binders`, if the new solver creates a placeholder universe, that universe needs an assumptions entry.

The bad path is `FindParamInClause` entering a binder through `replace_bound_vars`. `BoundVarReplacer` materializes a placeholder universe for the escaping bound vars, but nothing records placeholder assumptions for it. Later eager placeholder handling walks all non-input universes, which imo is the right behavior, and `get_placeholder_assumptions` hits the missing entry.

This moves the empty-assumptions bookkeeping into `EvalCtxt::replace_bound_vars` instead of keeping it local to `FindParamInClause`. The helper snapshots the universe slots before replacement and inserts `Assumptions::empty()` for any slot that got filled.

There is still a FIXME there because idk that empty assumptions is the final shape irl. `replace_bound_vars` does not have the param-env context to compute proper assumptions. But for this PR, imo this is the least weird local fix: it keeps the eager pass looking at all non-input universes and fixes the missing bookkeeping where the universe is created.

The repro is covered by a UI test. It reports the overflow diagnostic instead of ICEing.
2026-07-24 01:59:18 -04:00
Adwin White
203ebf228d rename and disable fcw in next-solver-by-default places 2026-07-24 10:46:18 +08:00
Adwin White
d70e25e904 add FCW for next solver overflow 2026-07-24 10:46:18 +08:00
Amirhossein Akhlaghpour
49a5d6da34 fix: lowering of resolved const inference variables
Signed-off-by: Amirhossein Akhlaghpour <m9.akhlaghpoor@gmail.com>
2026-07-23 16:04:48 +03:30