[mir-opt] GVN some more transmute cases
We already did `Transmute`-then-`PtrToPtr`; this adds the nearly-identical `PtrToPtr`-then-`Transmute`.
It also adds `transmute(Foo(x))` → `transmute(x)`, when `Foo` is a single-field transparent type. That's useful for things like `NonNull { pointer: p }.as_ptr()`. It also detects when a `Transmute` is just an identity-for-the-value `PtrCast` between different raw pointer types, to help such things fold with other GVN passes.
Found these as I was looking at <https://github.com/rust-lang/compiler-team/issues/807>-related changes. This also removes the questionably-useful "turn a transmute into a field projection" part of instsimplify (which I added ages ago without an obvious need for it) since that would just put back the field projections that MCP807 is trying to ban.
r? mir-opt
Rollup of 6 pull requests
Successful merges:
- #128110 (Suggest Replacing Comma with Semicolon in Incorrect Repeat Expressions)
- #134609 (Add new `{x86_64,i686}-win7-windows-gnu` targets)
- #134875 (Implement `const Destruct` in old solver)
- #135221 (Include rustc and rustdoc book in replace-version-placeholder)
- #135231 (bootstrap: Add more comments to some of the test steps)
- #135256 (Move `mod cargo` below the import statements)
Failed merges:
- #135195 (Make `lit_to_mir_constant` and `lit_to_const` infallible)
r? `@ghost`
`@rustbot` modify labels: rollup
bootstrap: Add more comments to some of the test steps
Some of the test steps have names that don't clearly indicate what they actually do.
While there is ongoing experimental work to actually rename the steps (e.g. #135071), that's dependent on figuring out what the new names should actually be. In the meantime, we can still improve things by adding comments to help describe the steps, which will remain useful even after any renaming.
Include rustc and rustdoc book in replace-version-placeholder
This PR includes the *(stable)* rustc and rustdoc books which might contain `CURRENT_RUSTC_VERSION` that should be replaced when branching beta. Include them so they are not forgotten.
I didn't include any other folder or books as they don't strike me as relevant for it and might be problematic in the future if some of the submodules are turned into subtree, because we have places where we wouldn't want to replace them.
cf. https://github.com/rust-lang/rust/pull/135163#issuecomment-2574694931
cc `@pietroalbini`
Implement `const Destruct` in old solver
Self-explanatory. Not totally settled that this is the best structure for built-in trait impls for effect goals in the new solver, but it's almost certainly the simplest.
r? lcnr or re-roll
Add new `{x86_64,i686}-win7-windows-gnu` targets
These are in symmetry with `{x86_64,i686}-win7-windows-msvc`.
> ## Tier 3 target policy
>
> At this tier, the Rust project provides no official support for a target, so we
> place minimal requirements on the introduction of targets.
>
> A proposed new tier 3 target must be reviewed and approved by a member of the
> compiler team based on these requirements. The reviewer may choose to gauge
> broader compiler team consensus via a [Major Change Proposal (MCP)][https://forge.rust-lang.org/compiler/mcp.html].
>
> A proposed target or target-specific patch that substantially changes code
> shared with other targets (not just target-specific code) must be reviewed and
> approved by the appropriate team for that shared code before acceptance.
>
> - A tier 3 target must have a designated developer or developers (the "target
> maintainers") on record to be CCed when issues arise regarding the target.
> (The mechanism to track and CC such developers may evolve over time.)
This is me, `@tbu-` on github.
> - Targets must use naming consistent with any existing targets; for instance, a
> target for the same CPU or OS as an existing Rust target should use the same
> name for that CPU or OS. Targets should normally use the same names and
> naming conventions as used elsewhere in the broader ecosystem beyond Rust
> (such as in other toolchains), unless they have a very good reason to
> diverge. Changing the name of a target can be highly disruptive, especially
> once the target reaches a higher tier, so getting the name right is important
> even for a tier 3 target.
> - Target names should not introduce undue confusion or ambiguity unless
> absolutely necessary to maintain ecosystem compatibility. For example, if
> the name of the target makes people extremely likely to form incorrect
> beliefs about what it targets, the name should be changed or augmented to
> disambiguate it.
> - If possible, use only letters, numbers, dashes and underscores for the name.
> Periods (`.`) are known to cause issues in Cargo.
Consistent with `{x86_64,i686}-win7-windows-msvc`, see also #118150.
> - Tier 3 targets may have unusual requirements to build or use, but must not
> create legal issues or impose onerous legal terms for the Rust project or for
> Rust developers or users.
> - The target must not introduce license incompatibilities.
> - Anything added to the Rust repository must be under the standard Rust
> license (`MIT OR Apache-2.0`).
> - The target must not cause the Rust tools or libraries built for any other
> host (even when supporting cross-compilation to the target) to depend
> on any new dependency less permissive than the Rust licensing policy. This
> applies whether the dependency is a Rust crate that would require adding
> new license exceptions (as specified by the `tidy` tool in the
> rust-lang/rust repository), or whether the dependency is a native library
> or binary. In other words, the introduction of the target must not cause a
> user installing or running a version of Rust or the Rust tools to be
> subject to any new license requirements.
> - Compiling, linking, and emitting functional binaries, libraries, or other
> code for the target (whether hosted on the target itself or cross-compiling
> from another target) must not depend on proprietary (non-FOSS) libraries.
> Host tools built for the target itself may depend on the ordinary runtime
> libraries supplied by the platform and commonly used by other applications
> built for the target, but those libraries must not be required for code
> generation for the target; cross-compilation to the target must not require
> such libraries at all. For instance, `rustc` built for the target may
> depend on a common proprietary C runtime library or console output library,
> but must not depend on a proprietary code generation library or code
> optimization library. Rust's license permits such combinations, but the
> Rust project has no interest in maintaining such combinations within the
> scope of Rust itself, even at tier 3.
> - "onerous" here is an intentionally subjective term. At a minimum, "onerous"
> legal/licensing terms include but are *not* limited to: non-disclosure
> requirements, non-compete requirements, contributor license agreements
> (CLAs) or equivalent, "non-commercial"/"research-only"/etc terms,
> requirements conditional on the employer or employment of any particular
> Rust developers, revocable terms, any requirements that create liability
> for the Rust project or its developers or users, or any requirements that
> adversely affect the livelihood or prospects of the Rust project or its
> developers or users.
AFAICT, it's the same legal situation as the tier 1 `{x86_64,i686}-pc-windows-gnu`.
> - Neither this policy nor any decisions made regarding targets shall create any
> binding agreement or estoppel by any party. If any member of an approving
> Rust team serves as one of the maintainers of a target, or has any legal or
> employment requirement (explicit or implicit) that might affect their
> decisions regarding a target, they must recuse themselves from any approval
> decisions regarding the target's tier status, though they may otherwise
> participate in discussions.
> - This requirement does not prevent part or all of this policy from being
> cited in an explicit contract or work agreement (e.g. to implement or
> maintain support for a target). This requirement exists to ensure that a
> developer or team responsible for reviewing and approving a target does not
> face any legal threats or obligations that would prevent them from freely
> exercising their judgment in such approval, even if such judgment involves
> subjective matters or goes beyond the letter of these requirements.
Understood.
> - Tier 3 targets should attempt to implement as much of the standard libraries
> as possible and appropriate (`core` for most targets, `alloc` for targets
> that can support dynamic memory allocation, `std` for targets with an
> operating system or equivalent layer of system-provided functionality), but
> may leave some code unimplemented (either unavailable or stubbed out as
> appropriate), whether because the target makes it impossible to implement or
> challenging to implement. The authors of pull requests are not obligated to
> avoid calling any portions of the standard library on the basis of a tier 3
> target not implementing those portions.
This target supports the whole libstd surface, since it's essentially reusing all of the x86_64-pc-windows-gnu target. Understood.
> - The target must provide documentation for the Rust community explaining how
> to build for the target, using cross-compilation if possible. If the target
> supports running binaries, or running tests (even if they do not pass), the
> documentation must explain how to run such binaries or tests for the target,
> using emulation if possible or dedicated hardware if necessary.
I tried to write some documentation on that.
> - Tier 3 targets must not impose burden on the authors of pull requests, or
> other developers in the community, to maintain the target. In particular,
> do not post comments (automated or manual) on a PR that derail or suggest a
> block on the PR based on a tier 3 target. Do not send automated messages or
> notifications (via any medium, including via ``@`)` to a PR author or others
> involved with a PR regarding a tier 3 target, unless they have opted into
> such messages.
> - Backlinks such as those generated by the issue/PR tracker when linking to
> an issue or PR are not considered a violation of this policy, within
> reason. However, such messages (even on a separate repository) must not
> generate notifications to anyone involved with a PR who has not requested
> such notifications.
Understood.
> - Patches adding or updating tier 3 targets must not break any existing tier 2
> or tier 1 target, and must not knowingly break another tier 3 target without
> approval of either the compiler team or the maintainers of the other tier 3
> target.
> - In particular, this may come up when working on closely related targets,
> such as variations of the same architecture with different features. Avoid
> introducing unconditional uses of features that another variation of the
> target may not have; use conditional compilation or runtime detection, as
> appropriate, to let each target run code supported by that target.
> - Tier 3 targets must be able to produce assembly using at least one of
> rustc's supported backends from any host target. (Having support in a fork
> of the backend is not sufficient, it must be upstream.)
Understood.
> If a tier 3 target stops meeting these requirements, or the target maintainers
> no longer have interest or time, or the target shows no signs of activity and
> has not built for some time, or removing the target would improve the quality
> of the Rust codebase, we may post a PR to remove it; any such PR will be CCed
> to the target maintainers (and potentially other people who have previously
> worked on the target), to check potential interest in improving the situation.
>
Understood.
r? compiler-team
Suggest Replacing Comma with Semicolon in Incorrect Repeat Expressions
Fixes#80173
This PR detects typos in repeat expressions like `["_", 10]` and `vec![String::new(), 10]` and suggests replacing comma with semicolon.
Also, improves code in other place by adding doc comments and making use of a helper function to check if a type implements `Clone`.
References:
1. For `vec![T; N]`: https://doc.rust-lang.org/std/macro.vec.html
2. For `[T; N]`: https://doc.rust-lang.org/std/primitive.array.html
We already did `Transmute`-then-`PtrToPtr`; this adds the nearly-identical `PtrToPtr`-then-`Transmute`.
It also adds `transmute(Foo(x))` → `transmute(x)`, when `Foo` is a single-field transparent type. That's useful for things like `NonNull { pointer: p }.as_ptr()`.
Found these as I was looking at MCP807-related changes.
Revert #131365
This PR reverts #131365, following the revert we did on the beta branches for both 1.84 and 1.85.
While the PR passes CI successfully on master, as soon as we branch off beta it starts failing in the newly created beta branch. This caused the release team to revert it for both 1.84 and 1.85, and if nothing is done it would continue being reverted every cycle.
`@heiseish` (PR author) feel free to submit the PR again in the future: this revert doesn't represent the release team rejecting your change, but just a (hopefully temporary!) revert to ensure future beta branches can be created without reverting it each time.
When submitting the PR again, I recommend you test your changes by configuring `rust.channel` to both `nightly` and `beta` in your `config.toml`. You can see the latest failure [here](https://github.com/rust-lang/rust/pull/135163#issuecomment-2576373995).
A couple simple borrowck cleanups
This PR has a couple simple renamings:
- it's been a long time since the mapping from `Location`s to `PointIndex`es was extracted from `RegionElements` into the `DenseLocationMap`, but only the types were renamed at the time. borrowck still refers to this map as `elements`. That's confusing, especially since sometimes we also use the mapping via `LivenessValues`, and makes more sense as `location_map` instead.
- to clarify `LocationTable` is not as general as it sounds, and is only for datalog polonius. In this branch I didn't rename the handful of `location_table` fields and params to `polonius_table`, but can do that to differentiate it even more from `location_map`. I did try it locally and it looks worthwhile, so if you'd prefer I can also push it here. (Or we could even switch these datalog types and fields to even more explicit names)
- to clarify the incomprehensible `AllFacts`, it is renamed to `PoloniusFacts`. These can be referred to as `facts` within the legacy polonius module, but as `polonius_facts` outside of it to make it clear that they're not about NLLs (nor are they about in-tree polonius but that'll be magically fixed when they're removed in the future)
r? `@matthewjasper`
Exhaustively handle expressions in patterns
We currently have this invariant in HIR that a `PatKind::Lit` or a `PatKind::Range` only contains
* `ExprKind::Lit`
* `ExprKind::UnOp(Neg, ExprKind::Lit)`
* `ExprKind::Path`
* `ExprKind::ConstBlock`
So I made `PatKind::Lit` and `PatKind::Range` stop containing `Expr`, and instead created a `PatLit` type whose `kind` enum only contains those variants.
The only place code got more complicated was in clippy, as it couldn't share as much anymore with `Expr` handling
It may be interesting on merging `ExprKind::{Path,Lit,ConstBlock}` in the future and using the same `PatLit` type (under a new name).
Then it should also be easier to eliminate any and all `UnOp(Neg, Lit) | Lit` matching that we have across the compiler. Some day we should fold the negation into the literal itself and just store it on the numeric literals
Run borrowck tests on BIDs and emit tail-expr-drop-order lints for violations
Fix#132861
r? `@nikomatsakis`
cc `@compiler-errors`
This patch enlarges the scope where the `tail-expr-drop-order` lint applies, so that all locals involved in tail expressions are inspected. This is necessary to run borrow-checking to capture the cases where it used to compile under Edition 2021 but is not going to pass borrow-checking from Edition 2024 onwards.
The way it works is to inspect each BID against the set of borrows that are still live. If the local involved in BID has a borrow index which happens to be live as well at the location of this BID statement, in the future this will be a borrow-checking violation. The lint will fire in this case.
Its original naming hides the fact that it's related to datalog
polonius, and bound to be deleted in the near future.
It also conflicts with the expected name for the actual NLL location
map, and prefixing it with its use will make the differentiation
possible.
`best_blame_constraint`: Blame better constraints when the region graph has cycles from invariance or `'static`
This fixes#132749 by changing which constraint is blamed for region errors in several cases. `best_blame_constraint` had a heuristic that tried to pinpoint the constraint causing an error by filtering out any constraints where the outliving region is unified with the ultimate target region being outlived. However, it used the SCCs of the region graph to do this, which is unreliable; in particular, if the target region is `'static`, or if there are cycles from the presence of invariant types, it was skipping over the constraints it should be blaming. As is the case in that issue, this could lead to confusing diagnostics. The simplest fix seems to work decently, judging by test stderr: this makes `best_blame_constraint` no longer filter constraints by their outliving region's SCC.
There are admittedly some quirks in the test output. In many cases, subdiagnostics that depend on the particular constraint being blamed have either started or stopped being emitted. After starting at this for quite a while, I think anything too fickle about whether it outputs based on the particular constraint being blamed should instead be looking at the constraint path as a whole, similar to what's done for [the placeholder-from-predicate note](https://github.com/rust-lang/rust/compare/master...dianne:rust:better-blame-constraints-for-static#diff-3c0de6462469af483c9ecdf2c4b00cb26192218ef2d5c62a0fde75107a74caaeR506).
Very many tests involving invariant types gained a note pointing out the types' invariance, but in a few cases it was lost. A particularly illustrative example is [tests/ui/lifetimes/copy_modulo_regions.stderr](https://github.com/rust-lang/rust/compare/master...dianne:rust:better-blame-constraints-for-static?expand=1#diff-96e1f8b29789b3c4ce2f77a5e0fba248829b97ef9d1ce39e7d2b4aa57b2cf4f0); I'd argue the new constraint is a better one to blame, but it lacks the variance diagnostic information that's elsewhere in the constraint path. If desired, I can try making that note check the whole path rather than just the blamed constraint.
The subdiagnostic [`BorrowExplanation::add_object_lifetime_default_note`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_borrowck/diagnostics/explain_borrow/enum.BorrowExplanation.html#method.add_object_lifetime_default_note) depends on a `Cast` being blamed, so [a special case](364ca7f99c) was necessary to keep it from disappearing from tests specifically testing for it. However, see the FIXME comment in that commit; I think the special case should be removed once that subdiagnostic works properly, but it's nontrivial enough to warrant a separate PR. Incidentally, this removes the note from a test where it was being added erroneously: in [tests/ui/borrowck/two-phase-surprise-no-conflict.stderr](https://github.com/rust-lang/rust/compare/master...dianne:rust:better-blame-constraints-for-static?expand=1#diff-8cf085af8203677de6575a45458c9e6b03412a927df879412adec7e4f7ff5e14), the object lifetime is explicitly provided and it's not `'static`.
"Elements" are `RegionElement`s. The dense location mapping was removed
from the element containers a while ago but didn't rename its use-sites.
Most of the old naming only used the mapping, and are better named
`location_map`.
arm: add unstable soft-float target feature
This has an actual usecase as mentioned [here](https://github.com/rust-lang/rust/issues/116344#issuecomment-2575324988), and with my recent ARM float ABI changes there shouldn't be any soundness concerns any more. We will reject enabling this feature on `hf` targets, but disabling it on non-`hf` targets is entirely fine -- the target feature refers to whether softfloat emulation is used for float instructions, and is independent of the ABI which we set separately via `llvm_floatabi`.
Cc ``@workingjubilee``
Convert typeck constraints in location-sensitive polonius
In this PR, we do a big chunk of the work of localizing regular outlives constraints.
The slightly annoying thing is handling effectful statements: usually the subset graph propagates loans at a single point between regions, and liveness propagates loans between points within a single region, but some statements have effects applied on exit.
This was also a problem before, in datalog polonius terms and Niko's solution at the time, this is about: the mid-point. The idea was to duplicate all MIR locations into two physical points, and orchestrate the effects with that. Somewhat easier to do, but double the CFG.
We've always believed we didn't _need_ midpoints in principle, as we can represent changes on exit as on happening entry to the successor, but there's some difficulty in tracking the position information at sufficient granularity through outlives relation (especially since we also have bidirectional edges and time-traveling now).
Now, that is surely what we should be doing in the future. In the mean time, I infer this from the kind of statement/terminator where an outlives constraint arose. It's not particularly complicated but some explanation will help clarify the code.
Assignments (in their various forms) are the quintessential example of these crossover cases: loans that would flow into the LHS would not be visible on entry to the point but on exit -- so we'll localize these edges to the successor. Let's look at a real-world example, involving invariance for bidirectional edges:
```rust
let mut _1: HashMap<i32, &'7 i32>;
let mut _3: &'9 mut HashMap<i32, &'10 i32>;
...
/* at bb1[3]: */ _3 = &'3 mut _1;
```
Here, typeck expectedly produces 3 outlives constraints today:
1. `'3 -> '9`
2. `'7 -> '10`
3. `'10 -> '7`
And we localize them like so,
1. `'3 -> '9` flows into the LHS and becomes: `3_bb1_3 -> 9_bb1_4`
2. `'7 -> '10` flows into the LHS and becomes: `7_bb1_3 -> 10_bb1_4`
3. `'10 -> '7` flows from the LHS and becomes: `10_bb1_4 -> 7_bb1_3` (time traveling 👌)
---
r? ``@jackh726``
To keep you entertained during the holidays I also threw in a couple of small changes removing cruft in the borrow checker.
We're actually getting there. The next PR will be the last one needed to get end-to-end tests working.
Condvar: implement wait_timeout for targets without threads
This always falls back to sleeping since there is no way to notify a condvar on a target without threads.
Even on a target that has no threads the following code is a legitimate use case:
```rust
use std::sync::{Condvar, Mutex};
use std::time::Duration;
fn main() {
let cv = Condvar::new();
let mutex = Mutex::new(());
let mut guard = mutex.lock().unwrap();
cv.notify_one();
let res;
(guard, res) = cv.wait_timeout(guard, Duration::from_secs(3)).unwrap();
assert!(res.timed_out());
}
```