It's a trait that aggregates five other traits. But consider the places
that use it.
- `BuilderMethods`: requires three of the five traits.
- `CodegenMethods`: requires zero(!) of the five traits.
- `BaseTypeMethods`: requires two of the five traits.
- `LayoutTypeMethods`: requires three of the five traits.
- `TypeMembershipMethods`: requires one of the five traits.
This commit just removes it, which makes everything simpler.
It has `Backend` and `Deref` boudns, plus an associated type
`CodegenCx`, and it has a single use. This commit "inlines" it into
`BuilderMethods`, which makes the complicated backend trait situation a
little simpler.
It only needs `Self::Value` and `Self::Type`, so it can be a subtrait of
`BackendTypes`. That is a smaller and simpler trait than `HasCodegen`
(which includes `BackendTypes` and a lot more).
This changed in
llvm/llvm-project@e190d074a0. I decided to
stick with more duplication between the ifdef blocks to make the code
easier to read for the next two years before we can plausibly drop LLVM
19.
@rustbot label: +llvm-main
For structs that cannot be unsized, the layout algorithm sometimes moves
unsized fields to the end of the struct, which circumvented the error
for unexpected unsized fields and returned an unsized layout anyway.
This commit makes it so that the unexpected unsized error is always
returned for structs that cannot be unsized, allowing us to remove an
old hack and fixing some old ICE.
Rollup of 3 pull requests
Successful merges:
- #130033 (Don't call `fn_arg_names` query for non-`fn` foreign items in resolver)
- #130282 (Do not report an excessive number of overflow errors for an ever-growing deref impl)
- #130437 (Avoid crashing on variadic functions when producing arg-mismatch errors)
r? `@ghost`
`@rustbot` modify labels: rollup
Avoid crashing on variadic functions when producing arg-mismatch errors
Fixes#130372 by accommodating how variadic functions change the argument list length between HIR body and FnDecls.
Also degrades the zip_eq to a debug_assert! to match other asserts in the area to avoid being disruptive to users. There is at least one other crash in this area I am working on in #130400 and also considering how we might refactor some of this code to hoist some of this logic up higher.
r? `@compiler-errors`
Do not report an excessive number of overflow errors for an ever-growing deref impl
Check that we don't first hit the recursion limit in `get_field_candidates_considering_privacy` before probing for methods when we have a method lookup failure and we want to see if `.field.method()` exists. We also silence overflow error messages if we're probing for methods for diagnostics.
Also renames some functions to make it clearer that they're only for diagnostics, and sprinkle some `Autoderef::silence_errors` around to silence unnecessary overflow errors that come from diagnostics.
Fixes#130224.
Rollup of 4 pull requests
Successful merges:
- #123436 (linker: Allow MSVC to use import libraries following the Meson/MinGW convention)
- #130410 (Don't ICE when generating `Fn` shim for async closure with borrowck error)
- #130412 (Don't ICE when RPITIT captures more method args than trait definition)
- #130436 (Ignore reduce-fadd-unordered on SGX platform)
r? `@ghost`
`@rustbot` modify labels: rollup
Don't ICE when RPITIT captures more method args than trait definition
Make sure we don't ICE when an RPITIT captures more method args than the trait definition, which is not allowed. This was because we were using the wrong def id for error reporting.
Due to the default lifetime capture rules of RPITITs (capturing everything in scope), this is only doable if we use precise capturing, which isn't currently allowed for RPITITs anyways but we still end up reaching the relevant codepaths.
Fixes#129850
Don't ICE when generating `Fn` shim for async closure with borrowck error
Turn an assumption that I had originally written as an assert into a delayed bug, because this shim code is reachable even if we have borrowck errors via the MIR inliner.
Fixes#129262.
linker: Allow MSVC to use import libraries following the Meson/MinGW convention
Hi all,
This PR implements support for `MsvcLinker` to use import libraries following Meson and the MinGW toolchain's naming convention. Meson [follows the `libfoo.dll.a` naming convention](https://mesonbuild.com/FAQ.html#why-does-building-my-project-with-msvc-output-static-libraries-called-libfooa) to disambiguate between static and import libraries.
This support already existed for static libraries (see #100101), but not for dynamic libraries. The latter case was added by duplicating the logic in `native_libs::find_native_static_library`, but a separate case was added in `link_dylib_by_name` for the Windows CRT libraries which must be handled by the linker itself.
See for prerequisites #129366, #126094, and #128370.
All feedback is appreciated!
Fixes#122455
cc `@sdroege` `@nirbheek`
Don't use `typeck_root_def_id` in codegen for finding closure's root
Generating debuginfo in codegen currently peels off all the closure-specific generics (which presumably is done because they're redundant). This doesn't currently work correctly for the bodies we synthesize for async closures's returned coroutines (#128506), leading to #129702.
Specifically, `typeck_root_def_id` for some `DefKind::SyntheticCoroutineBody` just returns itself (because it loops while `is_typeck_child` is `true`, and that returns `false` for this defkind), which means we don't end up peeling off the coroutine-specific generics, and we end up encountering an otherwise unreachable `CoroutineWitness` type leading to an ICE.
This PR fixes `is_typeck_child` to consider `DefKind::SyntheticCorotuineBody` to be a typeck child, fixing `typeck_root_def_id` and suppressing this debuginfo bug.
Fixes#129702
Add system libs for LLVM when cross compiling for Windows
Windows uses "import libraries" to link to system libraries. These are a kind of static lib that are distributed with the Windows SDK and therefore they don't rely on the host. All that matters is you have the right SDK installed for the target.
Use -0.0 in `intrinsics::simd::reduce_add_unordered`
-0.0 is the actual neutral additive float, not +0.0, and this matters to codegen.
try-job: aarch64-gnu
compiler: Document AbiAndPrefAlign
The mere existence of this struct is confusing, and the second field doubly so. It's easy to mistake the "preferred" alignment as semantically relevant somehow. Insofar as I am aware, it is not, and certainly not for Rust code.
deprecate -Csoft-float because it is unsound (and not fixable)
See https://github.com/rust-lang/rust/issues/129893 for details. The general sentiment there seems to be that this flag has no use and sound alternatives exist, so let's add this warning and see if anyone out there disagrees.
Also show a different warning on targets where it does nothing (as documented since https://github.com/rust-lang/rust/pull/36261): it seems to correspond to `-mfloat-abi` in GCC/clang, which is an ARM-specific option. To be really sure it does nothing, only forward the flag to LLVM for eabihf targets. This should not change behavior but makes me sleep better ;)
interpret, miri: fix dealing with overflow during slice indexing and allocation
This is mostly to fix https://github.com/rust-lang/rust/issues/130284.
I then realized we're using somewhat sketchy arguments for a similar multiplication in `copy`/`copy_nonoverlapping`/`write_bytes`, so I made them all share the same function that checks exactly the right thing. (The intrinsics would previously fail on allocations larger than `1 << 47` bytes... which are theoretically possible maybe? Anyway it seems conceptually wrong to use any other bound than `isize::MAX` here.)
miri: treat non-memory local variables properly for data race detection
Fixes https://github.com/rust-lang/miri/issues/3242
Miri has an optimization where some local variables are not represented in memory until something forces them to be stored in memory (most notably, creating a pointer/reference to the local will do that). However, for a subsystem triggering on memory accesses -- such as the data race detector -- this means that the memory access seems to happen only when the local is moved to memory, instead of at the time that it actually happens. This can lead to UB reports in programs that do not actually have UB.
This PR fixes that by adding machine hooks for reads and writes to such efficiently represented local variables. The data race system tracks those very similar to how it would track reads and writes to addressable memory, and when a local is moved to memory, the clocks get overwritten with the information stored for the local.
Rollup of 5 pull requests
Successful merges:
- #129195 (Stabilize `&mut` (and `*mut`) as well as `&Cell` (and `*const Cell`) in const)
- #130118 (move Option::unwrap_unchecked into const_option feature gate)
- #130295 (Fix target-cpu fpu features on Armv8-R.)
- #130371 (Correctly account for niche-optimized tags in rustc_transmute)
- #130381 (library: Compute Rust exception class from its string repr)
r? `@ghost`
`@rustbot` modify labels: rollup
Correctly account for niche-optimized tags in rustc_transmute
This is a bit hacky, but it fixes the ICE and makes it possible to run the safe transmute check on every `mem::transmute` check we instantiate. I want to write a lint that needs to do that, but this stands well on its own.
cc `@jswrenn` here's the fix I alluded to yesterday :)
Fixes#123693
Fix target-cpu fpu features on Armv8-R.
This is a follow-up to #123159, but applied to Armv8-R.
This required https://github.com/llvm/llvm-project/pull/88287 to work properly. Now that this change exists in rustc's llvm, we can fix Armv8-R's default fpu features. In Armv8-R's case, the default features from LLVM for floating-point are sufficient, because there is no integer-only variant of this architecture.
Stabilize `&mut` (and `*mut`) as well as `&Cell` (and `*const Cell`) in const
This stabilizes `const_mut_refs` and `const_refs_to_cell`. That allows a bunch of new things in const contexts:
- Mentioning `&mut` types
- Creating `&mut` and `*mut` values
- Creating `&T` and `*const T` values where `T` contains interior mutability
- Dereferencing `&mut` and `*mut` values (both for reads and writes)
The same rules as at runtime apply: mutating immutable data is UB. This includes mutation through pointers derived from shared references; the following is diagnosed with a hard error:
```rust
#[allow(invalid_reference_casting)]
const _: () = {
let mut val = 15;
let ptr = &val as *const i32 as *mut i32;
unsafe { *ptr = 16; }
};
```
The main limitation that is enforced is that the final value of a const (or non-`mut` static) may not contain `&mut` values nor interior mutable `&` values. This is necessary because the memory those references point to becomes *read-only* when the constant is done computing, so (interior) mutable references to such memory would be pretty dangerous. We take a multi-layered approach here to ensuring no mutable references escape the initializer expression:
- A static analysis rejects (interior) mutable references when the referee looks like it may outlive the current MIR body.
- To be extra sure, this static check is complemented by a "safety net" of dynamic checks. ("Dynamic" in the sense of "running during/after const-evaluation, e.g. at runtime of this code" -- in contrast to "static" which works entirely by looking at the MIR without evaluating it.)
- After the final value is computed, we do a type-driven traversal of the entire value, and if we find any `&mut` or interior-mutable `&` we error out.
- However, the type-driven traversal cannot traverse `union` or raw pointers, so there is a second dynamic check where if the final value of the const contains any pointer that was not derived from a shared reference, we complain. This is currently a future-compat lint, but will become an ICE in #128543. On the off-chance that it's actually possible to trigger this lint on stable, I'd prefer if we could make it an ICE before stabilizing const_mut_refs, but it's not a hard blocker. This part of the "safety net" is only active for mutable references since with shared references, it has false positives.
Altogether this should prevent people from leaking (interior) mutable references out of the const initializer.
While updating the tests I learned that surprisingly, this code gets rejected:
```rust
const _: Vec<i32> = {
let mut x = Vec::<i32>::new(); //~ ERROR destructor of `Vec<i32>` cannot be evaluated at compile-time
let r = &mut x;
let y = x;
y
};
```
The analysis that rejects destructors in `const` is very conservative when it sees an `&mut` being created to `x`, and then considers `x` to be always live. See [here](https://github.com/rust-lang/rust/issues/65394#issuecomment-541499219) for a longer explanation. `const_precise_live_drops` will solve this, so I consider this problem to be tracked by https://github.com/rust-lang/rust/issues/73255.
Cc `@rust-lang/wg-const-eval` `@rust-lang/lang`
Cc https://github.com/rust-lang/rust/issues/57349
Cc https://github.com/rust-lang/rust/issues/80384
interpret: get_ptr_alloc_mut: lookup allocation only once
I don't think this will make a big perf difference, but it makes this function symmetric with `get_ptr_alloc` -- and it's always nice to successfully solve a borrow checker puzzle like this. ;)
This is a follow-up to #123159, but applied to Armv8-R.
This required https://github.com/llvm/llvm-project/pull/88287 to work
properly. Now that this change exists in rustc's llvm, we can fix
Armv8-R's default fpu features. In Armv8-R's case, the default features
from LLVM for floating-point are sufficient, because there is no
integer-only variant of this architecture.
Given that we directly access the graph predecessors/successors in so many
other places, and sometimes must do so to satisfy the borrow checker, there is
little value in having this trivial helper method.
- Look up the node's predecessors only once
- Get rid of some overly verbose logging
- Explain why some nodes need physical counters
- Extract a helper method to create and set a physical node counter
Make some lint doctests compatible with `--stage=0`
Currently, running `x test compiler --stage=0` (with `rust.parallel-compiler=false` to avoid other problems) results in two failures, because these lint doctests aren't compatible with the current stage0 compiler.
In theory, the more “correct” solution would be to wrap the opening triple-backtick line in `#[cfg_attr(not(bootstrap), doc = "..."]`. However, that causes a few practical problems:
- `tidy` doesn't understand that syntax, and miscounts the number of backticks in the comment block.
- `lint-docs` doesn't understand that syntax, and thinks it's trying to declare the lint name.
- Working around the above problems would cause more work and more confusion for whoever does the next bootstrap beta bump.
So instead this PR adds some bootstrap gates inside the individual doctests, which end up producing the desired behaviour, and are straightforward to remove.
stabilize `const_extern_fn`
closes https://github.com/rust-lang/rust/issues/64926
tracking issue: https://github.com/rust-lang/rust/issues/64926
reference PR: https://github.com/rust-lang/reference/pull/1596
## Stabilizaton Report
### Summary
Using `const extern "Rust"` and `const extern "C"` was already stabilized (since version 1.62.0, see https://github.com/rust-lang/rust/pull/95346). This PR stabilizes the other calling conventions: it is now possible to write `const unsafe extern "calling-convention" fn` and `const extern "calling-convention" fn` for any supported calling convention:
```rust
const extern "C-unwind" fn foo1(val: u8) -> u8 { val + 1}
const extern "stdcall" fn foo2(val: u8) -> u8 { val + 1}
const unsafe extern "C-unwind" fn bar1(val: bool) -> bool { !val }
const unsafe extern "stdcall" fn bar2(val: bool) -> bool { !val }
```
This can be used to const-ify an `extern fn`, or conversely, to make a `const fn` callable from external code.
r? T-lang
cc `@RalfJung`
const-eval interning: accept interior mutable pointers in final value
…but keep rejecting mutable references
This fixes https://github.com/rust-lang/rust/issues/121610 by no longer firing the lint when there is a pointer with interior mutability in the final value of the constant. On stable, such pointers can be created with code like:
```rust
pub enum JsValue {
Undefined,
Object(Cell<bool>),
}
impl Drop for JsValue {
fn drop(&mut self) {}
}
// This does *not* get promoted since `JsValue` has a destructor.
// However, the outer scope rule applies, still giving this 'static lifetime.
const UNDEFINED: &JsValue = &JsValue::Undefined;
```
It's not great to accept such values since people *might* think that it is legal to mutate them with unsafe code. (This is related to how "infectious" `UnsafeCell` is, which is a [wide open question](https://github.com/rust-lang/unsafe-code-guidelines/issues/236).) However, we [explicitly document](https://doc.rust-lang.org/reference/behavior-considered-undefined.html) that things created by `const` are immutable. Furthermore, we also accept the following even more questionable code without any lint today:
```rust
let x: &'static Option<Cell<i32>> = &None;
```
This is even more questionable since it does *not* involve a `const`, and yet still puts the data into immutable memory. We could view this as promotion [potentially introducing UB](https://github.com/rust-lang/unsafe-code-guidelines/issues/493). However, we've accepted this since ~forever and it's [too late to reject this now](https://github.com/rust-lang/rust/pull/122789); the pattern is just too useful.
So basically, if you think that `UnsafeCell` should be tracked fully precisely, then you should want the lint we currently emit to be removed, which this PR does. If you think `UnsafeCell` should "infect" surrounding `enum`s, the big problem is really https://github.com/rust-lang/unsafe-code-guidelines/issues/493 which does not trigger the lint -- the cases the lint triggers on are actually the "harmless" ones as there is an explicit surrounding `const` explaining why things end up being immutable.
What all this goes to show is that the hard error added in https://github.com/rust-lang/rust/pull/118324 (later turned into the future-compat lint that I am now suggesting we remove) was based on some wrong assumptions, at least insofar as it concerns shared references. Furthermore, that lint does not help at all for the most problematic case here where the potential UB is completely implicit. (In fact, the lint is actively in the way of [my preferred long-term strategy](https://github.com/rust-lang/unsafe-code-guidelines/issues/493#issuecomment-2028674105) for dealing with this UB.) So I think we should go back to square one and remove that error/lint for shared references. For mutable references, it does seem to work as intended, so we can keep it. Here it serves as a safety net in case the static checks that try to contain mutable references to the inside of a const initializer are not working as intended; I therefore made the check ICE to encourage users to tell us if that safety net is triggered.
Closes https://github.com/rust-lang/rust/issues/122153 by removing the lint.
Cc `@rust-lang/opsem` `@rust-lang/lang`
Fix `Parser::break_up_float`'s right span
```rs
use std::mem::offset_of;
fn main() {
offset_of!((u8,), 0.0);
}
```
Before:
```
error[E0609]: no field `0` on type `u8`
--> ./main.rs:4:25
|
4 | offset_of!((u8,), 0.0);
| _____--------------------^-
| | |
| | in this macro invocation
5 | | }
... |
|
= note: this error originates in the macro `offset_of` (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to 1 previous error
```
After:
```
error[E0609]: no field `0` on type `u8`
--> ./main.rs:4:25
|
4 | offset_of!((u8,), 0.0);
| ^
error: aborting due to 1 previous error
```
---
`@rustbot` label +A-parser +D-imprecise-spans
simd_shuffle: require index argument to be a vector
Remove some codegen hacks by forcing the SIMD shuffle `index` argument to be a vector, which means (thanks to https://github.com/rust-lang/rust/pull/128537) that it will automatically be passed as an immediate in LLVM. The only special-casing we still have is for the extra sanity-checks we add that ensure that the indices are all in-bounds. (And the GCC backend needs to do a bunch of work since the Rust intrinsic is modeled after what LLVM expects, which seems to be quite different from what GCC expects.)
Fixes https://github.com/rust-lang/rust/issues/128738, see that issue for more context.
Simplify the canonical clone method and the copy-like forms to copy
Fixes#128081.
The optimized clone method ends up as the following MIR:
```
_2 = copy ((*_1).0: i32);
_3 = copy ((*_1).1: u64);
_4 = copy ((*_1).2: [i8; 3]);
_0 = Foo { a: move _2, b: move _3, c: move _4 };
```
We can transform this to:
```
_0 = copy (*_1);
```
r? `@cjgillot`
Fix `SDKROOT` ignore on macOS
`rustc` has code to detect when `SDKROOT` is obviously set for the wrong platform, so that it can choose to ignore it. This is a pretty important feature for Cargo build scripts and proc macros, since you will often have `SDKROOT` set to an iOS platform there.
However, the code was checking for an old SDK version name `"macosx10.15"` that was previously configured by `add_apple_sdk`, but nowadays configured to the correct `"macosx"`. I think this error was introduced in part https://github.com/rust-lang/rust/pull/77202 and in https://github.com/rust-lang/rust/pull/100286.
Fixes part of https://github.com/rust-lang/rust/issues/80817 (linking with `-Clinker=ld` now works), though more work is still needed in this area, see also https://github.com/rust-lang/rust/issues/129432.
``@rustbot`` label O-macos A-cross
(fix) conflicting negative impl marker
## Context
This MR fixes the error message for conflicting negative trait impls by adding the corresponding the polarity marker to the trait name.
## Issues
- closes#70849
r? `@fmease`
Failing to do this results in the lint example output complaining
about the lint not existing instead of the thing the lint is supposed
to be complaining about.
`ProjectionElem` and `UnOp`/`BinOp` dont need to be `PartialOrd`/`Ord`
These types don't really admit a natural ordering and no code seems to rely on it, so let's remove it.
Don't call closure_by_move_body_def_id on FnOnce async closures in MIR validation
Refactors the check in #129847 to not unncessarily call the `closure_by_move_body_def_id` query for async closures that don't *need* a by-move body.
Fixes#130167
Rollup of 6 pull requests
Successful merges:
- #129320 (Fix crash when labeling arguments for call_once and friends)
- #130266 (target: default to the medium code model on LoongArch targets)
- #130297 (Dataflow cleanups)
- #130299 (Add set_dcx to ParseSess)
- #130301 (some fixes for clashing_extern_declarations lint)
- #130305 (Clippy: consider msrv for const context for const_float_bits_conv)
r? `@ghost`
`@rustbot` modify labels: rollup
some fixes for clashing_extern_declarations lint
There were two issues with the clashing_extern_declarations lint:
- It would accept non-`repr(C)` structs as compatible with each other by comparing their fields in declaration order, but the fields could have different memory order (and with `-Zrandomize-layout`, this can really happen).
- It would accept two types as compatible if `compare_layouts` returns `true`, but that function actually just compared the *ABI*, not the fully layout -- and all sized structs with more than 2 fields have the same ABI (`Abi::Aggregate`), so this missed a *lot* of cases.
We don't currently have a clear spec for what we *want* to consider "clashing" and what is fine, so I otherwise kept the original logic. I hope to have a t-lang discussion about this at some point. But meanwhile, these changes seem like clear bugfixes.
Add set_dcx to ParseSess
After [this](https://github.com/rust-lang/rust/pull/126623) PR was merged, it is no longer possible to inject one's own `Emitter` in the way [described in the Compiler Development Guide](https://rustc-dev-guide.rust-lang.org/rustc-driver-getting-diagnostics.html). The reason is that the `dcx` field in `ParseSess` is no longer public, so it is not possible to update the `dcx` field with a `DiagCtxt` that contains one's own `Emitter` in the `psess_created` callback in `rustc_interface::Config`. The only way I have found to insert my own `DiagCtxt` is by creating an entirely new `ParseSess` and replacing the old one. This is not a good solution as the original `ParseSess` contains fields I would like to keep. (In my case the problem is that I lose the `cfg` and `check-cfg` fields of the original.)
The solution proposed in this PR is to add a `set_dcx` method to `ParseSess`. Per my limited understanding of the rustc codebase this should be fine as `set_dcx` requires a mutable reference to `ParseSess`, which is as far as I know only available in the `psess_created` callback (outside of `rustc_interface::run_compiler`).
If this PR is accepted, I will create a new PR to update the aforementioned example in the Compiler Development Guide.
target: default to the medium code model on LoongArch targets
The Rust LoongArch targets have been using the default LLVM code model so far, which is "small" in LLVM-speak and "normal" in LoongArch-speak. As described in the "Code Model" section of LoongArch ELF psABI spec v20231219 [1], one can only make function calls as far as ±128MiB with the "normal" code model; this is insufficient for very large software containing Rust components that needs to be linked into the big text section, such as Chromium.
Because:
* we do not want to ask users to recompile std if they are to build such software,
* objects compiled with larger code models can be linked with those with smaller code models without problems, and
* the "medium" code model is comparable to the "small"/"normal" one performance-wise (same data access pattern; each function call becomes 2-insn long and indirect, but this may be relaxed back into the direct 1-insn form in a future LLVM version), but is able to perform function calls within ±128GiB,
it is better to just switch the targets to the "medium" code model, which is also "medium" in LLVM-speak.
Relands [2]: #120661
[1]: https://github.com/loongson/la-abi-specs/blob/v2.30/laelf.adoc#code-models
[2]: https://github.com/rust-lang/rust/issues/121289#issuecomment-2333687396
Fix crash when labeling arguments for call_once and friends
When calling a method on Fn* traits explicitly, argument diagnostics should point at the called method (eg Fn::call_once), not the underlying callee.
This PR makes 3 main changes:
* It uses TupleArguments to detect if the user called a Fn* method directly (`my_fn.call_once(…)`) or implicitly (`my_fn(…)`). If it was explicit, argument diagnostics should point at the call_once method, not the underlying callable.
* The previous state was causing confusion between the two arguments lists (which could be different lengths), causing an out-of-bounds slice indexing in #128848. I added a length assert to capture the requirement in case this regresses or happens in another case.
* Unfortunately, this assert tripped when the required arguments information was not available (`self.get_hir_params_with_generics` was returning an empty Vec), so I've updated that to return None when that information is not available. (cc `@strottos` if you have any comments, since you added this function in #121595) Sorry this causes a bunch of indentation changes, recommend reviewing [ignoring whitespace](https://github.com/rust-lang/rust/pull/129320/files?w=1).)
This is my first rustc PR, so please call out if you'd like this split into more commits (or PRs), style nits, etc. I will add a few comments/questions inline. Thank you!
Fixes#128848
Don't leave debug locations for constants sitting on the builder indefinitely
Because constants are currently emitted *before* the prologue, leaving the debug location on the IRBuilder spills onto other instructions in the prologue and messes up both line numbers as well as the point LLVM chooses to be the prologue end.
Example LLVM IR (irrelevant IR elided):
Before:
```
define internal { i64, i64 } `@_ZN3tmp3Foo18var_return_opt_try17he02116165b0fc08cE(ptr` align 8 %self) !dbg !347 { start:
%self.dbg.spill = alloca [8 x i8], align 8
%_0 = alloca [16 x i8], align 8
%residual.dbg.spill = alloca [0 x i8], align 1
#dbg_declare(ptr %residual.dbg.spill, !353, !DIExpression(), !357)
store ptr %self, ptr %self.dbg.spill, align 8, !dbg !357
#dbg_declare(ptr %self.dbg.spill, !350, !DIExpression(), !358)
```
After:
```
define internal { i64, i64 } `@_ZN3tmp3Foo18var_return_opt_try17h00b17d08874ddd90E(ptr` align 8 %self) !dbg !347 { start:
%self.dbg.spill = alloca [8 x i8], align 8
%_0 = alloca [16 x i8], align 8
%residual.dbg.spill = alloca [0 x i8], align 1
#dbg_declare(ptr %residual.dbg.spill, !353, !DIExpression(), !357)
store ptr %self, ptr %self.dbg.spill, align 8
#dbg_declare(ptr %self.dbg.spill, !350, !DIExpression(), !358)
```
Note in particular how !357 from %residual.dbg.spill's dbg_declare no longer falls through onto the store to %self.dbg.spill. This fixes argument values at entry when the constant is a ZST (e.g. `<Option as Try>::Residual`). This fixes#130003 (but note that it does *not* fix issues with argument values and non-ZST constants, which emit their own stores that have debug info on them, like #128945).
r? `@michaelwoerister`
- Replace non-standard names like 's, 'p, 'rg, 'ck, 'parent, 'this, and
'me with vanilla 'a. These are cases where the original name isn't
really any more informative than 'a.
- Replace names like 'cx, 'mir, and 'body with vanilla 'a when the lifetime
applies to multiple fields and so the original lifetime name isn't
really accurate.
- Put 'tcx last in lifetime lists, and 'a before 'b.
Rescope temp lifetime in if-let into IfElse with migration lint
Tracking issue #124085
This PR shortens the temporary lifetime to cover only the pattern matching and consequent branch of a `if let`.
At the expression location, means that the lifetime is shortened from previously the deepest enclosing block or statement in Edition 2021. This warrants an Edition change.
Coming with the Edition change, this patch also implements an edition lint to warn about the change and a safe rewrite suggestion to preserve the 2021 semantics in most cases.
Related to #103108.
Related crater runs: https://github.com/rust-lang/rust/pull/129466.
Fix anon const def-creation when macros are involved
Fixes#128016.
Ever since #125915, some `ast::AnonConst`s turn into `hir::ConstArgKind::Path`s,
which don't have associated `DefId`s. To deal with the fact that we don't have
resolution information in `DefCollector`, we decided to implement a process
where if the anon const *appeared* to be trivial (i.e., `N` or `{ N }`), we
would avoid creating a def for it in `DefCollector`. If later, in AST lowering,
we realized it turned out to be a unit struct literal, or we were lowering it
to something that didn't use `hir::ConstArg`, we'd create its def there.
However, let's say we have a macro `m!()` that expands to a reference to a free
constant `FOO`. If we use `m!()` in the body of an anon const (e.g., `Foo<{ m!() }>`),
then in def collection, it appears to be a nontrivial anon const and we create
a def. But the macro expands to something that looks like a trivial const arg,
but is not, so in AST lowering we "fix" the mistake we assumed def collection
made and create a def for it. This causes a duplicate definition ICE.
The long-term fix for this is to delay the creation of defs for all expression-like
nodes until AST lowering (see #128844 for an incomplete attempt at this). This
would avoid issues like this one that are caused by hacky workarounds. However,
doing this uncovers a pre-existing bug with opaque types that is quite involved
to fix (see #129023).
In the meantime, this PR fixes the bug by delaying def creation for anon consts
whose bodies are macro invocations until after we expand the macro and know
what is inside it. This is accomplished by adding information to create the
anon const's def to the data in `Resolver.invocation_parents`.
r? `@BoxyUwU`
No analysis needs `Copy`, and `MaybeBorrowedLocals` is the only analysis
that needs `Clone`. In `locals_live_across_suspend_points` it gets
cloned so it can be used within a `MaybeRequiresStorage`.
...and remove the `const_arg_path` feature gate as a result. It was only
a stopgap measure to fix the regression that the new lowering introduced
(which should now be fixed by this PR).
Ever since #125915, some `ast::AnonConst`s turn into `hir::ConstArgKind::Path`s,
which don't have associated `DefId`s. To deal with the fact that we don't have
resolution information in `DefCollector`, we decided to implement a process
where if the anon const *appeared* to be trivial (i.e., `N` or `{ N }`), we
would avoid creating a def for it in `DefCollector`. If later, in AST lowering,
we realized it turned out to be a unit struct literal, or we were lowering it
to something that didn't use `hir::ConstArg`, we'd create its def there.
However, let's say we have a macro `m!()` that expands to a reference to a free
constant `FOO`. If we use `m!()` in the body of an anon const (e.g., `Foo<{ m!() }>`),
then in def collection, it appears to be a nontrivial anon const and we create
a def. But the macro expands to something that looks like a trivial const arg,
but is not, so in AST lowering we "fix" the mistake we assumed def collection
made and create a def for it. This causes a duplicate definition ICE.
The ideal long-term fix for this is a bit unclear. One option is to delay def
creation for all expression-like nodes until AST lowering (see #128844 for an
incomplete attempt at this). This would avoid issues like this one that are
caused by hacky workarounds. However, this approach has some downsides as well,
and the best approach is yet to be determined.
In the meantime, this PR fixes the bug by delaying def creation for anon consts
whose bodies are macro invocations until after we expand the macro and know
what is inside it. This is accomplished by adding information to create the
anon const's def to the data in `Resolver.invocation_parents`.
more eagerly discard constraints on overflow
We always discard the results of overflowing goals inside of the trait solver. We previously did so when instantiating the response in `evaluate_goal`. Canonicalizing results only to later discard them is also inefficient 🤷
It's simpler and nicer to debug to eagerly discard constraints inside of the query itself.
r? ``@compiler-errors``
coverage: Simplify creation of sum counters
A small and self-contained improvement, extracted from some larger changes that I'm still working on.
Ultimately I want to avoid creating these sum counter-expressions in some cases (in favour of just adding physical counters directly to the nodes we care about), so a good incremental move towards that is splitting the “gather edge counters” step out from the ”build a sum of those counters” step.
Creating an extra intermediate vector should have negligible cost (and coverage isn't exercised by the benchmark suite anyway). The removed logging is redundant with the `#[instrument(..)]` logging we already have on the underlying method calls.
Introduce `'ra` lifetime name.
`rustc_resolve` allocates many things in `ResolverArenas`. The lifetime used for references into the arena is mostly `'a`, and sometimes `'b`.
This commit changes it to `'rslv`, which is much more descriptive. The commit also changes the order of lifetimes on a couple of structs so that '`rslv` is second last, before `'tcx`, and does other minor renamings such as `'r` to `'a`.
r? ``@petrochenkov``
cc ``@oli-obk``
some const cleanup: remove unnecessary attributes, add const-hack indications
I learned that we use `FIXME(const-hack)` on top of the "const-hack" label. That seems much better since it marks the right place in the code and moves around with the code. So I went through the PRs with that label and added appropriate FIXMEs in the code. IMO this means we can then remove the label -- Cc ``@rust-lang/wg-const-eval.``
I also noticed some const stability attributes that don't do anything useful, and removed them.
r? ``@fee1-dead``
Properly report error on `const gen fn`
Fixes#130232
Also removes some (what I thought were unused) functions, and fixes a bug in clippy where we considered `gen fn` to be the same as `fn` because it was only built to consider asyncness.
Fix `clippy::useless_conversion`
Self-explanatory. Probably the last clippy change I'll actually put up since this is the only other one I've actually seen in the wild.
Simplify some nested `if` statements
Applies some but not all instances of `clippy::collapsible_if`. Some ended up looking worse afterwards, though, so I left those out. Also applies instances of `clippy::collapsible_else_if`
Review with whitespace disabled please.
Fix default/minimum deployment target for Aarch64 simulator targets
The minimum that `rustc` encoded did not match [the version in Clang](https://github.com/llvm/llvm-project/blob/llvmorg-18.1.8/llvm/lib/TargetParser/Triple.cpp#L1900-L1932), and that meant that that when linking, Clang ended up bumping the version. See https://github.com/rust-lang/rust/issues/129432 for more motivation behind this change.
Specifically, this PR sets the correct deployment target of the following targets:
- `aarch64-apple-ios-sim` from 10.0 to 14.0
- `aarch64-apple-tvos-sim` from 10.0 to 14.0
- `aarch64-apple-watchos-sim` from 5.0 to 7.0
- `aarch64-apple-ios-macabi` from 13.1 to 14.0
I have chosen not to document the `-sim` changes in the platform support docs, as it is fundamentally uninteresting; the normal targets (e.g. `aarch64-apple-ios`) still have the same deployment target, and that's what developers should actually target.
r? compiler
CC `@BlackHoleFox`
Pass deployment target when linking with CC on Apple targets
This PR effectively implements what's also being considered in the `cc` crate [here](https://github.com/rust-lang/cc-rs/issues/1030#issuecomment-2051020649), that is:
- When linking macOS targets with CC, pass the `-mmacosx-version-min=.` option to specify the desired deployment target. Also, no longer pass `-m32`/`-m64`, these are redundant since we already pass `-arch`.
- When linking with CC on iOS, tvOS, watchOS and visionOS, only pass `-target` (we assume for these targets that CC forwards to Clang).
This is required to get the linker to emit the correct `LC_BUILD_VERSION` of the final binary. See https://github.com/rust-lang/rust/issues/129432 for more motivation behind this change.
r? compiler
CC `@BlackHoleFox`
The Rust LoongArch targets have been using the default LLVM code model
so far, which is "small" in LLVM-speak and "normal" in LoongArch-speak.
As described in the "Code Model" section of LoongArch ELF psABI spec
v20231219 [1], one can only make function calls as far as ±128MiB with
the "normal" code model; this is insufficient for very large software
containing Rust components that needs to be linked into the big text
section, such as Chromium.
Because:
* we do not want to ask users to recompile std if they are to build
such software,
* objects compiled with larger code models can be linked with those
with smaller code models without problems, and
* the "medium" code model is comparable to the "small"/"normal" one
performance-wise (same data access pattern; each function call
becomes 2-insn long and indirect, but this may be relaxed back into
the direct 1-insn form in a future LLVM version), but is able to
perform function calls within ±128GiB,
it is better to just switch the targets to the "medium" code model,
which is also "medium" in LLVM-speak.
[1]: https://github.com/loongson/la-abi-specs/blob/v2.30/laelf.adoc#code-models
Co-authored-by: WANG Rui <wangrui@loongson.cn>
Add -Z small-data-threshold
This flag allows specifying the threshold size above which LLVM should not consider placing small objects in a `.sdata` or `.sbss` section.
Support is indicated in the target options via the
small-data-threshold-support target option, which can indicate either an
LLVM argument or an LLVM module flag. To avoid duplicate specifications
in a large number of targets, the default value for support is
DefaultForArch, which is translated to a concrete value according to the
target's architecture.
Use the same span for attributes and Try expansion of ?
This is needed for Clippy to know that the `#[allow(unused)]` attributes added by the expansion of `?` are part of the desugaring, and that they do not come from the user code.
rust-lang/rust-clippy#13380 exhibits a manifestation of this problem and will be fixed by this change.
miri: fix overflow detection for unsigned pointer offset
This is the Miri part of https://github.com/rust-lang/rust/pull/130229. This is already UB in codegen so we better make Miri detect it; updating the docs may take time if we have to follow some approval process, but let's make Miri match reality ASAP.
r? ``@scottmcm``
Don't warn empty branches unreachable for now
The [stabilization](https://github.com/rust-lang/rust/pull/122792) of `min_exhaustive_patterns` updated the `unreachable_pattern` lint to trigger on empty arms too. This has caused some amount of churn, and imposes an unjoyful `#[allow(unreachable_patterns)]` onto library authors who want to stay backwards-compatible.
While I think the lint should eventually cover these cases, for transition's sake I'd prefer to revert linting to what it was prior to stabilization, at least for now.
Fixes https://github.com/rust-lang/rust/issues/129031.
r? ``@compiler-errors``
`rustc_resolve` allocates many things in `ResolverArenas`. The lifetime
used for references into the arena is mostly `'a`, and sometimes `'b`.
This commit changes it to `'ra`, which is much more descriptive. The
commit also changes the order of lifetimes on a couple of structs so
that '`ra` is second last, before `'tcx`, and does other minor
renamings such as `'r` to `'a`.
This is needed for Clippy to know that the `#[allow(unused)]` attributes
added by the expansion of `?` are part of the desugaring, and that they
do not come from the user code.
rust-lang/rust-clippy#13380 exhibits a manifestation of this problem.
Rollup of 9 pull requests
Successful merges:
- #129260 (Don't suggest adding return type for closures with default return type)
- #129520 (Suggest the correct pattern syntax on usage of unit variant pattern for a struct variant)
- #129866 (Clarify documentation labelling and definitions for std::collections)
- #130123 (Report the `note` when specified in `diagnostic::on_unimplemented`)
- #130161 (refactor merge base logic and fix `x fmt`)
- #130206 (Map `WSAEDQUOT` to `ErrorKind::FilesystemQuotaExceeded`)
- #130207 (Map `ERROR_CANT_RESOLVE_FILENAME` to `ErrorKind::FilesystemLoop`)
- #130219 (Fix false positive with `missing_docs` and `#[test]`)
- #130221 (Make SearchPath::new public)
r? `@ghost`
`@rustbot` modify labels: rollup
Make SearchPath::new public
I'm writing a tool that uses `rustc_interface`, and would like to construct `SearchPath` with its `new` method.
As all three fields in `SearchPath` are public anyway, the proposed change should not change the privacy or encapsulation of the struct.
Fix false positive with `missing_docs` and `#[test]`
Since #130025, the compiler don't ignore missing_docs when compiling the tests. But there is now a false positive warning for every `#[test]`
For example, this code
```rust
//! Crate docs
fn just_a_test() {}
```
Would emit this warning when running `cargo test`
```
warning: missing documentation for a constant
--> src/lib.rs:5:1
|
4 | #[test]
| ------- in this procedural macro expansion
5 | fn just_a_test() {}
| ^^^^^^^^^^^^^^^^^^^
```
Report the `note` when specified in `diagnostic::on_unimplemented`
Before this PR the `note` field was completely ignored for some reason, now it is shown (I think) correctly during the hir typechecking phase.
1. Report the `note` when specified in `diagnostic::on_unimplemented`
2. Added a test for unimplemented trait diagnostic
3. Added a test for custom unimplemented trait diagnostic
Close#130084
P.S. This is my first PR to rustc.
Suggest the correct pattern syntax on usage of unit variant pattern for a struct variant
Closes#126243
I add a suggestion on usage of unit variant pattern for a struct variant.
Since #130025, the compiler don't ignore missing_docs when compiling the tests.
But there is now a false positive warning for every `#[test]`
For example, this code
```rust
//! Crate docs
fn just_a_test() {}
```
Would emit this warning when running `cargo test`
```
warning: missing documentation for a constant
--> src/lib.rs:5:1
|
4 | #[test]
| ------- in this procedural macro expansion
5 | fn just_a_test() {}
| ^^^^^^^^^^^^^^^^^^^
```
generalize: track relevant info in cache key
This was previously theoretically incomplete as we could incorrectly generalize as if the type was in an invariant context even though we're in a covariant one. Similar with the `in_alias` flag.
r? `@compiler-errors`
Enumerate lint expectations using AttrId
This PR implements the idea I outlined in https://github.com/rust-lang/rust/issues/127884#issuecomment-2240338547
We can uniquely identify a lint expectation `#[expect(lint0, lint1...)]` using the `AttrId` and the index of the lint inside the attribute. This PR uses this property in `check_expectations`.
In addition, this PR stops stashing expected diagnostics to wait for the unstable -> stable `LintExpectationId` mapping: if the lint is emitted with an unstable attribute, it must have been emitted by an `eval_always` query (like inside the resolver), so won't be loaded from cache. Decoding an `AttrId` from the on-disk cache ICEs, so we have no risk of accidentally checking an expectation.
Fixes https://github.com/rust-lang/rust/issues/127884
cc `@xFrednet`
This flag allows specifying the threshold size above which LLVM should
not consider placing small objects in a .sdata or .sbss section.
Support is indicated in the target options via the
small-data-threshold-support target option, which can indicate either an
LLVM argument or an LLVM module flag. To avoid duplicate specifications
in a large number of targets, the default value for support is
DefaultForArch, which is translated to a concrete value according to the
target's architecture.
coverage: Clean up terminology in counter creation
Some of the terminology in this module is confusing, or has drifted out of sync with other parts of the coverage code.
This PR therefore renames some variables and methods, and adjusts comments and debug logging statements, to make things clearer and more consistent.
No functional changes, other than some small tweaks to debug logging.
Also emit `missing_docs` lint with `--test` to fulfil expectations
This PR removes the "test harness" suppression of the `missing_docs` lint to be able to fulfil `#[expect]` (expectations) as it is now "relevant".
I think the goal was to maybe avoid false-positive while linting on public items under `#[cfg(test)]` but with effective visibility we should no longer have any false-positive.
Another possibility would be to query the lint level and only emit the lint if it's of expect level, but that is even more hacky.
Fixes https://github.com/rust-lang/rust/issues/130021
try-job: x86_64-gnu-aux
Rollup of 11 pull requests
Successful merges:
- #128316 (Stabilize most of `io_error_more`)
- #129473 (use `download-ci-llvm=true` in the default compiler config)
- #129529 (Add test to build crates used by r-a on stable)
- #129981 (Remove `serialized_bitcode` from `LtoModuleCodegen`.)
- #130094 (Inform the solver if evaluation is concurrent)
- #130132 ([illumos] enable SIGSEGV handler to detect stack overflows)
- #130146 (bootstrap `naked_asm!` for `compiler-builtins`)
- #130149 (Helper function for formatting with `LifetimeSuggestionPosition`)
- #130152 (adapt a test for llvm 20)
- #130162 (bump download-ci-llvm-stamp)
- #130164 (move some const fn out of the const_ptr_as_ref feature)
r? `@ghost`
`@rustbot` modify labels: rollup
bootstrap `naked_asm!` for `compiler-builtins`
tracking issue: https://github.com/rust-lang/rust/issues/90957
parent PR: https://github.com/rust-lang/rust/pull/128651
in this PR, `naked_asm!` is added as an alias for `asm!` with one difference: `options(noreturn)` is always enabled by `naked_asm!`. That makes it future-compatible for when `naked_asm!` starts disallowing `options(noreturn)` later.
The `naked_asm!` macro must be introduced first so that we can upgrade `compiler-builtins` to use it, and can then change the implementation of `naked_asm!` in https://github.com/rust-lang/rust/pull/128651
I've added some usages for `naked_asm!` in the tests, so we can be confident that it works, but I've left upgrading the whole test suite to the parent PR.
r? ``@Amanieu``
Inform the solver if evaluation is concurrent
Parallel compilation of a program can cause unexpected event sequencing. Inform the solver when this is true so it can skip invalid asserts.
Add test to build crates used by r-a on stable
r? ````````@Kobzol````````
I've opened other PRs for this one to work and they've landed already. I cherry-picked your commit, and added the last remaining pieces we needed I think.
interpret: make typed copies lossy wrt provenance and padding
A "typed copy" in Rust can be a lossy process: when copying at type `usize` (or any other non-pointer type), if the original memory had any provenance, that provenance is lost. When copying at pointer type, if the original memory had partial provenance (i.e., not the same provenance for all bytes), that provenance is lost. When copying any type with padding, the contents of padding are lost.
This PR equips our validity-checking pass with the ability to reset provenance and padding according to those rules. Can be reviewed commit-by-commit. The first three commits are just preparation without any functional change.
Fixes https://github.com/rust-lang/miri/issues/845
Fixes https://github.com/rust-lang/miri/issues/2182
In all cases the struct can own the relevant thing instead of having a
reference to it. This makes the code simpler, and in some cases removes
a struct lifetime.
These are all functions with a single callsite, where having a separate
function does nothing to help with readability. These changes make the
code a little shorter and easier to read.
Parallel compilation of a program can cause unexpected event sequencing.
Inform the solver when this is true so it can skip invalid asserts, then
assert replaced solutions are equal if Some
Rollup of 9 pull requests
Successful merges:
- #129929 (`rustc_mir_transform` cleanups, round 2)
- #130022 (Dataflow/borrowck lifetime cleanups)
- #130064 (fix ICE in CMSE type validation)
- #130067 (Remove redundant check in `symlink_hard_link` test)
- #130131 (Print a helpful message if any tests were skipped for being up-to-date)
- #130137 (Fix ICE caused by missing span in a region error)
- #130153 (use verbose flag as a default value for `rust.verbose-tests`)
- #130154 (Stabilize `char::MIN`)
- #130158 (Update books)
r? `@ghost`
`@rustbot` modify labels: rollup
Distribute rustc_codegen_cranelift for Windows
With support for raw-dylib recently added to cg_clif, and inline assembly support working on Windows for quite a while now, all blockers for distributing cg_clif on Windows that I mentioned in https://github.com/rust-lang/rust/pull/81746#issuecomment-1774099637 are fixed now.
When linking macOS targets with cc, pass the `-mmacosx-version-min=.`
option to specify the desired deployment target. Also, no longer pass
`-m32`/`-m64`, these are redundant since we already pass `-arch`.
When linking with cc on other Apple targets, always pass `-target`.
(We assume for these targets that cc => clang).
The minimum that `rustc` encoded did not match the version in Clang, and
that meant that that when linking, we ended up bumping the version.
Specifically, this sets the correct deployment target of the following
simulator and Mac Catalyst targets:
- `aarch64-apple-ios-sim` from 10.0 to 14.0
- `aarch64-apple-tvos-sim` from 10.0 to 14.0
- `aarch64-apple-watchos-sim` from 5.0 to 7.0
- `aarch64-apple-ios-macabi` from 13.1 to 14.0
I have chosen to not document the simulator target versions in the
platform support docs, as it is fundamentally uninteresting; the normal
targets (e.g. `aarch64-apple-ios`, `aarch64-apple-tvos`) still have the
same deployment target as before, and that's what developers should
actually target.
in this commit, `naked_asm!` is an alias for `asm!` with one difference: `options(noreturn)` is always enabled by `naked_asm!`. That makes it future-compatible for when `naked_asm!` starts disallowing `options(noreturn)` later.
Use sysroot crates maximally in `rustc_codegen_gcc`.
This shrinks `compiler/rustc_codegen_gcc/Cargo.lock` quite a bit. The only remaining dependencies in `compiler/rustc_codegen_gcc/Cargo.lock` are `gccjit`, `lang_tester`, and `boml`, all of which aren't used in any other compiler crates.
The commit also reorders and adds comments to the `extern crate` items so they match those in miri.
r? ```@Mark-Simulacrum```
It's a very thin wrapper that pairs `MoveDataBuilder` with a `Location`,
and it has four lifetime arguments. This commit removes it by just
adding a `Location` to `MoveDataBuilder`.
There are four related dataflow structs: `MaybeInitializedPlaces`,
`MaybeUninitializedPlaces`, and `EverInitializedPlaces`,
`DefinitelyInitializedPlaces`. They all have a `&Body` and a
`&MoveData<'tcx>` field. The first three use different lifetimes for the
two fields, but the last one uses the same lifetime for both.
This commit changes the first three to use the same lifetime, removing
the need for one of the lifetimes. Other structs that also lose a
lifetime as a result of this are `LivenessContext`, `LivenessResults`,
`InitializationData`.
It then does similar things in various other structs.
Currently it constructs two vectors `calls_to_terminated` and
`cleanups_to_remove` in the main loop, and then processes them after the
main loop. But the processing can be done in the main loop, avoiding the
need for the vectors.
Correctly handle stability of `#[diagnostic]` attributes
This commit changes the way we treat the stability of attributes in the
`#[diagnostic]` namespace. Instead of relaying on ad-hoc checks to
ensure at call side that a certain attribute is really usable at that
location it centralises the logic to one place. For diagnostic
attributes comming from other crates it just skips serializing
attributes that are not stable and that do not have the corresponding
feature enabled. For attributes from the current crate we can just use
the feature information provided by `TyCtx`.
r? `@compiler-errors`