Rewrite lint_expectations in a single pass.
This PR aims at reducing the perf regression from https://github.com/rust-lang/rust/pull/120924#issuecomment-2202486203 with drive-by simplifications.
Basically, instead of using the lint level builder, which is slow, this PR splits `lint_expectations` logic in 2:
- listing the `LintExpectations` is done in `shallow_lint_levels_on`, on a per-owner basis;
- building the unstable->stable expectation id map is done by iterating on attributes.
r? ghost for perf
Rollup of 11 pull requests
Successful merges:
- #128523 (Add release notes for 1.81.0)
- #129605 (Add missing `needs-llvm-components` directives for run-make tests that need target-specific codegen)
- #129650 (Clean up `library/profiler_builtins/build.rs`)
- #129651 (skip stage 0 target check if `BOOTSTRAP_SKIP_TARGET_SANITY` is set)
- #129684 (Enable Miri to pass pointers through FFI)
- #129762 (Update the `wasm-component-ld` binary dependency)
- #129782 (couple more crash tests)
- #129816 (tidy: say which feature gate has a stability issue mismatch)
- #129818 (make the const-unstable-in-stable error more clear)
- #129824 (Fix code examples buttons not appearing on click on mobile)
- #129826 (library: Fix typo in `core::mem`)
r? `@ghost`
`@rustbot` modify labels: rollup
Enable Miri to pass pointers through FFI
Following https://github.com/rust-lang/rust/pull/126787, the purpose of this PR is to now enable Miri to execute native calls that make use of pointers.
> <details>
>
> <summary> Simple example </summary>
>
> ```rust
> extern "C" {
> fn ptr_printer(ptr: *mut i32);
> }
>
> fn main() {
> let ptr = &mut 42 as *mut i32;
> unsafe {
> ptr_printer(ptr);
> }
> }
> ```
> ```c
> void ptr_printer(int *ptr) {
> printf("printing pointer dereference from C: %d\n", *ptr);
> }
> ```
> should now show `printing pointer dereference from C: 42`.
>
> </details>
Note that this PR does not yet implement any logic involved in updating Miri's "analysis" state (byte initialization, provenance) upon such a native call.
r? ``@RalfJung``
Expand NLL MIR dumps
This PR is a first step to clean up and expand NLL MIR dumps:
- by restoring the "mir-include-spans" comments which are useful for `-Zdump-mir=nll`
- by adding the list of borrows to NLL MIR dumps, where they are introduced in the CFG and in which region
Comments in MIR dumps were turned off in #112346, but as shown in #114652 they were still useful for us working with NLL MIR dumps. So this PR pulls `-Z mir-include-spans` into its own options struct, so that passes dumping MIR can override them if need be. The rest of the compiler is not affected, only the "nll" pass dumps have these comments enabled again. The CLI still has priority when specifying the flag, so that we can explicitly turn them off in the `mir-opt` tests to keep blessed dumps easier to work with (which was one of the points of #112346).
Then, as part of a couple steps to improve NLL/polonius MIR dumps and `.dot` visualizations, I've also added the list of borrows and where they're introduced. I'm doing all this to help debug some polonius scope issues in my prototype location-sensitive analysis :3. I'll probably add member constraints soon.
const fn stability checking: also check declared language features
Fixes https://github.com/rust-lang/rust/issues/129656
`@oli-obk` I assume it is just an oversight that this didn't use `features().declared()`? Or is there a deep reason that this must only check `declared_lib_features`?
Stop using `ty::GenericPredicates` for non-predicates_of queries
`GenericPredicates` is a struct of several parts: A list of of an item's own predicates, and a parent def id (and some effects related stuff, but ignore that since it's kinda irrelevant). When instantiating these generic predicates, it calls `predicates_of` on the parent and instantiates its predicates, and appends the item's own instantiated predicates too:
acb4e8b625/compiler/rustc_middle/src/ty/generics.rs (L407-L413)
Notice how this should result in a recursive set of calls to `predicates_of`... However, `GenericPredicates` is *also* misused by a bunch of *other* queries as a convenient way of passing around a list of predicates. For these queries, we don't ever set the parent def id of the `GenericPredicates`, but if we did, then this would be very easy to mistakenly call `predicates_of` instead of some other intended parent query.
Given that footgun, and the fact that we don't ever even *use* the parent def id in the `GenericPredicates` returned from queries like `explicit_super_predicates_of`, It really has no benefit over just returning `&'tcx [(Clause<'tcx>, Span)]`.
This PR additionally opts to wrap the results of `EarlyBinder`, as we've tended to use that in the return type of these kinds of queries to properly convey that the user has params to deal with, and it also gives a convenient way of iterating over a slice of things after instantiating.
We want to allow setting this on the CLI, override it only in MIR
passes, and disable it altogether in mir-opt tests.
The default value is "only for NLL MIR dumps", which is considered off
for all intents and purposes, except for `rustc_borrowck` when an NLL
MIR dump is requested.
Implement a first version of RFC 3525: struct target features
This PR is an attempt at implementing https://github.com/rust-lang/rfcs/pull/3525, behind a feature gate `struct_target_features`.
There's obviously a few tasks that ought to be done before this is merged; in no particular order:
- add proper error messages
- add tests
- create a tracking issue for the RFC
- properly serialize/deserialize the new target_features field in `rmeta` (assuming I even understood that correctly :-))
That said, as I am definitely not a `rustc` expert, I'd like to get some early feedback on the overall approach before fixing those things (and perhaps some pointers for `rmeta`...), hence this early PR :-)
Here's an example piece of code that I have been using for testing - with the new code, the calls to intrinsics get correctly inlined:
```rust
#![feature(struct_target_features)]
use std::arch::x86_64::*;
/*
// fails to compile
#[target_feature(enable = "avx")]
struct Invalid(u32);
*/
#[target_feature(enable = "avx")]
struct Avx {}
#[target_feature(enable = "sse")]
struct Sse();
/*
// fails to compile
extern "C" fn bad_fun(_: Avx) {}
*/
/*
// fails to compile
#[inline(always)]
fn inline_fun(_: Avx) {}
*/
trait Simd {
fn do_something(&self);
}
impl Simd for Avx {
fn do_something(&self) {
unsafe {
println!("{:?}", _mm256_setzero_ps());
}
}
}
impl Simd for Sse {
fn do_something(&self) {
unsafe {
println!("{:?}", _mm_setzero_ps());
}
}
}
struct WithAvx {
#[allow(dead_code)]
avx: Avx,
}
impl Simd for WithAvx {
fn do_something(&self) {
unsafe {
println!("{:?}", _mm256_setzero_ps());
}
}
}
#[inline(never)]
fn dosomething<S: Simd>(simd: &S) {
simd.do_something();
}
fn main() {
/*
// fails to compile
Avx {};
*/
if is_x86_feature_detected!("avx") {
let avx = unsafe { Avx {} };
dosomething(&avx);
dosomething(&WithAvx { avx });
}
if is_x86_feature_detected!("sse") {
dosomething(&unsafe { Sse {} })
}
}
```
Tracking:
- https://github.com/rust-lang/rust/issues/129107
LLVM uses the word "code" to refer to a particular kind of coverage mapping.
This unrelated usage of the word is confusing, and makes it harder to introduce
types whose names correspond to the LLVM classification of coverage kinds.
Get rid of `predicates_defined_on`
This is the uncontroversial part of #129532. This simply inlines the `predicates_defined_on` into into `predicates_of`. Nothing should change here logically.
Stop storing a special inner body for the coroutine by-move body for async closures
...and instead, just synthesize an item which is treated mostly normally by the MIR pipeline.
This PR does a few things:
* We synthesize a new `DefId` for the by-move body of a closure, which has its `mir_built` fed with the output of the `ByMoveBody` MIR transformation, and some other relevant queries.
* This has the `DefKind::ByMoveBody`, which we use to distinguish it from "real" bodies (that come from HIR) which need to be borrowck'd. Introduce `TyCtxt::is_synthetic_mir` to skip over `mir_borrowck` which is called by `mir_promoted`; borrowck isn't really possible to make work ATM since it heavily relies being called on a body generated from HIR, and is redundant by the construction of the by-move-body.
* Remove the special `PassManager` hacks for handling the inner `by_move_body` stored within the coroutine's mir body. Instead, this body is fed like a regular MIR body, so it's goes through all of the `tcx.*_mir` stages normally (build -> promoted -> ...etc... -> optimized) ✨.
* Remove the `InstanceKind::ByMoveBody` shim, since now we have a "regular" def id, we can just use `InstanceKind::Item`. This also allows us to remove the corresponding hacks from codegen, such as in `fn_sig_for_fn_abi` ✨.
Notable remarks:
* ~~I know it's kind of weird to be using `DefKind::Closure` here, since it's not a distinct closure but just a new MIR body. I don't believe it really matters, but I could also use a different `DefKind`... maybe one that we could use for synthetic MIR bodies in general?~~ edit: We're doing this now.
Detect `*` operator on `!Sized` expression
The suggestion is new:
```
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> $DIR/unsized-str-in-return-expr-arg-and-local.rs:15:9
|
LL | let x = *"";
| ^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `str`
= note: all local variables must have a statically known size
= help: unsized locals are gated as an unstable feature
help: references to `!Sized` types like `&str` are `Sized`; consider not dereferencing the expression
|
LL - let x = *"";
LL + let x = "";
|
```
Fix#128199.
Retroactively feature gate `ConstArgKind::Path`
This puts the lowering introduced by #125915 under a feature gate until we fix the regressions introduced by it. Alternative to whole sale reverting the PR since it didn't seem like a very clean revert and I think this is generally a step in the right direction and don't want to get stuck landing and reverting the PR over and over :)
cc #129137 ``@camelid,`` tests taken from there. beta is branching soon so I think it makes sense to not try and rush that fix through since it wont have much time to bake and if it has issues we can't simply revert it on beta.
Fixes#128016
Pretty-print own args of existential projections (dyn-Trait w/ GAT constraints)
Previously we would just drop them. This bug isn't that significant as it can only be triggered by user code that constrains GATs inside trait object types which is currently gated under the interim feature `generic_associated_types_extended` (whose future is questionable) or on stable if the GATs are 'disabled' in dyn-Trait via `where Self: Sized` (in which case the assoc type bindings get ignored anyway (and trigger the warn-by-default lint `unused_associated_type_bounds`)), so yeah.
Affects diagnostic output and output of `std::any::type_name{_of_val}`.
Use `bool` in favor of `Option<()>` for diagnostics
We originally only supported `Option<()>` for optional notes/labels, but we now support `bool`. Let's use that, since it usually leads to more readable code.
I'm not removing the support from the derive macro, though I guess we could error on it... 🤔
Added "copy" to Debug fmt for copy operands
In MIR's debug mode (--emit mir) the printing for Operands is slightly inconsistent.
The RValues - values on the right side of an Assign - are usually printed with their Operand when they are Places.
Example:
_2 = move _3
But for arguments, the operand is omitted.
_2 = _1
I propose a change be made, to display the place with the operand.
_2 = copy _1
Move and copy have different semantics, meaning this difference is important and helpful to the user. It also adds consistency to the pretty printing.
-- EDIT --
Consider this example Rust program and its MIR output with the **updated pretty printer.**
This was generated with the arguments --emit mir --crate-type lib -Zmir-opt-level=0 (Otherwise, it's optimised away since it's a junk program).
```rust
fn main(foo: i32) {
let v = 10;
if v == 20 {
foo;
}
else {
v;
}
}
```
```MIR
// WARNING: This output format is intended for human consumers only
// and is subject to change without notice. Knock yourself out.
fn main(_1: i32) -> () {
debug foo => _1;
let mut _0: ();
let _2: i32;
let mut _3: bool;
let mut _4: i32;
let _5: i32;
let _6: i32;
scope 1 {
debug v => _2;
}
bb0: {
StorageLive(_2);
_2 = const 10_i32;
StorageLive(_3);
StorageLive(_4);
_4 = copy _2;
_3 = Eq(move _4, const 20_i32);
switchInt(move _3) -> [0: bb2, otherwise: bb1];
}
bb1: {
StorageDead(_4);
StorageLive(_5);
_5 = copy _1;
StorageDead(_5);
_0 = const ();
goto -> bb3;
}
bb2: {
StorageDead(_4);
StorageLive(_6);
_6 = copy _2;
StorageDead(_6);
_0 = const ();
goto -> bb3;
}
bb3: {
StorageDead(_3);
StorageDead(_2);
return;
}
}
```
In this example program, we can see that when we move a place, it is preceded by "move". e.g. ``` _3 = Eq(move _4, const 20_i32);```. However, when we copy a place such as ```_5 = _1;```, it is not preceded by the operand in the original printout. I propose to change the print to include the copy ```_5 = copy _1``` as in this example.
Regarding the arguments part. When I originally submitted this PR, I was under the impression this only affected the print for arguments to a function, but actually, it affects anything that uses a copy. This is preferable anyway with regard to consistency. The PR is about making ```copy``` explicit.
Use cnum for extern crate data key
Noticed this when fixing #129184. I still have yet to put up a fix for that (mostly because I'm too lazy to minimize a test, that will come soon though).
Use `FnSig` instead of raw `FnDecl` for `ForeignItemKind::Fn`, fix ICE for `Fn` trait error on safe foreign fn
Let's use `hir::FnSig` instead of `hir::FnDecl + hir::Safety` for `ForeignItemKind::Fn`. This consolidates some handling code between normal fns and foreign fns.
Separetly, fix an ICE where we weren't handling `Fn` trait errors for safe foreign fns.
If perf is bad for the first commit, I can rework the ICE fix to not rely on it. But if perf is good, I prefer we fix and clean up things all at once 👍
r? spastorino
Fixes#128764
Return correct HirId when finding body owner in diagnostics
Fixes#129145Fixes#128810
r? ```@compiler-errors```
```rust
fn generic<const N: u32>() {}
trait Collate<const A: u32> {
type Pass;
fn collate(self) -> Self::Pass;
}
impl<const B: u32> Collate<B> for i32 {
type Pass = ();
fn collate(self) -> Self::Pass {
generic::<{ true }>()
//~^ ERROR: mismatched types
}
}
```
When type checking the `{ true }` anon const we would error with a type mismatch. This then results in diagnostics code attempting to check whether its due to a type mismatch with the return type. That logic was implemented by walking up the hir until we reached the body owner, except instead of using the `enclosing_body_owner` function it special cased various hir nodes incorrectly resulting in us walking out of the anon const and stopping at `fn collate` instead.
This then resulted in diagnostics logic inside of the anon consts `ParamEnv` attempting to do trait solving involving the `<i32 as Collate<B>>::Pass` type which ICEs because it is in the wrong environment.
I have rewritten this function to just walk up until it hits the `enclosing_body_owner` and made some other changes since I found this pretty hard to read/understand. Hopefully it's easier to understand now, it also makes it more obvious that this is not implemented in a very principled way and is definitely missing cases :)
mir/pretty: use `Option` instead of `Either<Once, Empty>`
`Either` is wasteful for a one-or-none iterator, especially since `Once`
is already an `option::IntoIter` internally. We don't really need any of
the iterator mechanisms in this case, just a single conditional insert.
`Either` is wasteful for a one-or-none iterator, especially since `Once`
is already an `option::IntoIter` internally. We don't really need any of
the iterator mechanisms in this case, just a single conditional insert.
Special-case alias ty during the delayed bug emission in `try_from_lit`
This PR tries to fix#116308.
A delayed bug in `try_from_lit` will not be emitted so that the compiler will not ICE when it sees the pair `(ast::LitKind::Int, ty::TyKind::Alias)` in `lit_to_const` (called from `try_from_lit`).
This PR is related to an unstable feature `adt_const_params` (#95174).
r? ``@BoxyUwU``
`-Znext-solver` caching
This PR has two major changes while also fixing multiple issues found via fuzzing.
The main optimization is the ability to not discard provisional cache entries when popping the highest cycle head the entry depends on. This fixes the hang in Fuchsia with `-Znext-solver=coherence`.
It also bails if the result of a fixpoint iteration is ambiguous, even without reaching a fixpoint. This is necessary to avoid exponential blowup if a coinductive cycle results in ambiguity, e.g. due to unknowable candidates in coherence.
Updating stack entries pretty much exclusively happens lazily now, so `fn check_invariants` ended up being mostly useless and I've removed it. See https://gist.github.com/lcnr/8de338fdb2685581e17727bbfab0622a for the invariants we would be able to assert with it.
For a general overview, see the in-process update of the relevant rustc-dev-guide chapter: https://hackmd.io/1ALkSjKlSCyQG-dVb_PUHw
r? ```@compiler-errors```
Shrink `TyKind::FnPtr`.
By splitting the `FnSig` within `TyKind::FnPtr` into `FnSigTys` and `FnHeader`, which can be packed more efficiently. This reduces the size of the hot `TyKind` type from 32 bytes to 24 bytes on 64-bit platforms. This reduces peak memory usage by a few percent on some benchmarks. It also reduces cache misses and page faults similarly, though this doesn't translate to clear cycles or wall-time improvements on CI.
r? `@compiler-errors`
miri: make vtable addresses not globally unique
Miri currently gives vtables a unique global address. That's not actually matching reality though. So this PR enables Miri to generate different addresses for the same type-trait pair.
To avoid generating an unbounded number of `AllocId` (and consuming unbounded amounts of memory), we use the "salt" technique that we also already use for giving constants non-unique addresses: the cache is keyed on a "salt" value n top of the actually relevant key, and Miri picks a random salt (currently in the range `0..16`) each time it needs to choose an `AllocId` for one of these globals -- that means we'll get up to 16 different addresses for each vtable. The salt scheme is integrated into the global allocation deduplication logic in `tcx`, and also used for functions and string literals. (So this also fixes the problem that casting the same function to a fn ptr over and over will consume unbounded memory.)
r? `@saethlin`
Fixes https://github.com/rust-lang/miri/issues/3737
Store `do_not_recommend`-ness in impl header
Alternative to #128674
It's less flexible, but also less invasive. Hopefully it's also performant. I'd recommend we think separately about the design for how to gate arbitrary diagnostic attributes moving forward.
Normalize struct tail properly for `dyn` ptr-to-ptr casting in new solver
Realized that the new solver didn't handle ptr-to-ptr casting correctly.
r? lcnr
Built on #128694
doing so requires overwriting global cache entries and
generally adds significant complexity to the solver. This is
also only ever done for root goals, so it feels easier to wrap
the `evaluate_canonical_goal` in an ordinary query if
necessary.
Differentiate between methods and associated functions in diagnostics
Accurately refer to assoc fn without receiver as assoc fn instead of methods. Add `AssocItem::descr` method to centralize where we call methods and associated functions.
Stabilize `min_exhaustive_patterns`
## Stabilisation report
I propose we stabilize the [`min_exhaustive_patterns`](https://github.com/rust-lang/rust/issues/119612) language feature.
With this feature, patterns of empty types are considered unreachable when matched by-value. This allows:
```rust
enum Void {}
fn foo() -> Result<u32, Void>;
fn main() {
let Ok(x) = foo();
// also
match foo() {
Ok(x) => ...,
}
}
```
This is a subset of the long-unstable [`exhaustive_patterns`](https://github.com/rust-lang/rust/issues/51085) feature. That feature is blocked because omitting empty patterns is tricky when *not* matched by-value. This PR stabilizes the by-value case, which is not tricky.
The not-by-value cases (behind references, pointers, and unions) stay as they are today, e.g.
```rust
enum Void {}
fn foo() -> Result<u32, &Void>;
fn main() {
let Ok(x) = foo(); // ERROR: missing `Err(_)`
}
```
The consequence on existing code is some extra "unreachable pattern" warnings. This is fully backwards-compatible.
### Comparison with today's rust
This proposal only affects match checking of empty types (i.e. types with no valid values). Non-empty types behave the same with or without this feature. Note that everything below is phrased in terms of `match` but applies equallly to `if let` and other pattern-matching expressions.
To be precise, a visibly empty type is:
- an enum with no variants;
- the never type `!`;
- a struct with a *visible* field of a visibly empty type (and no #[non_exhaustive] annotation);
- a tuple where one of the types is visibly empty;
- en enum with all variants visibly empty (and no `#[non_exhaustive]` annotation);
- a `[T; N]` with `N != 0` and `T` visibly empty;
- all other types are nonempty.
(An extra change was proposed below: that we ignore #[non_exhaustive] for structs since adding fields cannot turn an empty struct into a non-empty one)
For normal types, exhaustiveness checking requires that we list all variants (or use a wildcard). For empty types it's more subtle: in some cases we require a `_` pattern even though there are no valid values that can match it. This is where the difference lies regarding this feature.
#### Today's rust
Under today's rust, a `_` is required for all empty types, except specifically: if the matched expression is of type `!` (the never type) or `EmptyEnum` (where `EmptyEnum` is an enum with no variants), then the `_` is not required.
```rust
let foo: Result<u32, !> = ...;
match foo {
Ok(x) => ...,
Err(_) => ..., // required
}
let foo: Result<u32, &!> = ...;
match foo {
Ok(x) => ...,
Err(_) => ..., // required
}
let foo: &! = ...;
match foo {
_ => ..., // required
}
fn blah(foo: (u32, !)) {
match foo {
_ => ..., // required
}
}
unsafe {
let ptr: *const ! = ...;
match *ptr {} // allowed
let ptr: *const (u32, !) = ...;
match *ptr {
(x, _) => { ... } // required
}
let ptr: *const Result<u32, !> = ...;
match *ptr {
Ok(x) => { ... }
Err(_) => { ... } // required
}
}
```
#### After this PR
After this PR, a pattern of an empty type can be omitted if (and only if):
- the match scrutinee expression has type `!` or `EmptyEnum` (like before);
- *or* the empty type is matched by value (that's the new behavior).
In all other cases, a `_` is required to match on an empty type.
```rust
let foo: Result<u32, !> = ...;
match foo {
Ok(x) => ..., // `Err` not required
}
let foo: Result<u32, &!> = ...;
match foo {
Ok(x) => ...,
Err(_) => ..., // required because `!` is under a dereference
}
let foo: &! = ...;
match foo {
_ => ..., // required because `!` is under a dereference
}
fn blah(foo: (u32, !)) {
match foo {} // allowed
}
unsafe {
let ptr: *const ! = ...;
match *ptr {} // allowed
let ptr: *const (u32, !) = ...;
match *ptr {
(x, _) => { ... } // required because the matched place is under a (pointer) dereference
}
let ptr: *const Result<u32, !> = ...;
match *ptr {
Ok(x) => { ... }
Err(_) => { ... } // required because the matched place is under a (pointer) dereference
}
}
```
### Documentation
The reference does not say anything specific about exhaustiveness checking, hence there is nothing to update there. The nomicon does, I opened https://github.com/rust-lang/nomicon/pull/445 to reflect the changes.
### Tests
The relevant tests are in `tests/ui/pattern/usefulness/empty-types.rs`.
### Unresolved Questions
None that I know of.
try-job: dist-aarch64-apple
Cache supertrait outlives of impl header for soundness check
This caches the results of computing the transitive supertraits of an impl and filtering it to its outlives obligations. This is purely an optimization to improve https://github.com/rust-lang/rust/pull/124336.
Stop unnecessarily taking GenericPredicates by `&self`
This results in overcapturing in edition 2024, and is unnecessary since `GenericPredicates: Copy`.
Accurately refer to assoc fn without receiver as assoc fn instead of methods.
Add `AssocItem::descr` method to centralize where we call methods and associated functions.
Miscellaneous improvements to struct tail normalization
1. Make checks for foreign tails more accurate by normalizing the struct tail. I didn't write a test for this one.
2. Normalize when computing struct tail for `offset_of` for slice/str. This fixes the new solver only.
3. Normalizing when computing tails for disaligned reference check. This fixes both solvers.
r? lcnr
By splitting the `FnSig` within `TyKind::FnPtr` into `FnSigTys` and
`FnHeader`, which can be packed more efficiently. This reduces the size
of the hot `TyKind` type from 32 bytes to 24 bytes on 64-bit platforms.
This reduces peak memory usage by a few percent on some benchmarks. It
also reduces cache misses and page faults similarly, though this doesn't
translate to clear cycles or wall-time improvements on CI.
```
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> $DIR/unsized-str-in-return-expr-arg-and-local.rs:15:9
|
LL | let x = *"";
| ^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `str`
= note: all local variables must have a statically known size
= help: unsized locals are gated as an unstable feature
help: references are always `Sized`, even if they point to unsized data; consider not dereferencing the expression
|
LL - let x = *"";
LL + let x = "";
|
```