Use zero for initialized Once state
By re-labeling which integer represents which internal state for `Once` we can ensure that the initialized state is the all-zero state. This is beneficial because some CPU architectures (such as Arm) have specialized instructions to specifically branch on non-zero, and checking for the initialized state is by far the most important operation.
As an example, take this:
```rust
use std::sync::atomic::{AtomicU32, Ordering};
const INIT: u32 = 3;
#[inline(never)]
#[cold]
pub fn slow(state: &AtomicU32) {
state.store(INIT, Ordering::Release);
}
pub fn ensure_init(state: &AtomicU32) {
if state.load(Ordering::Acquire) != INIT {
slow(state)
}
}
```
If `INIT` is 3 (as is currently the state for `Once`), we see the following assembly on `aarch64-apple-darwin`:
```asm
example::ensure_init::h332061368366e313:
ldapr w8, [x0]
cmp w8, #3
b.ne LBB1_2
ret
LBB1_2:
b example::slow::ha042bd6a4f33724e
```
By changing the `INIT` state to zero we get the following:
```asm
example::ensure_init::h332061368366e313:
ldapr w8, [x0]
cbnz w8, LBB1_2
ret
LBB1_2:
b example::slow::ha042bd6a4f33724e
```
So this PR saves 1 instruction every time a `LazyLock` gets accessed on platforms such as these.
bootstrap/miri: avoid rebuilds for test builds
When building Miri in its own repo, we always build with `--all-targets`:
a009612691/src/tools/miri/miri-script/src/util.rs (L167-L174)
This saves a bunch of time since some of Miri's dependencies get more features enabled by some of Miri's dev-dependencies, and they all get built twice otherwise if you do `cargo build && cargo test` (which is typically what you end up doing inside `./miri test` and also inside `./x test miri`).
This applies the same approach to bootstrap, drastically reducing the edit-compile cycle for Miri work here. :)
make `cfg_select` a builtin macro
tracking issue: https://github.com/rust-lang/rust/issues/115585
This parses mostly the same as the `macro cfg_select` version, except:
1. wrapping in double brackets is no longer supported (or needed): `cfg_select {{ /* ... */ }}` is now rejected.
2. in an expression context, the rhs is no longer wrapped in a block, so that this now works:
```rust
fn main() {
println!(cfg_select! {
unix => { "foo" }
_ => { "bar" }
});
}
```
3. a single wildcard rule is now supported: `cfg_select { _ => 1 }` now works
I've also added an error if none of the rules evaluate to true, and warnings for any arms that follow the `_` wildcard rule.
cc `@traviscross` if I'm missing any feature that should/should not be included
r? `@petrochenkov` for the macro logic details
Run `tests/rustdoc-json/attrs/target_features` on all hosts.
Makes it more convenient to test rustdoc on non x86_64. I mainly care about the aarch64 dev-desktops.
This works because rustdoc uses all target features, not just that of the target.
de-duplicate condition scoping logic between AST→HIR lowering and `ScopeTree` construction
There was some overlap between `rustc_ast_lowering::LoweringContext::lower_cond` and `rustc_hir_analysis::check::region::resolve_expr`, so I've removed the former and migrated its logic to the latter, with some simplifications.
Consequences:
- For `while` and `if` expressions' `let`-chains, this changes the `HirId`s for the `&&`s to properly correspond to their AST nodes. This is how guards were handled already.
- This makes match guards share previously-duplicated logic with `if`/`while` expressions. This will also be used by guard pattern[^1] guards.
- Aside from legacy syntax extensions (e.g. some builtin macros) that directly feed AST to the compiler, it's currently impossible to put attributes directly on `&&` operators in `let` chains[^2]. Nonetheless, attributes on `&&` operators in `let` chains in `if`/`while` expression conditions are no longer silently ignored and will be lowered.
- This no longer wraps conditions in `DropTemps`, so the HIR and THIR will be slightly smaller.
- `DesugaringKind::CondTemporary` is now gone. It's no longer applied to any spans, and all uses of it were dead since they were made to account for `if` and `while` being desugared to `match` on a boolean scrutinee.
- Should be a marginal perf improvement beyond that due to leveraging [`ScopeTree` construction](5e749eb66f/compiler/rustc_hir_analysis/src/check/region.rs (L312-L355))'s clever handling of `&&` and `||`:
- This removes some unnecessary terminating scopes that were placed around top-level `&&` and `||` operators in conditions. When lowered to MIR, logical operator chains don't create intermediate boolean temporaries, so there's no temporary to drop. The linked snippet handles wrapping the operands in terminating scopes as necessary, in case they create temporaries.
- The linked snippet takes care of letting `let` temporaries live and terminating other operands, so we don't need separate traversals of `&&` chains for that.
[^1]: rust-lang/rust#129967
[^2]: Case-by-case, here's my justification: `#[attr] e1 && e2` applies the attribute to `e1`. In `#[attr] (e1 && e2)` , the attribute is on the parentheses in the AST, plus it'd fail to parse if `e1` or `e2` contains a `let`. In `#[attr] expands_to_let_chain!()`, the attribute would already be ignored (rust-lang/rust#63221) and it'd fail to parse anyway; even if the expansion site is a condition, the expansion wouldn't be parsed with `Restrictions::ALLOW_LET`. If it *was* allowed, the notion of a "reparse context" from https://github.com/rust-lang/rust/issues/61733#issuecomment-509626449 would be necessary in order to make `let`-chains left-associative; multiple places in the compiler assume they are.
Split up the `unknown_or_malformed_diagnostic_attributes` lint
This splits up the lint into the following lint group:
- `unknown_diagnostic_attributes` - triggers if the attribute is unknown to the current compiler
- `misplaced_diagnostic_attributes` - triggers if the attribute exists but it is not placed on the item kind it's meant for
- `malformed_diagnostic_attributes` - triggers if the attribute's syntax or options are invalid
- `malformed_diagnostic_format_literals` - triggers if the format string literal is invalid, for example if it has unpaired curly braces or invalid parameters
- this pr doesn't create it, but future lints for things like deprecations can also go here.
This PR does not start emitting lints in places that previously did not.
## Motivation
I want to have finer control over what `unknown_or_malformed_diagnostic_attributes` does
I have a project with fairly low msrv that is/will have a lower msrv than future diagnostic attributes. So lints will be emitted when I or others compile it on a lower msrv.
At this time, there are two options to silence these lints:
- `#[allow(unknown_or_malformed_diagnostic_attributes)]` - this risks diagnostic regressions if I (or others) mess up using the attribute, or if the attribute's syntax ever changes.
- write a build script to detect the compiler version and emit cfgs, and then conditionally enable the attribute:
```rust
#[cfg_attr(rust_version_99, diagnostic::new_attr_in_rust_99(thing = ..))]`
struct Foo;
```
or conditionally `allow` the lint:
```rust
// lib.rs
#![cfg_attr(not(current_rust), allow(unknown_or_malformed_diagnostic_attributes))]
```
I like to avoid using build scripts if I can, so the following works much better for me. That is what this PR will let me do in the future:
```rust
#[allow(unknown_diagnostic_attribute, reason = "attribute came out in rust 1.99 but msrv is 1.70")]
#[diagnostic::new_attr_in_rust_99(thing = ..)]`
struct Foo;
Rollup of 9 pull requests
Successful merges:
- rust-lang/rust#143403 (Port several trait/coherence-related attributes the new attribute system)
- rust-lang/rust#143633 (fix: correct assertion to check for 'noinline' attribute presence before removal)
- rust-lang/rust#143647 (Clarify and expand documentation for std::sys_common dependency structure)
- rust-lang/rust#143716 (compiler: doc/comment some codegen-for-functions interfaces)
- rust-lang/rust#143747 (Add target maintainer information for aarch64-unknown-linux-musl)
- rust-lang/rust#143759 (Fix typos in function names in the `target_feature` test)
- rust-lang/rust#143767 (Bump `src/tools/x` to Edition 2024 and some cleanups)
- rust-lang/rust#143769 (Remove support for SwitchInt edge effects in backward dataflow)
- rust-lang/rust#143770 (build-helper: clippy fixes)
r? `@ghost`
`@rustbot` modify labels: rollup
Clarify and expand documentation for std::sys_common dependency structure
This PR makes a minor improvement to the module-level documentation of std::sys_common:
Replaces the lowercase “dag” with the more standard and explicit form “DAG (Directed Acyclic Graph)” for clarity.
Port several trait/coherence-related attributes the new attribute system
Part of rust-lang/rust#131229
This ports:
- `#[const_trait]`
- `#[rustc_deny_explicit_impl]`
- `#[rustc_do_not_implement_via_object]`
- `#[rustc_coinductive]`
- `#[type_const]`
- `#[rustc_specialization_trait]`
- `#[rustc_unsafe_specialization_marker]`
- `#[marker]`
- `#[fundamental]`
- `#[rustc_paren_sugar]`
- `#[rustc_allow_incoherent_impl]`
- `#[rustc_coherence_is_core]`
This also changes `#[marker]` to error on duplicates instead of warning.
cc rust-lang/rust#142838, but I don't think it matters too much, since it's unstable.
r? ``@oli-obk``
Make UB transmutes really UB in LLVM
Ralf suggested in <https://github.com/rust-lang/rust/pull/143410#discussion_r2184928123> that UB transmutes shouldn't be trapping, which happened for the one path *that* PR was changing, but there's another path as well, so *this* PR changes that other path to match.
r? codegen
fix: Include frontmatter in -Zunpretty output
In the implementation (rust-lang/rust#140035), this was left as an open question for
the tracking issue (rust-lang/rust#136889). My assumption is that this should be
carried over.
The test was carried over from rust-lang/rust#137193 which was superseded by rust-lang/rust#140035.
Thankfully, either way, `-Zunpretty` is unstable and we can always
change it even if we stabilize frontmatter.
chore: Improve how the other suggestions message gets rendered
Note: This change is part of my ongoing work to use `annotate-snippets` as `rustc`'s emitter
This change started as a way to remove some specialty code paths from `annotate-snippets`, by making the "and {} other candidates" message get rendered like a secondary message with no level, but turned into a fix for the message's Unicode output. Before this change, when using the Unicode output, the other suggestions message would get rendered outside of the main suggestion block, making it feel disconnected from what it was referring to. This change makes it so that the message is on the last line of the block, aligning its rendering with other secondary messages, and making it clear what the message is referring to.
Before:
```
error[E0433]: failed to resolve: use of undeclared type `IntoIter`
╭▸ $DIR/issue-82956.rs:28:24
│
LL │ let mut iter = IntoIter::new(self);
│ ━━━━━━━━ use of undeclared type `IntoIter`
╰╴
help: consider importing one of these structs
╭╴
LL + use std::array::IntoIter;
├╴
LL + use std::collections::binary_heap::IntoIter;
├╴
LL + use std::collections::btree_map::IntoIter;
├╴
LL + use std::collections::btree_set::IntoIter;
╰╴
and 9 other candidates
```
After:
```
error[E0433]: failed to resolve: use of undeclared type `IntoIter`
╭▸ $DIR/issue-82956.rs:28:24
│
LL │ let mut iter = IntoIter::new(self);
│ ━━━━━━━━ use of undeclared type `IntoIter`
╰╴
help: consider importing one of these structs
╭╴
LL + use std::array::IntoIter;
├╴
LL + use std::collections::binary_heap::IntoIter;
├╴
LL + use std::collections::btree_map::IntoIter;
├╴
LL + use std::collections::btree_set::IntoIter;
│
╰ and 9 other candidates
```
`tests/ui`: A New Order [28/28] FINAL PART
> [!NOTE]
>
> Intermediate commits are intended to help review, but will be squashed prior to merge.
Some `tests/ui/` housekeeping, to trim down number of tests directly under `tests/ui/`. Part of rust-lang/rust#133895.
r? ``@tgross35``
`tests/ui`: A New Order [27/N]
> [!NOTE]
>
> Intermediate commits are intended to help review, but will be squashed prior to merge.
Some `tests/ui/` housekeeping, to trim down number of tests directly under `tests/ui/`. Part of rust-lang/rust#133895.
r? ``@tgross35``
rust: library: Add `setsid` method to `CommandExt` trait
Add a setsid method to the CommandExt trait so that callers can create a process in a new session and process group whilst still using the POSIX spawn fast path.
Tracking issue: rust-lang/rust#105376
ACP: https://github.com/rust-lang/libs-team/issues/184
This PR was previously submitted by ``@HarveyHunt`` (whom I marked as Co-Author in the commit message) in rust-lang/rust#105377. However that PR went stale.
I applied the [suggestion](231d19fcbf (r1893457943)) to change the function signature to `fn setsid(&mut self, setsid: bool) -> &mut Command`.
Add profiler to bootstrap command
This PR adds command profiling to the bootstrap command. It tracks the total execution time and records cache hits for each command. It also provides the ability to export execution result to a JSON file. Integrating this with Chrome tracing could further enhance observability.
r? `@Kobzol`
triagebot.toml: ping lolbinarycat if tidy extra checks were modified
I rewrote a large chunk of this module, and plan to do further changes to it (namely moving rustdoc_js checks into it), so it would be nice to keep up with and provide feedback on any changes to it, at least for the immediate future.
r? `@Kobzol`
Assorted `run-make-support` maintenance
This PR should contain no functional changes.
- Commit 1: Removes the support library's CHANGELOG. In the very beginning, I thought maybe we would try to version this library. But this is a purely internal test support library, and it's just extra busywork trying to maintain changelog/versions. It's also hopelessly outdated.
- Commit 2: Resets version number to `0.0.0`. Ditto on busywork.
- Commit 3: Bump `run-make-support` to Edition 2024. The support library was already "compliant" with Edition 2024.
- Commit 4: Slightly organizes the support library dependencies.
- Commit 5: Previously, I tried hopelessly to maintain some manual formatting, but that was annoying because it required skipping rustfmt (so export ordering etc. could not be extra formatted). Give up, and do some rearrangements / module prefix tricks to get the `lib.rs` looking at least *reasonable*. IMO this is not a strict improvement, but I rather regain the ability to auto-format it with rustfmt.
- Commit {6,7}: Noticed in rust-lang/rust#143669 that we apparently had *both* {`is_msvc`, `is_windows_msvc`}. This PR removes `is_msvc` in favor of `is_windows_msvc` to make it unambiguous (and only retain one way of gating) as there are some UEFI targets which are MSVC but not Windows.
Best reviewed commit-by-commit.
r? `@Kobzol`
Re-expose nested bodies in rustc_borrowck::consumers
After https://github.com/rust-lang/rust/pull/138499, it's not possible anymore to get borrowck information for nested bodies via `get_body_with_borrowck_facts`. This PR re-exposes nested bodies by returning a map containing the typeck root and all its nested bodies. To collect the bodies, a map is added to `BorrowCheckRootCtxt`, and a body is inserted every time `do_mir_borrowck` is called.
r? ``@lcnr``
docs: document trait upcasting rules in `Unsize` trait
The trait upcasting feature stabilized in 1.86 added new `Unsize` implementation, but this wasn't reflected in the trait's documentation.
Instantiate auto trait/`Copy`/`Clone`/`Sized` before computing constituent types binder
This makes the binder logic w.r.t. coroutines a bit simpler.
r? lcnr
Let `rvalue_creates_operand` return true for *all* `Rvalue::Aggregate`s
~~Draft for now because it's built on Ralf's rust-lang/rust#143291~~
Inspired by https://github.com/rust-lang/rust/pull/138759#discussion_r2156375342 where I noticed that we were nearly at this point, plus the comments I was writing in rust-lang/rust#143410 that reminded me a type-dependent `true` is fine.
This PR splits the `OperandRef::builder` logic out to a separate type, with the updates needed to handle SIMD as well. In doing so, that makes the existing `Aggregate` path in `codegen_rvalue_operand` capable of handing SIMD values just fine.
As a result, we no longer need to do layout calculations for aggregate result types when running the analysis to determine which things can be SSA in codegen.
`rustc_pattern_analysis`: always check that deref patterns don't match on the same place as normal constructors
In rust-lang/rust#140106, deref pattern validation was tied to the `deref_patterns` feature to temporarily avoid affecting perf. However:
- As of rust-lang/rust#143414, box patterns are represented as deref patterns in `rustc_pattern_analysis`. Since they can be used by enabling `box_patterns` instead of `deref_patterns`, it was possible for them to skip validation, resulting in an ICE. This fixes that and adds a regression test.
- External tooling (e.g. rust-analyzer) will also need to validate matches containing deref patterns, which was not possible. This fixes that by making `compute_match_usefulness` validate deref patterns by default.
In order to avoid doing an extra pass for anything with patterns, the second commit makes `RustcPatCtxt` keep track of whether it encounters a deref pattern, so that it only does the check if so. This is purely for performance. If the perf impact of the first commit is negligible and the complexity cost introduced by the second commit is significant, it may be worth dropping the latter.
r? `@Nadrieril`
Apply effects to `otherwise` edge in dataflow analysis
This allows `ElaborateDrops` to remove drops when a `match` wildcard arm covers multiple no-Drop enum variants. It modifies dataflow analysis to update the `MaybeUninitializedPlaces` and `MaybeInitializedPlaces` data for a block reached through an `otherwise` edge.
Fixesrust-lang/rust#142705.
Use `join_with_double_colon` in `write_shared.rs`.
For consistency. Also, it's faster because `join_with_double_colon` does a better job estimating the allocation size than `join` from `itertools`.
r? `@camelid`