Recurse into APITs in `impl_trait_overcaptures`
We were previously not detecting cases where an RPIT was located in the return type of an async function, leading to underfiring of the `impl_trait_overcaptures`. This PR does this recursion properly now.
cc https://github.com/rust-lang/rust/issues/132809
Separate `RemoveLet` span into primary span for `let` and removal
suggestion span for `let `, so that primary span does not include
whitespace.
Fixes: #133031
Signed-off-by: Tyrone Wu <wudevelops@gmail.com>
check_consts: fix error requesting feature gate when that gate is not actually needed
When working on https://github.com/rust-lang/hashbrown/pull/586 I noticed that the compiler asks for the `rustc_private` feature to be enabled if one forgets to set `rustc_const_stable_indirect` on a function -- but enabling `rustc_private` would not actually help. This fixes the diagnostics.
r? `@compiler-errors`
Over in Zed we've noticed that loading crates for a large-ish workspace can take almost 200ms. We've pinned it down to how rustc searches for paths, as it performs a linear search over the list of candidate paths. In our case the candidate list had about 20k entries which we had to iterate over for each dependency being loaded.
This commit introduces a simple FilesIndex that's just a sorted Vec under the hood. Since crates are looked up by both prefix and suffix, we perform a range search on said Vec (which constraints the search space based on prefix) and follow up with a linear scan of entries with matching suffixes.
FilesIndex is also pre-filtered before any queries are performed using available target information; query prefixes/sufixes are based on the target we are compiling for, so we can remove entries that can never match up front.
Overall, this commit brings down build time for us in dev scenarios by about 6%.
100ms might not seem like much, but this is a constant cost that each of our workspace crates has to pay, even when said crate is miniscule.
Rollup of 8 pull requests
Successful merges:
- #132790 (Add as_slice/into_slice for IoSlice/IoSliceMut.)
- #132905 ([AIX] Add crate "unwind" to link with libunwind)
- #132977 (Fix compilation error on Solaris due to flock usage)
- #132984 ([illumos] use pipe2 to create anonymous pipes)
- #133019 (docs: Fix missing period and colon in methods for primitive types)
- #133048 (use `&raw` in `{read, write}_unaligned` documentation)
- #133050 (Always inline functions signatures containing `f16` or `f128`)
- #133053 (tests: Fix the SIMD FFI tests with certain x86 configuration)
r? `@ghost`
`@rustbot` modify labels: rollup
Always inline functions signatures containing `f16` or `f128`
There are a handful of tier 2 and tier 3 targets that cause a LLVM crash or linker error when generating code that contains `f16` or `f128`. The cranelift backend also does not support these types. To work around this, every function in `std` or `core` that contains these types must be marked `#[inline]` in order to avoid sending any code to the backend unless specifically requested.
However, this is inconvenient and easy to forget. Introduce a check for these types in the frontend that automatically inlines any function signatures that take or return `f16` or `f128`.
Note that this is not a perfect fix because it does not account for the types being passed by reference or as members of aggregate types, but this is sufficient for what is currently needed in the standard library.
Fixes: https://github.com/rust-lang/rust/issues/133035
Closes: https://github.com/rust-lang/rust/pull/133037
There are a handful of tier 2 and tier 3 targets that cause a LLVM crash
or linker error when generating code that contains `f16` or `f128`. The
cranelift backend also does not support these types. To work around
this, every function in `std` or `core` that contains these types must
be marked `#[inline]` in order to avoid sending any code to the backend
unless specifically requested.
However, this is inconvenient and easy to forget. Introduce a check for
these types in the frontend that automatically inlines any function
signatures that take or return `f16` or `f128`.
Note that this is not a perfect fix because it does not account for the
types being passed by reference or as members of aggregate types, but
this is sufficient for what is currently needed in the standard library.
Fixes: https://github.com/rust-lang/rust/issues/133035
Closes: https://github.com/rust-lang/rust/pull/133037
Skip locking span interner for some syntax context checks
- `from_expansion` now never needs to consult the interner
- `eq_ctxt` now only needs the interner when both spans are fully interned
borrowck diagnostics: suggest borrowing function inputs in generic positions
# Summary
This generalizes borrowck's existing suggestions to borrow instead of moving when passing by-value to a function that's generic in that input. Previously, this was special-cased to `AsRef`/`Borrow`-like traits and `Fn`-like traits. This PR changes it to test if, for a moved place with type `T`, that the callee's signature and clauses don't break if you substitute in `&T` or `&mut T`. For instance, it now works with `Read`/`Write`-like traits.
Fixes https://github.com/rust-lang/rust/issues/131413
# Incidental changes
- No longer spuriously suggests mutable borrows of closures in some situations (see e.g. the tests in [tests/ui/closures/2229_closure_analysis/](https://github.com/rust-lang/rust/compare/master...dianne:rust:suggest-borrow-generic?expand=1#diff-8dfb200c559f0995d0f2ffa2f23bc6f8041b263e264e5c329a1f4171769787c0)).
- No longer suggests cloning closures that implement `Fn`, since they can be borrowed (see e.g. [tests/ui/moves/borrow-closures-instead-of-move.stderr](https://github.com/rust-lang/rust/compare/master...dianne:rust:suggest-borrow-generic?expand=1#diff-5db268aac405eec56d099a72d8b58ac46dab523cf013e29008104840168577fb)).
This keeps the behavior to suppress suggestions of `fn_once.clone()()`. I think it might make sense to suggest it with a "but this might not be your desired behavior" caveat, as is done when something is used after being consumed as the receiver for a method call. That's probably out of the scope of this PR though.
# Limitations and possible improvements
- This doesn't work for receivers of method calls. This is a small change, and I have it implemented locally, but I'm not sure it's useful on its own. In most cases I've found borrowing the receiver would change the call's output type (see below). In other cases (e.g. `Iterator::sum`), borrowing the receiver isn't useful since it's consumed.
- This doesn't work when it would change the call's output type. In general, I figure inserting references into the output type is an unwanted change. However, this also means it doesn't work in cases where the new output type would be effectively the same as the old one. For example, from the rand crate, the iterator returned by [`Rng::sample_iter`](https://docs.rs/rand/latest/rand/trait.Rng.html#method.sample_iter) is effectively the same (modulo regions) whether you borrow or consume the receiver `Rng`, so common usage involves borrowing it. I'm not sure whether the best approach is to add a more complex check of approximate equivalence, to forego checking the call's output type and give spurious suggestions, or to leave it as-is.
- This doesn't work when it would change the call's other input types. Instead, it could suggest borrowing any others that have the same parameter type (but only when suggesting shared borrows). I think this would be a pretty easy change, but I don't think it's very useful so long as the normalized output type can't change.
I'm happy to implement any of these (or other potential improvements to this), but I'm not sure which are common enough patterns to justify the added complexity. Please let me know if any sound worthwhile.
PassWrapper: disable UseOdrIndicator for Asan Win32
As described in https://reviews.llvm.org/D137227 UseOdrIndicator should be disabled on Windows since link.exe does not support duplicate weak definitions.
Fixes https://github.com/rust-lang/rust/issues/124390.
Credits also belong to `@1c3t3a` who worked with me on this.
We are currently testing this on a Windows machine.
Handle infer vars in anon consts on stable
Fixes#132955
Diagnostics will sometimes try to replace generic parameters with inference variables in failing goals. This means that if we have some failing goal with an array repeat expr count anon const in it, we will wind up with some `ty::ConstKind::Unevaluated(anon_const_def, [?x])` during diagnostics which will then ICE if we do not handle inference variables correctly on stable when normalizing type system consts.
r? ```@compiler-errors```
This subsumes the suggestions to borrow arguments with `AsRef`/`Borrow` bounds and those to borrow
arguments with `Fn` and `FnMut` bounds. It works for other traits implemented on references as well,
such as `std::io::Read`, `std::io::Write`, and `core::fmt::Write`.
Incidentally, by making the logic for suggesting borrowing closures general, this removes some
spurious suggestions to mutably borrow `FnMut` closures in assignments, as well as an unhelpful
suggestion to add a `Clone` constraint to an `impl Fn` argument.
Important: we know from the `parse_annotatable_with` call above the call
site that only some of the `Annotatable` variants are possible. The
remaining cases can be replaced with `unreachable!`.
They each have a single callsite, and the result is always unwrapped, so
the `Option<Annotatable>` return type is misleading.
Also, the comment at the `configure_annotatable` call site is wrong,
talking about a result vector, so this commit also removes that.
It was added in #115367 for anonymous ADTs. Those changes were then
reverted in #131045, but `empty_disambiguator` was left behind, perhaps
by mistake. It seems to be unnecessary.
This is setup for unifing the logic for suggestions to borrow arguments in generic positions.
As of this commit, it's still special cases for `AsRef`/`Borrow`-like traits and `Fn`-like traits.
This also downgrades its applicability to MaybeIncorrect. Its suggestion can result in ill-typed
code when the type parameter it suggests providing a different generic argument for appears
elsewhere in the callee's signature or predicates.
`resolve_ident_in_module` is a very thin wrapper around
`resolve_ident_in_module_ext`, and `resolve_ident_in_module_unadjusted`
is a very thin wrapper around `resolve_ident_in_module_unadjusted_ext`.
The wrappers make the call sites slightly more concise, but I don't
think that's worth the extra code and indirection.
This commit removes the two wrappers and removes the `_ext` suffixes
from the inner methods.
As described here UseOdrIndicator should be disabled on Windows
since link.exe does not support duplicate weak definitions
(https://reviews.llvm.org/D137227).
Co-Authored-By: Bastian Kersting <bkersting@google.com>
CFI: Append debug location to CFI blocks
Currently we're not appending debug locations to the inserted CFI blocks. This shows up in #132615 and #100783. This change fixes that by passing down the debug location to the CFI type-test generation and appending it to the blocks.
Credits also belong to `@jakos-sec` who worked with me on this.
`to_lowercase` allocates, but `eq_ignore_ascii_case` doesn't. This path
is hot enough that this makes a small but noticeable difference in
benchmarking.
clarify `must_produce_diag` ICE for debugging
We have a sanity check to ensure the expensive `trimmed_def_paths` functions are called only when producing diagnostics, and not e.g. on the happy path. The panic often happens IME during development because of randomly printing stuff, causing an ICE if no diagnostics were also emitted.
I have this change locally but figured it could be useful to others, so this PR clarifies the message when this happens during development.
The output currently looks like this by default; it's a bit confusing with words missing:
```
thread 'rustc' panicked at compiler/rustc_errors/src/lib.rs:628:17:
must_produce_diag: `trimmed_def_paths` called but no diagnostics emitted; `with_no_trimmed_paths` for debugging. called at: disabled backtrace
stack backtrace:
0: 0x7ffff79570f6 - std::backtrace_rs::backtrace::libunwind::trace::h33576c57327a3cea
at .../library/std/src/../../backtrace/src/backtrace/libunwind.rs:116:5
1: 0x7ffff79570f6 - std::backtrace_rs::backtrace::trace_unsynchronized::h7972a09393b420db
at .../library/std/src/../../backtrace/src/backtrace/mod.rs:66:5
2: 0x7ffff79570f6 - std::sys::backtrace::_print_fmt::hae8c5bbfbf7a8322
at .../library/std/src/sys/backtrace.rs:66:9
3: 0x7ffff79570f6 - <std::sys::backtrace::BacktraceLock::print::DisplayBacktrace as core::fmt::Display>::fmt::h1fd6a7a210f5b535
...
```
The new output mentions how to get more information and locate where the `with_no_trimmed_paths` call needs to be added.
1. By default, backtraces are disabled:
```
thread 'rustc' panicked at compiler/rustc_errors/src/lib.rs:642:17:
`trimmed_def_paths` called, diagnostics were expected but none were emitted. Use `with_no_trimmed_paths` for debugging. Backtraces are currently disabled: set `RUST_BACKTRACE=1` and re-run to see where it happened.
stack backtrace:
0: 0x7ffff79565f6 - std::backtrace_rs::backtrace::libunwind::trace::h33576c57327a3cea
...
```
2. With backtraces enabled:
```
thread 'rustc' panicked at compiler/rustc_errors/src/lib.rs:642:17:
`trimmed_def_paths` called, diagnostics were expected but none were emitted. Use `with_no_trimmed_paths` for debugging. This happened in the following `must_produce_diag` call's backtrace:
0: <rustc_errors::DiagCtxtHandle>::set_must_produce_diag
at .../compiler/rustc_errors/src/lib.rs:1133:58
1: <rustc_session::session::Session>::record_trimmed_def_paths
at .../compiler/rustc_session/src/session.rs:327:9
2: rustc_middle::ty::print::pretty::trimmed_def_paths
at .../compiler/rustc_middle/src/ty/print/pretty.rs:3351:5
...
```
A `\n` could be added here or there, but it didn't matter much whenever I hit this case with the new message.
Make precise capturing suggestion machine-applicable only if it has no APITs
cc https://github.com/rust-lang/rust/issues/132932
The only case where this suggestion is not machine-applicable is when we suggest turning arg-position impl trait into type parameters, which may expose type parameters that were not turbofishable before.
Proper support for cross-crate recursive const stability checks
~~Stacked on top of https://github.com/rust-lang/rust/pull/132492; only the last three commits are new.~~
In a crate without `staged_api` but with `-Zforce-unstable-if-unmarked`, we now subject all functions marked with `#[rustc_const_stable_indirect]` to recursive const stability checks. We require an opt-in so that by default, a crate can be built with `-Zforce-unstable-if-unmarked` and use nightly features as usual. This property is recorded in the crate metadata so when a `staged_api` crate calls such a function, it sees the `#[rustc_const_stable_indirect]` and allows it to be exposed on stable. This, finally, will let us expose `const fn` from hashbrown on stable.
The second commit makes const stability more like regular stability: via `check_missing_const_stability`, we ensure that all publicly reachable functions have a const stability attribute -- both in `staged_api` crates and `-Zforce-unstable-if-unmarked` crates. To achieve this, we move around the stability computation so that const stability is computed after regular stability is done. This lets us access the final result of the regular stability computation, which we use so that `const fn` can inherit the regular stability (but only if that is "unstable"). Fortunately, this lets us get rid of an `Option` in `ConstStability`.
This is the last PR that I have planned in this series.
r? `@compiler-errors`
Delete the `cfg(not(parallel))` serial compiler
Since it's inception a long time ago, the parallel compiler and its cfgs have been a maintenance burden. This was a necessary evil the allow iteration while not degrading performance because of synchronization overhead.
But this time is over. Thanks to the amazing work by the parallel working group (and the dyn sync crimes), the parallel compiler has now been fast enough to be shipped by default in nightly for quite a while now.
Stable and beta have still been on the serial compiler, because they can't use `-Zthreads` anyways.
But this is quite suboptimal:
- the maintenance burden still sucks
- we're not testing the serial compiler in nightly
Because of these reasons, it's time to end it. The serial compiler has served us well in the years since it was split from the parallel one, but it's over now.
Let the knight slay one head of the two-headed dragon!
#113349
Note that the default is still 1 thread, as more than 1 thread is still fairly broken.
cc `@onur-ozkan` to see if i did the bootstrap field removal correctly, `@SparrowLii` on the sync parts
Since it's inception a long time ago, the parallel compiler and its cfgs
have been a maintenance burden. This was a necessary evil the allow
iteration while not degrading performance because of synchronization
overhead.
But this time is over. Thanks to the amazing work by the parallel
working group (and the dyn sync crimes), the parallel compiler has now
been fast enough to be shipped by default in nightly for quite a while
now.
Stable and beta have still been on the serial compiler, because they
can't use `-Zthreads` anyways.
But this is quite suboptimal:
- the maintenance burden still sucks
- we're not testing the serial compiler in nightly
Because of these reasons, it's time to end it. The serial compiler has
served us well in the years since it was split from the parallel one,
but it's over now.
Let the knight slay one head of the two-headed dragon!
move all mono-time checks into their own folder, and their own query
The mono item collector currently also drives two mono-time checks: the lint for "large moves", and the check whether function calls are done with all the required target features.
Instead of doing this "inside" the collector, this PR refactors things so that we have a new `rustc_monomorphize::mono_checks` module providing a per-instance query that does these checks. We already have a per-instance query for the ABI checks, so this should be "free" for incremental builds. Non-incremental builds might do a bit more work now since we now have two separate MIR visits (in the collector and the mono-time checks) -- but one of them is cached in case the MIR doesn't change, which is nice.
This slightly changes behavior of the large-move check since the "move_size_spans" deduplication logic now only works per-instance, not globally across the entire collector.
Cc `@saethlin` since you're also doing some work related to queries and caching and monomorphization, though I don't know if there's any interaction here.
Make sure to ignore elided lifetimes when pointing at args for fulfillment errors
See the comment I left in the code.
---
If we have something like:
```
fn foo<'a, T: 'a + BoundThatIsNotSatisfied>() {}
```
And the user turbofishes just the type args:
```
foo::<()>();
```
Then if we try pointing at `()` (i.e. the type argument for `T`), we don't actually consider the possibility that the lifetimes may have been left out of the turbofish. We try indexing incorrectly into the HIR args, and bail on the suggestion.
Consolidate type system const evaluation under `traits::evaluate_const`
Part of #130704Fixes#128232Fixes#118545
Removes `ty::Const::{normalize_internal, eval_valtree}` and `InferCtxt::(try_)const_eval_resolve`, consolidating the associated logic into `evaluate_const` in `rustc_trait_selection`. This results in an API for `ty::Const` that is free of any normalization/evaluation functions that would be incorrect to use under `min_generic_const_args`/`associated_const_equality`/`generic_const_exprs` or, more generally, that would be incorrect to use in the presence of generic type system constants.
Moving this logic to `rustc_trait_selection` and out of `rustc_middle` is also a pre-requisite for ensuring that we do not evaluate constants whose where clauses do not hold.
From this point it should be relatively simple (hah) to implement more complex normalization of type system constants such as: checking wf'ness before invoking CTFE machinery, or being able to normalize const aliases that still refer to generic parameters.
r? `@compiler-errors`
Feature gate yield expressions not in 2024
This changes it so that yield expressions are no longer allowed in the 2024 edition without a feature gate. We are currently only reserving the `gen` keyword in the 2024 edition, and not allowing anything else to be implicitly enabled by the edition.
In practice this doesn't have a significant difference since yield expressions can't really be used outside of coroutines or gen blocks, which have their own feature gates. However, it does affect what is accepted pre-expansion, and I would feel more comfortable not allowing yield expressions.
I believe the stabilization process for gen blocks or coroutines will not need to check the edition here, so this shouldn't ever be needed.
Remove attributes from generics in built-in derive macros
Related issue #132561
Removes all attributes from generics in the expanded implementations of built-in derive macros.
Make sure that we suggest turbofishing the right type arg for never suggestion
I had a bug where rust would suggest the wrong arg to turbofish `()` if there were any early-bound lifetimes...
r? WaffleLapkin
Don't use `maybe_unwrap_block` when checking for macro calls in a block expr
Fixes#131915
Using `maybe_unwrap_block` to determine if we are looking at a `{ mac_call!{} }` will fail sometimes as `mac_call!{}` could be a `StmtKind::MacCall` not a `StmtKind::Expr`. This caused the def collector to think that `{ mac_call!{} }` was a non-trivial const argument and create a definition for it even though it should not.
r? `@compiler-errors` cc `@camelid`
cleanup: Remove outdated comment of `thir_body`
When typeck fails, `thir_body` returns `ErrorGuaranteed` rather than empty body.
No other code follows this outdated description except `check_unsafety`, which is also cleaned up in this PR.
Provide placeholder generics for traits in "no method found for type parameter" suggestions
In the diagnostics for the error ``no method named `method` found for type parameter `T` in the current scope [E0599]``, the compiler will suggest adding bounds on `T` for traits that define a method named `method`. However, these suggestions didn't include any generic arguments, so applying them would result in a `missing generics for trait` or `missing lifetime specifier` error. This PR adds placeholder arguments to the suggestion in such cases. Specifically, I tried to base the placeholders off of what's done in suggestions for when generics are missing or too few are provided:
- The placeholder for a parameter without a default is the name of the parameter.
- Placeholders are not provided for parameters with defaults.
Placeholder arguments are enclosed in `/*` and `*/`, and the applicability of the suggestion is downgraded to `Applicability::HasPlaceholders` if any placeholders are provided.
Fixes#132407
Add a default implementation for CodegenBackend::link
As a side effect this should add raw-dylib support to cg_gcc as the default ArchiveBuilderBuilder that is used implements create_dll_import_lib. I haven't tested if the raw-dylib support actually works however.
Document some `check_expr` methods, and other misc `hir_typeck` tweaks
Most importantly, make sure that all of the expression checking functions that are called from `check_expr_kind` start with `check_expr_*`. This is super useful to me personally, since I grep these functions all the time, and the ones that *aren't* named consistently are incredibly hard to find.
Also document more of the `check_expr_*` functions, and squash two args for passing data about a call expr into one `Option`.
Arbitrary self types v2: (unused) Receiver trait
This commit contains a new `Receiver` trait, which is the basis for the Arbitrary Self Types v2 RFC. This allows smart pointers to be method receivers even if they're not Deref.
This is currently unused by the compiler - a subsequent PR will start to use this for method resolution if the `arbitrary_self_types` feature gate is enabled. This is being landed first simply to make review simpler: if people feel this should all be in an atomic PR let me know.
This is a part of the arbitrary self types v2 project, https://github.com/rust-lang/rfcs/pull/3519https://github.com/rust-lang/rust/issues/44874
r? `@wesleywiser`
Remove `rustc_session::config::rustc_short_optgroups`
Follow-up to https://github.com/rust-lang/rust/pull/132754#discussion_r1835427349.
The name `rustc_short_optgroups` has always been confusing, because it is unrelated to the distinction between short and long options (i.e. `-s` vs `--long`), and instead means something like “the subset of command-line options that are printed by `rustc --help` without `-v`”.
So let's merge that function into the main `rustc_optgroups`, and store the relevant bit of information in a boolean field in `RustcOptGroup` instead.
---
This PR also modifies `RustcOptGroup` to store its various strings directly, instead of inside a boxed `apply` closure. That turned out to not be necessary for the main change, but is a worthwhile cleanup in its own right.
query/plumbing: adjust comment to reality
The limit for the query key size got changed recently in f51ec110a7 but the comment was not updated.
Though maybe it is time to intern `CanonicalTypeOpAscribeUserTypeGoal` rather than copying it everywhere?
r? `@lcnr`
Stabilize WebAssembly `multivalue`, `reference-types`, and `tail-call` target features
For the `multivalue` and `reference-types` features this commit is
similar to https://github.com/rust-lang/rust/pull/117457 in that it's stabilizing target features specific to
WebAssembly targets. The previous PR left out these two features because
they weren't expected to change much about compiled code so it was
unclear what the rationale was. It has [since been discovered][blog]
that `reference-types` can be useful as it changes the binary format of
the `call_indirect` instruction. Additionally [on Zulip][zulip] there's
a use case of detecting these features at compile time and generating a
compile error to better warn users about features not supported on
engines.
This PR then additionally adds the `tail-call` feature which corresponds
to the [tail-call] proposal to WebAssembly. This feature advanced to
"phase 4" in the WebAssembly CG awhile back and has been supported in
LLVM for quite some time now. Engines are finishing up implementations
or have already shipped implementations, so while this is a bit of a
late addition to Rust itself it reflects the current status of
WebAssembly's state of the feature.
A test has been added here not only for these features but other
WebAssembly features as well to showcase that they're usable without
feature gates in stable Rust.
[blog]: https://blog.rust-lang.org/2024/09/24/webassembly-targets-change-in-default-target-features.html
[zulip]: https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/wasm32.20reference-types.20.2F.20multivalue.20in.201.2E82-beta.20not.20enabled/near/473893987
[tail-call]: https://github.com/webassembly/tail-call
Prefer `pub(super)` in `unreachable_pub` lint suggestion
This PR updates the `unreachable_pub` lint suggestion to prefer `pub(super)` instead of `pub(crate)` when possible.
cc `@petrochenkov`
r? `@nnethercote`
Stabilize Arm64EC inline assembly
This stabilizes inline assembly for Arm64EC ("Emulation Compatible").
Corresponding reference PR: https://github.com/rust-lang/reference/pull/1653
---
From the requirements of stabilization mentioned in https://github.com/rust-lang/rust/issues/93335
> Each architecture needs to be reviewed before stabilization:
> - It must have clobber_abi.
Done in https://github.com/rust-lang/rust/pull/131332.
> - It must be possible to clobber every register that is normally clobbered by a function call.
This is possible from the time of the initial implementation.
> - Generally review that the exposed register classes make sense.
The registers available in this target are a subset of those available in the AArch64 inline assembly which is already stable.
The following registers cannot be used in Arm64EC compared to AArch64:
- `x13`, `x14`, `x23`, `x24`, `x28` (register class: `reg`)
- `v[16-31]` (register class: `vreg`)
- `p[0-15]`, `ffr` (clobber-only register class `preg`)
These are disallowed by the ABI (see also [abi docs](https://learn.microsoft.com/en-us/cpp/build/arm64ec-windows-abi-conventions?view=msvc-170#register-mapping) for `reg`/`vreg` and https://github.com/rust-lang/rust/pull/131332#issuecomment-2401189142 for `preg`).
Although not listed in the above requirements, preserves_flags is also implemented and the same as AArch64.
---
cc `@dpaoliello`
r? `@Amanieu`
`@rustbot` label O-windows O-AArch64 +A-inline-assembly +T-lang -T-compiler +needs-fcp
coverage: Restrict empty-span expansion to only cover `{` and `}`
Coverage instrumentation has some tricky code for converting a coverage-relevant `Span` into a set of start/end line/byte-column coordinates that will be embedded in the CGU's coverage metadata.
A big part of this complexity is special code for handling empty spans, which are expanded into non-empty spans (if possible) because LLVM's coverage reporter does not handle empty spans well.
This PR simplifies that code by restricting it to only apply in two specific situations: when the character after the empty span is `{`, or the character before the empty span is `}`.
(As an added benefit, this means that the expanded spans no longer extend awkwardly beyond the end of a physical line, which was common under the previous implementation.)
Along the way, this PR also removes some unhelpful code for dealing with function source code spread across multiple files. Functions currently can't have coverage spans in multiple files, and if that ever changes (e.g. to properly support expansion regions) then this code will need to be completely overhauled anyway.
For the `multivalue` and `reference-types` features this commit is
similar to #117457 in that it's stabilizing target features specific to
WebAssembly targets. The previous PR left out these two features because
they weren't expected to change much about compiled code so it was
unclear what the rationale was. It has [since been discovered][blog]
that `reference-types` can be useful as it changes the binary format of
the `call_indirect` instruction. Additionally [on Zulip][zulip] there's
a use case of detecting these features at compile time and generating a
compile error to better warn users about features not supported on
engines.
This PR then additionally adds the `tail-call` feature which corresponds
to the [tail-call] proposal to WebAssembly. This feature advanced to
"phase 4" in the WebAssembly CG awhile back and has been supported in
LLVM for quite some time now. Engines are finishing up implementations
or have already shipped implementations, so while this is a bit of a
late addition to Rust itself it reflects the current status of
WebAssembly's state of the feature.
A test has been added here not only for these features but other
WebAssembly features as well to showcase that they're usable without
feature gates in stable Rust.
[blog]: https://blog.rust-lang.org/2024/09/24/webassembly-targets-change-in-default-target-features.html
[zulip]: https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/wasm32.20reference-types.20.2F.20multivalue.20in.201.2E82-beta.20not.20enabled/near/473893987
[tail-call]: https://github.com/webassembly/tail-call
Dont suggest `use<impl Trait>` when we have an edition-2024-related borrowck issue
#131186 implements some machinery to detect in borrowck when we may have RPIT overcaptures due to edition 2024, and suggests adding `+ use<'a, T>` to go back to the edition 2021 capture rules. However, we weren't filtering out cases when there are APITs in scope.
This PR implements a more sophisticated diagnostic where we will suggest turning any APITs in scope into type parameters, and applies this to both the borrowck error note, and to the `impl_trait_overcaptures` migration lint.
cc #132809
require const_impl_trait gate for all conditional and trait const calls
Alternative to https://github.com/rust-lang/rust/pull/132786.
`@compiler-errors` this is basically what I meant with my proposals. I found it's easier to express this in code than English. ;)
r? `@compiler-errors`
interpret: get_alloc_info: also return mutability
This will be needed for https://github.com/rust-lang/miri/pull/3971
This then tuned into a larger refactor where we introduce a new type for the `get_alloc_info` return data, and we move some code to methods on `GlobalAlloc` to avoid duplicating it between the validity check and `get_alloc_info`.
Stabilize s390x inline assembly
This stabilizes inline assembly for s390x (SystemZ).
Corresponding reference PR: https://github.com/rust-lang/reference/pull/1643
---
From the requirements of stabilization mentioned in https://github.com/rust-lang/rust/issues/93335
> Each architecture needs to be reviewed before stabilization:
> - It must have clobber_abi.
Done in https://github.com/rust-lang/rust/pull/130630.
> - It must be possible to clobber every register that is normally clobbered by a function call.
Done in the PR that added support for clobber_abi.
> - Generally review that the exposed register classes make sense.
The followings can be used as input/output:
- `reg` (`r[0-10]`, `r[12-14]`): General-purpose register
- `reg_addr` (`r[1-10]`, `r[12-14]`): General-purpose register except `r0` which is evaluated as zero in an address context
This class is needed because `r0`, which may be allocated when using the `reg` class, cannot be used as a register in certain contexts. This is identical to the `a` constraint in LLVM and GCC. See https://github.com/rust-lang/rust/pull/119431 for details.
- `freg` (`f[0-15]`): Floating-point register
The followings are clobber-only:
- `vreg` (`v[0-31]`): Vector register
Technically `vreg` should be able to accept `#[repr(simd)]` types as input/output if the unstable `vector` target feature added is enabled, but `core::arch` has no s390x vector type and both `#[repr(simd)]` and `core::simd` are unstable. Everything related is unstable, so the fact that this is currently a clobber-only should not be considered a stabilization blocker. (https://github.com/rust-lang/rust/issues/130869 tracks unstable stuff here)
- `areg` (`a[2-15]`): Access register
All of the above register classes except `reg_addr` are needed for `clobber_abi`.
The followings cannot be used as operands for inline asm (see also [getReservedRegs](https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/SystemZ/SystemZRegisterInfo.cpp#L258-L282) and [SystemZELFRegisters](https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/SystemZ/SystemZRegisterInfo.h#L107-L128) in LLVM):
- `r11`: frame pointer
- `r15`: stack pointer
- `a0`, `a1`: Reserved for system use
- `c[0-15]` (control register) Reserved by the kernel
Although not listed in the above requirements, `preserves_flags` is implemented in https://github.com/rust-lang/rust/pull/111331.
---
cc ``@uweigand``
r? ``@Amanieu``
``@rustbot`` label +O-SystemZ +A-inline-assembly
Emit warning when calling/declaring functions with unavailable vectors.
On some architectures, vector types may have a different ABI depending on whether the relevant target features are enabled. (The ABI when the feature is disabled is often not specified, but LLVM implements some de-facto ABI.)
As discussed in rust-lang/lang-team#235, this turns out to very easily lead to unsound code.
This commit makes it a post-monomorphization future-incompat warning to declare or call functions using those vector types in a context in which the corresponding target features are disabled, if using an ABI for which the difference is relevant. This ensures that these functions are always called with a consistent ABI.
See the [nomination comment](https://github.com/rust-lang/rust/pull/127731#issuecomment-2288558187) for more discussion.
Part of #116558
r? RalfJung
After link_binary the temporary files referenced by CodegenResults are
deleted, so calling link_binary again with the same CodegenResults
should not be allowed.
As a side effect this should add raw-dylib support to cg_gcc as the
default ArchiveBuilderBuilder that is used implements
create_dll_import_lib. I haven't tested if the raw-dylib support
actually works however.
Rollup of 7 pull requests
Successful merges:
- #132341 (Reject raw lifetime followed by `'`, like regular lifetimes do)
- #132363 (Enforce that raw lifetimes must be valid raw identifiers)
- #132744 (add regression test for #90781)
- #132754 (Simplify the internal API for declaring command-line options)
- #132772 (use `download-rustc="if-unchanged"` as a global default)
- #132774 (Use lld with non-LLVM backends)
- #132799 (Make `Ty::primitive_symbol` recognize `str`)
r? `@ghost`
`@rustbot` modify labels: rollup
Make `Ty::primitive_symbol` recognize `str`
Make `Ty::primitive_symbol` recognize `str`, which makes `str` eligible for the "expected primitive, found local type" (and vice versa) [diagnostic](https://github.com/rust-lang/rust/blob/master/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs#L1430-L1437) that already exists for other primitives.
<details><summary> diagnostic difference</summary>
```rs
#[allow(non_camel_case_types)]
struct str;
fn foo() {
let _: &str = "hello";
let _: &core::primitive::str = &str;
}
```
`rustc --crate-type lib --edition 2021 a.rs`
Current nightly:
```rs
error[E0308]: mismatched types
--> a.rs:5:19
|
5 | let _: &str = "hello";
| ---- ^^^^^^^ expected `str`, found a different `str`
| |
| expected due to this
|
= note: expected reference `&str`
found reference `&'static str`
error[E0308]: mismatched types
--> a.rs:6:36
|
6 | let _: &core::primitive::str = &str;
| --------------------- ^^^^ expected `str`, found a different `str`
| |
| expected due to this
|
= note: expected reference `&str` (`str`)
found reference `&str` (`str`)
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0308`.
```
With this patch:
```rs
error[E0308]: mismatched types
--> a.rs:5:19
|
5 | let _: &str = "hello";
| ---- ^^^^^^^ expected `str`, found a different `str`
| |
| expected due to this
|
= note: str and `str` have similar names, but are actually distinct types
= note: str is a primitive defined by the language
note: `str` is defined in the current crate
--> a.rs:2:1
|
2 | struct str;
| ^^^^^^^^^^
error[E0308]: mismatched types
--> a.rs:6:36
|
6 | let _: &core::primitive::str = &str;
| --------------------- ^^^^ expected `str`, found a different `str`
| |
| expected due to this
|
= note: str and `str` have similar names, but are actually distinct types
= note: str is a primitive defined by the language
note: `str` is defined in the current crate
--> a.rs:2:1
|
2 | struct str;
| ^^^^^^^^^^
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0308`.
```
</details>
Use lld with non-LLVM backends
On arm64, Cranelift used to produce object files that don't work with lld. This has since been fixed. The GCC backend should always produce object files that work with lld unless lld for whatever reason drops GCC support. Most of the other more niche backends don't use cg_ssa's linker code at all. If they do and don't work with lld, they can always disable lld usage using a cli argument.
Without this commit using cg_clif is by default in a non-trivial amount of cases a perf regression on Linux due to ld.bfd being a fair bit slower than lld. It is possible to explicitly enable it without this commit, but most users are unlikely to do this.
Simplify the internal API for declaring command-line options
The internal APIs for declaring command-line options are old, and intimidatingly complex. This PR replaces them with a single function that takes explicit `stability` and `kind` arguments, making it easier to see how each option is handled, and whether it is treated as stable or unstable.
We also don't appear to have any tests for the output of `rustc --help` and similar, so I've added a run-make test to verify that this PR doesn't change any output. (There is already a similar run-make test for rustdoc's help output.)
---
The librustdoc changes are simply adjusting to updated compiler APIs; no functional change intended.
---
A side-effect of these changes is that rustfmt can once again format the entirety of these option declaration lists, which it was not doing before.
Enforce that raw lifetimes must be valid raw identifiers
Make sure that the identifier part of a raw lifetime is a valid raw identifier. This precludes `'r#_` and all module segment paths for now.
I don't believe this is compelling to support. This was raised by `@ehuss` in https://github.com/rust-lang/reference/pull/1603#discussion_r1822726753 (well, specifically the `'r#_` case), but I don't see why we shouldn't just make it consistent with raw identifiers.
Reject raw lifetime followed by `'`, like regular lifetimes do
See comment. We want to reject cases like `'r#long'id`, which currently gets interpreted as a raw lifetime (`'r#long`) followed by a lifetime (`'id`). This could have alternative lexes, such as an overlong char literal (`'r#long'`) followed by an identifier (`id`). To avoid committing to this in any case, let's reject the whole thing.
`@mattheww,` is this what you were looking for in https://github.com/rust-lang/reference/pull/1603#issuecomment-2339237325? I'd say ignore the details about the specific error message (the fact that this gets reinterpreted as a char literal is 🤷), just that because this causes a lexer error we're effectively saving syntactical space like you wanted.
Add discriminators to DILocations when multiple functions are inlined into a single point.
LLVM does not expect to ever see multiple dbg_declares for the same variable at the same location with different values. proc-macros make it possible for arbitrary code, including multiple calls that get inlined, to happen at any given location in the source code. Add discriminators when that happens so these locations are different to LLVM.
This may interfere with the AddDiscriminators pass in LLVM, which is added by the unstable flag -Zdebug-info-for-profiling.
LLVM does not expect to ever see multiple dbg_declares for the same variable at the same
location with different values. proc-macros make it possible for arbitrary code,
including multiple calls that get inlined, to happen at any given location in the source
code. Add discriminators when that happens so these locations are different to LLVM.
This may interfere with the AddDiscriminators pass in LLVM, which is added by the
unstable flag -Zdebug-info-for-profiling.
Fixes#131944
Subtree sync for rustc_codegen_cranelift
Apart from a perf optimization for some crates (https://github.com/rust-lang/rustc_codegen_cranelift/pull/1541) not much changed this time as the last sync was less than a week ago.
r? `@ghost`
`@rustbot` label +A-codegen +A-cranelift +T-compiler
Rollup of 5 pull requests
Successful merges:
- #132552 (Add v9, v8plus, and leoncasa target feature to sparc and use v8plus in create_object_file)
- #132745 (pointee_info_at: fix logic for recursing into enums)
- #132777 (try_question_mark_nop: update test for LLVM 20)
- #132785 (rustc_target: more target string fixes for LLVM 20)
- #132794 (Use a separate dir for r-a builds consistently in helix config)
r? `@ghost`
`@rustbot` modify labels: rollup
rustc_target: more target string fixes for LLVM 20
LLVM continues to clean these up, and we continue to make this consistent. This is similar to 9caced7bad and e985396145.
`@rustbot` label: +llvm-main
pointee_info_at: fix logic for recursing into enums
Fixes https://github.com/rust-lang/rust/issues/131834
The logic in `pointee_info_at` was likely written at a time when the null pointer optimization was the *only* enum layout optimization -- and as `Variant::Multiple` kept getting expanded, nobody noticed that the logic is now unsound.
The job of this function is to figure out whether there is a dereferenceable-or-null and aligned pointer at a given offset inside a type. So when we recurse into a multi-variant enum, we better make sure that all the other enum variants must be null! This is the part that was forgotten, and this PR adds it.
The reason this didn't explode in many ways so far is that our references only have 1 niche value (null), so it's not possible on stable to have a multi-variant enum with a dereferenceable pointer and other enum variants that are not null. But with `rustc_layout_scalar_valid_range` attributes one can force such a layout, and if `@the8472's` work on alignment niches ever lands, that will make this possible on stable.
Trim and tidy includes in `rustc_llvm`
These includes tend to accumulate over time, and are usually only removed when something breaks in a new LLVM version, so it's nice to clean them up manually once in a while.
General strategy used for this PR:
- Remove all includes from `LLVMWrapper.h` that aren't needed by the header itself, transplanting them to individual source files as necessary.
- For each source file, temporarily remove each include if doing so doesn't cause a compile error.
- If a “required” include looks like it shouldn't be needed, try replacing it with its sub-includes, then trim that list.
- After doing all of the above, go back and re-add any removed include if the file does actually use things defined in that header, even if the header happens to also be included by something else.
use verbose for path separator suggestion
A single `-` of suggestion underlining that is adjacent to a much more significant `^^^` underlying of the LHS path component is hard to distinguish. IMO this presents much more cleanly when it's verbose, especially because it's a *replacment* suggestion.
r? estebank
Don't suggest `.into_iter()` on iterators
This makes the the suggestion to call `.into_iter()` only consider unsatisfied `Iterator` bounds for the receiver type itself. That way, it ignores predicates generated by trying to auto-ref the receiver (the result of which usually won't implement `Iterator`).
Fixes#127511
Unfortunately, the error in that case is still confusing: it labels `Iterator` as an unsatisfied bound because `&impl Iterator: Iterator` can't be satisfied, despite that not being required or helpful. I'd like to handle that in a separate PR. ~~I'm hoping fixing #124802 will fix it too.~~ It doesn't look connected to that issue. Still, I think it'd be clearest to visually distinguish unsatisfied predicates from different attempts at `pick_method`; I'll make a PR for that soon.