From 8804eedfa4c948abfc6c838449e7bd40e8872b9a Mon Sep 17 00:00:00 2001 From: Joao Roberto Date: Mon, 24 Aug 2026 19:50:35 -0300 Subject: [PATCH 01/39] Propagate async closure output into its body Async closure bodies are checked as coroutines, but their expected return type was lost before body checking. Reuse the matching coroutine signature. Keep this path limited to async closures because gen closures have a different input shape. --- compiler/rustc_hir_typeck/src/closure.rs | 20 ++++++++++++++++++ ...utput-mismatch-issue-161619.current.stderr | 21 +++++++++++++++++++ ...e-output-mismatch-issue-161619.next.stderr | 21 +++++++++++++++++++ ...nc-closure-output-mismatch-issue-161619.rs | 18 ++++++++++++++++ 4 files changed, 80 insertions(+) create mode 100644 tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.current.stderr create mode 100644 tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.next.stderr create mode 100644 tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.rs diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index f6a97f04d99e4..f7fcfb6ea80d3 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -62,6 +62,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (expected_sig, expected_kind) = match expected.to_option(self) { Some(ty) => self.deduce_closure_signature( self.deeply_resolve_ignoring_regions_with_obligations(ty), + closure.def_id, closure.kind, ), None => (None, None), @@ -291,9 +292,28 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn deduce_closure_signature( &self, expected_ty: Ty<'tcx>, + closure_def_id: LocalDefId, closure_kind: hir::ClosureKind, ) -> (Option>, Option) { match *expected_ty.kind() { + ty::Coroutine(def_id, args) + if def_id == closure_def_id.to_def_id() + && matches!( + closure_kind, + hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared( + hir::CoroutineDesugaring::Async, + hir::CoroutineSource::Closure, + )) + ) => + { + // An async closure's body is itself a coroutine. Propagate the signature + // inferred for that coroutine into its body. + let args = args.as_coroutine(); + let sig = ty::Binder::dummy( + self.tcx.mk_fn_sig_safe_rust_abi([args.resume_ty()], args.return_ty()), + ); + (Some(ExpectedSig { cause_span: None, sig }), None) + } ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => self .deduce_closure_signature_from_predicates( expected_ty, diff --git a/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.current.stderr b/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.current.stderr new file mode 100644 index 0000000000000..62ee5193400c9 --- /dev/null +++ b/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.current.stderr @@ -0,0 +1,21 @@ +error[E0308]: mismatched types + --> $DIR/async-closure-output-mismatch-issue-161619.rs:16:27 + | +LL | for_each(async |_| Ok(String::new())); + | -- ^^^^^^^^^^^^^ expected `()`, found `String` + | | + | arguments to this enum variant are incorrect + | +help: the type constructed contains `String` due to the type of the argument passed + --> $DIR/async-closure-output-mismatch-issue-161619.rs:16:24 + | +LL | for_each(async |_| Ok(String::new())); + | ^^^-------------^ + | | + | this argument influences the type of `Ok` +note: tuple variant defined here + --> $SRC_DIR/core/src/result.rs:LL:COL + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.next.stderr b/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.next.stderr new file mode 100644 index 0000000000000..62ee5193400c9 --- /dev/null +++ b/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.next.stderr @@ -0,0 +1,21 @@ +error[E0308]: mismatched types + --> $DIR/async-closure-output-mismatch-issue-161619.rs:16:27 + | +LL | for_each(async |_| Ok(String::new())); + | -- ^^^^^^^^^^^^^ expected `()`, found `String` + | | + | arguments to this enum variant are incorrect + | +help: the type constructed contains `String` due to the type of the argument passed + --> $DIR/async-closure-output-mismatch-issue-161619.rs:16:24 + | +LL | for_each(async |_| Ok(String::new())); + | ^^^-------------^ + | | + | this argument influences the type of `Ok` +note: tuple variant defined here + --> $SRC_DIR/core/src/result.rs:LL:COL + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.rs b/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.rs new file mode 100644 index 0000000000000..aa26814ff5dbc --- /dev/null +++ b/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.rs @@ -0,0 +1,18 @@ +//@ edition: 2024 +//@ revisions: current next +//@ ignore-compare-mode-next-solver (explicit revisions) +//@[next] compile-flags: -Znext-solver + +use std::future::Future; + +fn for_each(_: F) +where + F: FnMut(()) -> Fut, + Fut: Future>, +{ +} + +fn main() { + for_each(async |_| Ok(String::new())); + //~^ ERROR mismatched types +} From 1b7d358443fdfc6a047214544d53cf38e32ebf1b Mon Sep 17 00:00:00 2001 From: Joao Roberto Date: Mon, 24 Aug 2026 20:33:09 -0300 Subject: [PATCH 02/39] Update async closure suggestion expectations --- .../suggest-create-closure-issue-150701.fixed | 1 - .../suggest-create-closure-issue-150701.rs | 1 - ...suggest-create-closure-issue-150701.stderr | 25 ++++--------------- 3 files changed, 5 insertions(+), 22 deletions(-) diff --git a/tests/ui/suggestions/suggest-create-closure-issue-150701.fixed b/tests/ui/suggestions/suggest-create-closure-issue-150701.fixed index f3e226c9e5681..d19ab19f98012 100644 --- a/tests/ui/suggestions/suggest-create-closure-issue-150701.fixed +++ b/tests/ui/suggestions/suggest-create-closure-issue-150701.fixed @@ -9,7 +9,6 @@ fn f(_c: impl Future) {} fn main() { f((async || {})()); //~ ERROR: expected function, found `()` - //~^ ERROR: is not a future f(async {}); //~^ ERROR: is not a future } diff --git a/tests/ui/suggestions/suggest-create-closure-issue-150701.rs b/tests/ui/suggestions/suggest-create-closure-issue-150701.rs index e7a5076d8f1d9..bbb5f4d0bb6bd 100644 --- a/tests/ui/suggestions/suggest-create-closure-issue-150701.rs +++ b/tests/ui/suggestions/suggest-create-closure-issue-150701.rs @@ -9,7 +9,6 @@ fn f(_c: impl Future) {} fn main() { f(async || {}()); //~ ERROR: expected function, found `()` - //~^ ERROR: is not a future f(async || {}); //~^ ERROR: is not a future } diff --git a/tests/ui/suggestions/suggest-create-closure-issue-150701.stderr b/tests/ui/suggestions/suggest-create-closure-issue-150701.stderr index 0f991169d6772..8f1f721f97f35 100644 --- a/tests/ui/suggestions/suggest-create-closure-issue-150701.stderr +++ b/tests/ui/suggestions/suggest-create-closure-issue-150701.stderr @@ -11,30 +11,15 @@ help: if you meant to create this closure and immediately call it, surround the LL | f((async || {})()); | + + -error[E0277]: `{async closure@$DIR/suggest-create-closure-issue-150701.rs:11:7: 11:15}` is not a future - --> $DIR/suggest-create-closure-issue-150701.rs:11:7 - | -LL | f(async || {}()); - | - ^^^^^^^^^^^^^ `{async closure@$DIR/suggest-create-closure-issue-150701.rs:11:7: 11:15}` is not a future - | | - | required by a bound introduced by this call - | - = help: the trait `Future` is not implemented for `{async closure@$DIR/suggest-create-closure-issue-150701.rs:11:7: 11:15}` -note: required by a bound in `f` - --> $DIR/suggest-create-closure-issue-150701.rs:8:15 - | -LL | fn f(_c: impl Future) {} - | ^^^^^^^^^^^^^^^^^^^ required by this bound in `f` - -error[E0277]: `{async closure@$DIR/suggest-create-closure-issue-150701.rs:13:7: 13:15}` is not a future - --> $DIR/suggest-create-closure-issue-150701.rs:13:7 +error[E0277]: `{async closure@$DIR/suggest-create-closure-issue-150701.rs:12:7: 12:15}` is not a future + --> $DIR/suggest-create-closure-issue-150701.rs:12:7 | LL | f(async || {}); - | - ^^^^^^^^^^^ `{async closure@$DIR/suggest-create-closure-issue-150701.rs:13:7: 13:15}` is not a future + | - ^^^^^^^^^^^ `{async closure@$DIR/suggest-create-closure-issue-150701.rs:12:7: 12:15}` is not a future | | | required by a bound introduced by this call | - = help: the trait `Future` is not implemented for `{async closure@$DIR/suggest-create-closure-issue-150701.rs:13:7: 13:15}` + = help: the trait `Future` is not implemented for `{async closure@$DIR/suggest-create-closure-issue-150701.rs:12:7: 12:15}` note: required by a bound in `f` --> $DIR/suggest-create-closure-issue-150701.rs:8:15 | @@ -46,7 +31,7 @@ LL - f(async || {}); LL + f(async {}); | -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors Some errors have detailed explanations: E0277, E0618. For more information about an error, try `rustc --explain E0277`. From 9cc30143ffa78ad2909570adf51dfb281262cca1 Mon Sep 17 00:00:00 2001 From: albab-hasan Date: Sat, 26 Sep 2026 17:29:59 +0600 Subject: [PATCH 03/39] keep the use<..> bound in the refining_impl_trait suggestion the lint suggested a return type built only from the trait bounds, so the precise capturing list was dropped. applying the suggestion then captured every lifetime in scope and failed to compile with "return type captures more lifetimes than trait definition". the suggestion now carries the capture list over, written in terms of the impl generics. a use<..> bound is only added when the trait opaque leaves out one of the method late bound lifetimes, since everything else already has to be listed in the trait. fixes https://github.com/rust-lang/rust/issues/141047 --- .../src/check/compare_impl_item/refine.rs | 62 ++++++++++++- .../refine-precise-capturing-issue-141047.rs | 51 ++++++++++ ...fine-precise-capturing-issue-141047.stderr | 93 +++++++++++++++++++ 3 files changed, 205 insertions(+), 1 deletion(-) create mode 100644 tests/ui/impl-trait/in-trait/refine-precise-capturing-issue-141047.rs create mode 100644 tests/ui/impl-trait/in-trait/refine-precise-capturing-issue-141047.stderr diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs index aa170a364b5b8..6e59d99adf1ec 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs @@ -95,6 +95,7 @@ pub(crate) fn check_refining_return_position_impl_trait_in_trait<'tcx>( report_mismatched_rpitit_signature( tcx, trait_m_sig_with_self_for_diag, + trait_m_sig, trait_m.def_id, impl_m.def_id, None, @@ -115,6 +116,7 @@ pub(crate) fn check_refining_return_position_impl_trait_in_trait<'tcx>( report_mismatched_rpitit_signature( tcx, trait_m_sig_with_self_for_diag, + trait_m_sig, trait_m.def_id, impl_m.def_id, None, @@ -219,6 +221,7 @@ pub(crate) fn check_refining_return_position_impl_trait_in_trait<'tcx>( report_mismatched_rpitit_signature( tcx, trait_m_sig_with_self_for_diag, + trait_m_sig, trait_m.def_id, impl_m.def_id, Some(span), @@ -292,6 +295,7 @@ impl<'tcx> TypeVisitor> for ImplTraitInTraitCollector<'tcx> { fn report_mismatched_rpitit_signature<'tcx>( tcx: TyCtxt<'tcx>, trait_m_sig: ty::FnSig<'tcx>, + trait_m_sig_with_impl_self: ty::FnSig<'tcx>, trait_m_def_id: DefId, impl_m_def_id: DefId, unmatched_bound: Option, @@ -319,6 +323,10 @@ fn report_mismatched_rpitit_signature<'tcx>( let mut return_ty = trait_m_sig.output().fold_with(&mut super::RemapLateParam { tcx, mapping }); + // An `async fn` suggestion replaces the desugared `Future` output rather than an opaque, so + // there is no `use<..>` bound to carry over. + let mut maybe_use_bounds_for_impl = None; + if tcx.asyncness(impl_m_def_id).is_async() && tcx.asyncness(trait_m_def_id).is_async() { let &ty::Alias( _, @@ -342,6 +350,9 @@ fn report_mismatched_rpitit_signature<'tcx>( span_bug!(tcx.def_span(trait_m_def_id), "expected `Future` projection bound in AFIT"); }; return_ty = future_output_ty; + } else { + maybe_use_bounds_for_impl = + rpitit_use_bounds_for_impl(tcx, trait_m_def_id, trait_m_sig_with_impl_self.output()); } let (span, impl_return_span, pre, post) = @@ -364,7 +375,10 @@ fn report_mismatched_rpitit_signature<'tcx>( // standard approach used elsewhere in the compiler for formatting types in suggestions // (e.g., see `rustc_hir_typeck/src/demand.rs`). let return_ty_suggestion = - with_no_trimmed_paths!(with_types_for_signature!(format!("{return_ty}"))); + with_no_trimmed_paths!(with_types_for_signature!(match &maybe_use_bounds_for_impl { + Some(use_bound) => format!("{return_ty} + {use_bound}"), + None => format!("{return_ty}"), + })); let span = unmatched_bound.unwrap_or(span); tcx.emit_node_span_lint( @@ -441,6 +455,52 @@ impl<'tcx> TypeVisitor> for CollectParams<'_, 'tcx> { } } +/// The `use<..>` bound of an impl has to be repeated so that its opaque captures no more than the +/// trait's RPITIT does, phrased in terms of the impl's own generics. +/// +/// A capture list is not part of how an opaque prints, and everything but in the method's late-bound +/// lifetimes has to appear, so a suggestion built from the trait's bounds alone would only +/// capture those lifetimes and would be rejected by the check `use<..>` exists to satisfy. +fn rpitit_use_bounds_for_impl<'tcx>( + tcx: TyCtxt<'tcx>, + trait_m_def_id: DefId, + trait_return_ty: Ty<'tcx>, +) -> Option { + let ty::Alias(_, alias) = *trait_return_ty.kind() else { + return None; + }; + let projection = alias.try_to_projection()?; + if !tcx.is_impl_trait_in_trait(projection.kind) { + return None; + } + + // An opaque only declares the late-bound lifetimes it captured, so declaring all of them + // means the impl captures the same set on its own. + let captured_lifetimes = tcx + .generics_of(projection.kind) + .own_params + .iter() + .filter(|param| matches!(param.kind, ty::GenericParamDefKind::Lifetime)) + .count(); + let late_bound_lifetimes = tcx + .fn_sig(trait_m_def_id) + .skip_binder() + .bound_vars() + .iter() + .filter(|var| matches!(var, ty::BoundVariableKind::Region(_))) + .count(); + if captured_lifetimes == late_bound_lifetimes { + return None; + } + + let mut captures = FxIndexSet::default(); + for arg in projection.args { + arg.visit_with(&mut CollectParams { params: &mut captures }); + } + captures.sort_by_cached_key(|arg| !matches!(arg.kind(), ty::GenericArgKind::Lifetime(_))); + Some(format!("use<{}>", captures.iter().join(", "))) +} + fn report_mismatched_rpitit_captures<'tcx>( tcx: TyCtxt<'tcx>, impl_opaque_def_id: LocalDefId, diff --git a/tests/ui/impl-trait/in-trait/refine-precise-capturing-issue-141047.rs b/tests/ui/impl-trait/in-trait/refine-precise-capturing-issue-141047.rs new file mode 100644 index 0000000000000..cd257bb597111 --- /dev/null +++ b/tests/ui/impl-trait/in-trait/refine-precise-capturing-issue-141047.rs @@ -0,0 +1,51 @@ +// The suggestion has to carry the trait's `use<..>` list over, expressed in terms of the impl's own +// generics, or applying it turns this warning into a hard error. + +#![deny(refining_impl_trait)] + +trait Captures { + fn f(&self) -> impl use + Send; +} + +impl Captures for () { + fn f(&self) -> () {} + //~^ ERROR impl trait in impl method signature does not match trait method signature +} + +struct W(T); + +impl Captures for W { + fn f(&self) -> () {} + //~^ ERROR impl trait in impl method signature does not match trait method signature +} + +trait CapturesParam { + fn f(&self) -> impl use + Send; +} + +impl CapturesParam for () { + fn f(&self) -> () {} + //~^ ERROR impl trait in impl method signature does not match trait method signature +} + +// The trait captures everything in scope, so the suggestion is already correct. +trait NoCaptures { + fn f(&self) -> impl Send; +} + +impl NoCaptures for () { + fn f(&self) -> () {} + //~^ ERROR impl trait in impl method signature does not match trait method signature +} + +// The impl would capture the same lifetime by default, so the suggestion is already correct. +trait CapturesLifetime { + fn f<'a>(&'a self) -> impl use<'a, Self> + Send; +} + +impl CapturesLifetime for () { + fn f<'a>(&'a self) -> () {} + //~^ ERROR impl trait in impl method signature does not match trait method signature +} + +fn main() {} diff --git a/tests/ui/impl-trait/in-trait/refine-precise-capturing-issue-141047.stderr b/tests/ui/impl-trait/in-trait/refine-precise-capturing-issue-141047.stderr new file mode 100644 index 0000000000000..9bb0c7b3543e9 --- /dev/null +++ b/tests/ui/impl-trait/in-trait/refine-precise-capturing-issue-141047.stderr @@ -0,0 +1,93 @@ +error: impl trait in impl method signature does not match trait method signature + --> $DIR/refine-precise-capturing-issue-141047.rs:11:20 + | +LL | fn f(&self) -> impl use + Send; + | --------------------- return type from trait method defined here +... +LL | fn f(&self) -> () {} + | ^^ + | + = note: add `#[allow(refining_impl_trait)]` if it is intended for this to be part of the public API of this crate + = note: we are soliciting feedback, see issue #121718 for more information +note: the lint level is defined here + --> $DIR/refine-precise-capturing-issue-141047.rs:4:9 + | +LL | #![deny(refining_impl_trait)] + | ^^^^^^^^^^^^^^^^^^^ + = note: `#[deny(refining_impl_trait_internal)]` implied by `#[deny(refining_impl_trait)]` +help: replace the return type so that it matches the trait + | +LL - fn f(&self) -> () {} +LL + fn f(&self) -> impl std::marker::Send + use<> {} + | + +error: impl trait in impl method signature does not match trait method signature + --> $DIR/refine-precise-capturing-issue-141047.rs:18:20 + | +LL | fn f(&self) -> impl use + Send; + | --------------------- return type from trait method defined here +... +LL | fn f(&self) -> () {} + | ^^ + | + = note: add `#[allow(refining_impl_trait)]` if it is intended for this to be part of the public API of this crate + = note: we are soliciting feedback, see issue #121718 for more information +help: replace the return type so that it matches the trait + | +LL - fn f(&self) -> () {} +LL + fn f(&self) -> impl std::marker::Send + use {} + | + +error: impl trait in impl method signature does not match trait method signature + --> $DIR/refine-precise-capturing-issue-141047.rs:27:20 + | +LL | fn f(&self) -> impl use + Send; + | ------------------------ return type from trait method defined here +... +LL | fn f(&self) -> () {} + | ^^ + | + = note: add `#[allow(refining_impl_trait)]` if it is intended for this to be part of the public API of this crate + = note: we are soliciting feedback, see issue #121718 for more information +help: replace the return type so that it matches the trait + | +LL - fn f(&self) -> () {} +LL + fn f(&self) -> impl std::marker::Send + use<> {} + | + +error: impl trait in impl method signature does not match trait method signature + --> $DIR/refine-precise-capturing-issue-141047.rs:37:20 + | +LL | fn f(&self) -> impl Send; + | --------- return type from trait method defined here +... +LL | fn f(&self) -> () {} + | ^^ + | + = note: add `#[allow(refining_impl_trait)]` if it is intended for this to be part of the public API of this crate + = note: we are soliciting feedback, see issue #121718 for more information +help: replace the return type so that it matches the trait + | +LL - fn f(&self) -> () {} +LL + fn f(&self) -> impl std::marker::Send {} + | + +error: impl trait in impl method signature does not match trait method signature + --> $DIR/refine-precise-capturing-issue-141047.rs:47:27 + | +LL | fn f<'a>(&'a self) -> impl use<'a, Self> + Send; + | ------------------------- return type from trait method defined here +... +LL | fn f<'a>(&'a self) -> () {} + | ^^ + | + = note: add `#[allow(refining_impl_trait)]` if it is intended for this to be part of the public API of this crate + = note: we are soliciting feedback, see issue #121718 for more information +help: replace the return type so that it matches the trait + | +LL - fn f<'a>(&'a self) -> () {} +LL + fn f<'a>(&'a self) -> impl std::marker::Send {} + | + +error: aborting due to 5 previous errors + From 2483fb6e908b10c7c67c48df76092160c81f6b08 Mon Sep 17 00:00:00 2001 From: lapla Date: Fri, 4 Sep 2026 15:29:21 +0900 Subject: [PATCH 04/39] Keep deref suggestions from inserting a second pair of brackets --- Cargo.lock | 1 + compiler/rustc_span/Cargo.toml | 1 + compiler/rustc_span/src/source_map.rs | 74 +++++---------- tests/ui/suggestions/wrapped-path-trivia.rs | 34 +++++++ .../ui/suggestions/wrapped-path-trivia.stderr | 93 +++++++++++++++++++ 5 files changed, 153 insertions(+), 50 deletions(-) create mode 100644 tests/ui/suggestions/wrapped-path-trivia.rs create mode 100644 tests/ui/suggestions/wrapped-path-trivia.stderr diff --git a/Cargo.lock b/Cargo.lock index 5b3cd45c5205e..c8ad5a19cab95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4840,6 +4840,7 @@ dependencies = [ "rustc_data_structures", "rustc_hashes", "rustc_index", + "rustc_lexer", "rustc_macros", "rustc_serialize", "scoped-tls", diff --git a/compiler/rustc_span/Cargo.toml b/compiler/rustc_span/Cargo.toml index f8e5e2b48b5f0..2ebe3ef8cacc9 100644 --- a/compiler/rustc_span/Cargo.toml +++ b/compiler/rustc_span/Cargo.toml @@ -14,6 +14,7 @@ rustc_arena = { path = "../rustc_arena" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_hashes = { path = "../rustc_hashes" } rustc_index = { path = "../rustc_index" } +rustc_lexer = { path = "../rustc_lexer" } rustc_macros = { path = "../rustc_macros" } rustc_serialize = { path = "../rustc_serialize" } scoped-tls = "1.0" diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs index f394765ab9f8e..9a743e6a802c8 100644 --- a/compiler/rustc_span/src/source_map.rs +++ b/compiler/rustc_span/src/source_map.rs @@ -15,6 +15,7 @@ use std::{fs, path}; use rustc_data_structures::sync::{IntoDynSyncSend, MappedReadGuard, ReadGuard, RwLock}; use rustc_data_structures::unhash::UnhashMap; +use rustc_lexer::{FrontmatterAllowed, TokenKind, tokenize}; use tracing::{debug, instrument, trace}; use crate::*; @@ -820,62 +821,26 @@ impl SourceMap { } /// Given a 'Span', tries to tell if it's wrapped by "<>" or "()" - /// the algorithm searches if the next character is '>' or ')' after skipping white space - /// then searches the previous character to match '<' or '(' after skipping white space + /// the algorithm searches if the next character is '>' or ')' after skipping whitespace and comments + /// then searches the previous character to match '<' or '(' after skipping whitespace and comments /// return true if wrapped by '<>' or '()' pub fn span_wrapped_by_angle_or_parentheses(&self, span: Span) -> bool { self.span_to_source(span, |src, start_index, end_index| { if src.get(start_index..end_index).is_none() { return Ok(false); } - // test the right side to match '>' after skipping white space - let end_src = &src[end_index..]; - let mut i = 0; - let mut found_right_parentheses = false; - let mut found_right_angle = false; - while let Some(cc) = end_src.chars().nth(i) { - if cc == ' ' { - i = i + 1; - } else if cc == '>' { - // found > in the right; - found_right_angle = true; - break; - } else if cc == ')' { - found_right_parentheses = true; - break; - } else { - // failed to find '>' return false immediately - return Ok(false); - } - } - // test the left side to match '<' after skipping white space - i = start_index; - let start_src = &src[0..start_index]; - while let Some(cc) = start_src.chars().nth(i) { - if cc == ' ' { - if i == 0 { - return Ok(false); - } - i = i - 1; - } else if cc == '<' { - // found < in the left - if !found_right_angle { - // skip something like "(< )>" - return Ok(false); - } - break; - } else if cc == '(' { - if !found_right_parentheses { - // skip something like "<(>)" - return Ok(false); - } - break; - } else { - // failed to find '<' return false immediately - return Ok(false); - } - } - Ok(true) + let right = tokenize(&src[end_index..], FrontmatterAllowed::No) + .find_map(|token| (!is_trivia(token.kind)).then_some(token.kind)); + let left = tokenize(&src[..start_index], FrontmatterAllowed::No) + .map(|token| token.kind) + .filter(|kind| !is_trivia(*kind)) + .last(); + + Ok(matches!( + (left, right), + (Some(TokenKind::Lt), Some(TokenKind::Gt)) + | (Some(TokenKind::OpenParen), Some(TokenKind::CloseParen)) + )) }) .is_ok_and(|is_accessible| is_accessible) } @@ -1326,3 +1291,12 @@ impl FilePathMapping { found } } + +fn is_trivia(kind: TokenKind) -> bool { + matches!( + kind, + TokenKind::Whitespace + | TokenKind::LineComment { doc_style: None, .. } + | TokenKind::BlockComment { doc_style: None, .. } + ) +} diff --git a/tests/ui/suggestions/wrapped-path-trivia.rs b/tests/ui/suggestions/wrapped-path-trivia.rs new file mode 100644 index 0000000000000..1e5d695638985 --- /dev/null +++ b/tests/ui/suggestions/wrapped-path-trivia.rs @@ -0,0 +1,34 @@ +fn main() { + < + &[u32] + >::iter; + //~^ ERROR no associated function or constant named `iter` found for reference `&[u32]` + + <&[u32]/*c*/>::iter; + //~^ ERROR no associated function or constant named `iter` found for reference `&[u32]` + + <&[u32] // c + >::iter; + //~^ ERROR no associated function or constant named `iter` found for reference `&[u32]` + + ::iter; + //~^ ERROR no associated function or constant named `iter` found for reference `&[u32]` + + ::iter; + //~^ ERROR no associated function or constant named `iter` found for reference `&[u32]` + + let _ = ( + r#" +// "#, + <&[u32]>::iter, + //~^ ERROR no associated function or constant named `iter` found for reference `&[u32]` + ); + + fn foo<'a>() { + < // */ + &[u32]>::iter; + //~^ ERROR no associated function or constant named `iter` found for reference `&[u32]` + } +} diff --git a/tests/ui/suggestions/wrapped-path-trivia.stderr b/tests/ui/suggestions/wrapped-path-trivia.stderr new file mode 100644 index 0000000000000..604e7fe761db6 --- /dev/null +++ b/tests/ui/suggestions/wrapped-path-trivia.stderr @@ -0,0 +1,93 @@ +error[E0599]: no associated function or constant named `iter` found for reference `&[u32]` in the current scope + --> $DIR/wrapped-path-trivia.rs:4:8 + | +LL | < +LL | &[u32] +LL | >::iter; + | ^^^^ associated function or constant not found in `&[u32]` + | +help: the function `iter` is implemented on `[u32]` + | +LL - &[u32] +LL + [u32] + | + +error[E0599]: no associated function or constant named `iter` found for reference `&[u32]` in the current scope + --> $DIR/wrapped-path-trivia.rs:7:20 + | +LL | <&[u32]/*c*/>::iter; + | ^^^^ associated function or constant not found in `&[u32]` + | +help: the function `iter` is implemented on `[u32]` + | +LL - <&[u32]/*c*/>::iter; +LL + <[u32]/*c*/>::iter; + | + +error[E0599]: no associated function or constant named `iter` found for reference `&[u32]` in the current scope + --> $DIR/wrapped-path-trivia.rs:11:8 + | +LL | <&[u32] // c +LL | >::iter; + | ^^^^ associated function or constant not found in `&[u32]` + | +help: the function `iter` is implemented on `[u32]` + | +LL - <&[u32] // c +LL + <[u32] // c + | + +error[E0599]: no associated function or constant named `iter` found for reference `&[u32]` in the current scope + --> $DIR/wrapped-path-trivia.rs:16:14 + | +LL | ::iter; + | ^^^^ associated function or constant not found in `&[u32]` + | +help: the function `iter` is implemented on `[u32]` + | +LL - &[u32]>::iter; +LL + [u32]>::iter; + | + +error[E0599]: no associated function or constant named `iter` found for reference `&[u32]` in the current scope + --> $DIR/wrapped-path-trivia.rs:19:21 + | +LL | ::iter; + | ^^^^ associated function or constant not found in `&[u32]` + | +help: the function `iter` is implemented on `[u32]` + | +LL - ::iter; +LL + ::iter; + | + +error[E0599]: no associated function or constant named `iter` found for reference `&[u32]` in the current scope + --> $DIR/wrapped-path-trivia.rs:25:19 + | +LL | <&[u32]>::iter, + | ^^^^ associated function or constant not found in `&[u32]` + | +help: the function `iter` is implemented on `[u32]` + | +LL - <&[u32]>::iter, +LL + <[u32]>::iter, + | + +error[E0599]: no associated function or constant named `iter` found for reference `&[u32]` in the current scope + --> $DIR/wrapped-path-trivia.rs:31:18 + | +LL | < // */ +LL | &[u32]>::iter; + | ^^^^ associated function or constant not found in `&[u32]` + | +help: the function `iter` is implemented on `[u32]` + | +LL - &[u32]>::iter; +LL + [u32]>::iter; + | + +error: aborting due to 7 previous errors + +For more information about this error, try `rustc --explain E0599`. From e6c7d9c9899512cdbf6780d596bfa9182fa3de20 Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Mon, 12 Oct 2026 16:12:29 +0000 Subject: [PATCH 05/39] Compact the previous dependency-node reverse index --- .../rustc_middle/src/dep_graph/serialized.rs | 35 +++++++--- .../src/dep_graph/serialized/tests.rs | 68 +++++++++++++++++++ 2 files changed, 95 insertions(+), 8 deletions(-) create mode 100644 compiler/rustc_middle/src/dep_graph/serialized/tests.rs diff --git a/compiler/rustc_middle/src/dep_graph/serialized.rs b/compiler/rustc_middle/src/dep_graph/serialized.rs index 1c476fc91697e..cba0486682765 100644 --- a/compiler/rustc_middle/src/dep_graph/serialized.rs +++ b/compiler/rustc_middle/src/dep_graph/serialized.rs @@ -41,16 +41,21 @@ use std::cell::RefCell; use std::cmp::max; +use std::hash::{BuildHasher, BuildHasherDefault}; use std::sync::atomic::Ordering; use std::sync::{Arc, OnceLock}; use std::{iter, mem}; +#[cfg(test)] +mod tests; + use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint}; use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::hash_table::{Entry, HashTable}; use rustc_data_structures::outline; use rustc_data_structures::profiling::SelfProfilerRef; use rustc_data_structures::sync::{AtomicU64, Lock, WorkerLocal, broadcast}; -use rustc_data_structures::unhash::UnhashMap; +use rustc_data_structures::unhash::Unhasher; use rustc_index::{IndexSlice, IndexVec}; use rustc_serialize::opaque::mem_encoder::MemEncoder; use rustc_serialize::opaque::{FileEncodeResult, FileEncoder, IntEncodedWithFixedSize, MemDecoder}; @@ -165,8 +170,14 @@ struct LazyKindIndex { /// Number of nodes of this kind. len: u32, /// `key_fingerprint -> node index`, built from this kind's range on first - /// lookup. Empty kinds (and kinds never looked up) never build a map. - map: OnceLock>, + /// lookup. Keys are read from the immutable node array rather than duplicated + /// in each table entry. Kinds never looked up never build a map. + map: OnceLock>, +} + +#[inline] +fn fingerprint_hash(fingerprint: PackedFingerprint) -> u64 { + BuildHasherDefault::::default().hash_one(fingerprint) } impl LazyKindIndex { @@ -177,19 +188,23 @@ impl LazyKindIndex { nodes: &IndexSlice, nodes_by_kind: &[Option], profiler: &Option, - ) -> &UnhashMap { + ) -> &HashTable { self.map.get_or_init(|| { let _prof_timer = profiler .as_ref() .map(|p| p.generic_activity("incr_comp_load_dep_graph_reverse_index")); let range = (self.start as usize)..(self.start as usize + self.len as usize); - let mut map = - UnhashMap::with_capacity_and_hasher(self.len as usize, Default::default()); + let mut map = HashTable::::with_capacity(self.len as usize); for &idx in &nodes_by_kind[range] { let idx = idx.expect("counting sort fills every slot of a kind's range"); let node = nodes[idx]; debug_assert_eq!(node.kind, kind); - if map.insert(node.key_fingerprint, idx).is_some() + let entry = map.entry( + fingerprint_hash(node.key_fingerprint), + |&index| nodes[index].key_fingerprint == node.key_fingerprint, + |&index| fingerprint_hash(nodes[index].key_fingerprint), + ); + if matches!(&entry, Entry::Occupied(_)) // Side effect nodes can legitimately share a fingerprint. && node.kind != DepKind::SideEffect { @@ -201,6 +216,7 @@ impl LazyKindIndex { DepNode: {node:?}" ) } + entry.insert(idx); } map }) @@ -244,7 +260,10 @@ impl SerializedDepGraph { &self.reverse_index.nodes_by_kind, &self.profiler, ); - map.get(&dep_node.key_fingerprint).copied() + map.find(fingerprint_hash(dep_node.key_fingerprint), |&index| { + self.nodes[index].key_fingerprint == dep_node.key_fingerprint + }) + .copied() } #[inline] diff --git a/compiler/rustc_middle/src/dep_graph/serialized/tests.rs b/compiler/rustc_middle/src/dep_graph/serialized/tests.rs new file mode 100644 index 0000000000000..7ff5999c66999 --- /dev/null +++ b/compiler/rustc_middle/src/dep_graph/serialized/tests.rs @@ -0,0 +1,68 @@ +use super::*; + +fn node(kind: DepKind, first: u64, second: u64) -> DepNode { + DepNode { kind, key_fingerprint: Fingerprint::new(first, second).into() } +} + +fn graph(nodes: Vec) -> SerializedDepGraph { + let nodes = IndexVec::from_raw(nodes); + let mut nodes_by_kind = Vec::new(); + let kinds = (0..DepKind::NUM_VARIANTS) + .map(|kind| { + let start = nodes_by_kind.len(); + nodes_by_kind.extend(nodes.iter_enumerated().filter_map(|(index, node)| { + (node.kind != DepKind::Null && node.kind.as_usize() == kind).then_some(Some(index)) + })); + LazyKindIndex { + start: start as u32, + len: (nodes_by_kind.len() - start) as u32, + map: OnceLock::new(), + } + }) + .collect(); + SerializedDepGraph { + nodes, + live_node_count: nodes_by_kind.len(), + reverse_index: LazyNodeIndex { nodes_by_kind, kinds }, + ..Default::default() + } +} + +#[test] +fn reverse_index_checks_full_fingerprints_and_kind_with_sparse_indices() { + let first = node(DepKind::CompileCodegenUnit, 1, 2); + let collision = node(DepKind::CompileCodegenUnit, 2, 1); + let other_kind = node(DepKind::CompileMonoItem, 1, 2); + let null = node(DepKind::Null, 0, 0); + assert_eq!( + fingerprint_hash(first.key_fingerprint), + fingerprint_hash(collision.key_fingerprint) + ); + let graph = graph(vec![null, first, null, other_kind, collision]); + assert!(graph.reverse_index.kinds.iter().all(|kind| kind.map.get().is_none())); + assert_eq!(graph.node_to_index_opt(&first), Some(SerializedDepNodeIndex::from_u32(1))); + assert!(graph.reverse_index.kinds[other_kind.kind.as_usize()].map.get().is_none()); + for (node, index) in [(first, 1), (collision, 4), (other_kind, 3)] { + assert_eq!(graph.node_to_index_opt(&node), Some(SerializedDepNodeIndex::from_u32(index))); + } + assert_eq!(graph.node_to_index_opt(&node(DepKind::CompileCodegenUnit, 3, 0)), None); + assert_eq!(graph.node_to_index_opt(&node(DepKind::SideEffect, 1, 2)), None); + assert_eq!(graph.node_to_index_opt(&null), None); + assert_eq!(SerializedDepGraph::default().node_to_index_opt(&first), None); +} + +#[test] +fn reverse_index_side_effect_duplicates_use_the_last_index() { + let duplicate = node(DepKind::SideEffect, 1, 2); + let collision = node(DepKind::SideEffect, 2, 1); + let graph = graph(vec![duplicate, collision, node(DepKind::Null, 0, 0), duplicate]); + assert_eq!(graph.node_to_index_opt(&duplicate), Some(SerializedDepNodeIndex::from_u32(3))); + assert_eq!(graph.node_to_index_opt(&collision), Some(SerializedDepNodeIndex::from_u32(1))); +} + +#[test] +#[should_panic(expected = "does not have an unique index")] +fn reverse_index_rejects_other_duplicate_nodes() { + let duplicate = node(DepKind::CompileCodegenUnit, 1, 2); + graph(vec![duplicate, duplicate]).node_to_index_opt(&duplicate); +} From fc4814191d309124271425a02539d170da90a1d0 Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Thu, 15 Oct 2026 11:51:15 -0400 Subject: [PATCH 06/39] Simplify dependency graph index tests --- .../src/dep_graph/serialized/tests.rs | 49 ++++++------------- 1 file changed, 14 insertions(+), 35 deletions(-) diff --git a/compiler/rustc_middle/src/dep_graph/serialized/tests.rs b/compiler/rustc_middle/src/dep_graph/serialized/tests.rs index 7ff5999c66999..a008b6b863d97 100644 --- a/compiler/rustc_middle/src/dep_graph/serialized/tests.rs +++ b/compiler/rustc_middle/src/dep_graph/serialized/tests.rs @@ -4,65 +4,44 @@ fn node(kind: DepKind, first: u64, second: u64) -> DepNode { DepNode { kind, key_fingerprint: Fingerprint::new(first, second).into() } } -fn graph(nodes: Vec) -> SerializedDepGraph { +fn single_kind_graph(nodes: Vec) -> SerializedDepGraph { + let kind = nodes[0].kind; let nodes = IndexVec::from_raw(nodes); - let mut nodes_by_kind = Vec::new(); - let kinds = (0..DepKind::NUM_VARIANTS) - .map(|kind| { - let start = nodes_by_kind.len(); - nodes_by_kind.extend(nodes.iter_enumerated().filter_map(|(index, node)| { - (node.kind != DepKind::Null && node.kind.as_usize() == kind).then_some(Some(index)) - })); - LazyKindIndex { - start: start as u32, - len: (nodes_by_kind.len() - start) as u32, - map: OnceLock::new(), - } - }) - .collect(); + let mut kinds = Vec::new(); + kinds.resize_with(DepKind::NUM_VARIANTS, LazyKindIndex::default); + kinds[kind.as_usize()].len = nodes.len() as u32; SerializedDepGraph { + live_node_count: nodes.len(), + reverse_index: LazyNodeIndex { nodes_by_kind: nodes.indices().map(Some).collect(), kinds }, nodes, - live_node_count: nodes_by_kind.len(), - reverse_index: LazyNodeIndex { nodes_by_kind, kinds }, ..Default::default() } } #[test] -fn reverse_index_checks_full_fingerprints_and_kind_with_sparse_indices() { +fn reverse_index_distinguishes_hash_collisions() { let first = node(DepKind::CompileCodegenUnit, 1, 2); let collision = node(DepKind::CompileCodegenUnit, 2, 1); - let other_kind = node(DepKind::CompileMonoItem, 1, 2); - let null = node(DepKind::Null, 0, 0); assert_eq!( fingerprint_hash(first.key_fingerprint), fingerprint_hash(collision.key_fingerprint) ); - let graph = graph(vec![null, first, null, other_kind, collision]); - assert!(graph.reverse_index.kinds.iter().all(|kind| kind.map.get().is_none())); - assert_eq!(graph.node_to_index_opt(&first), Some(SerializedDepNodeIndex::from_u32(1))); - assert!(graph.reverse_index.kinds[other_kind.kind.as_usize()].map.get().is_none()); - for (node, index) in [(first, 1), (collision, 4), (other_kind, 3)] { - assert_eq!(graph.node_to_index_opt(&node), Some(SerializedDepNodeIndex::from_u32(index))); - } + let graph = single_kind_graph(vec![first, collision]); + assert_eq!(graph.node_to_index_opt(&first), Some(SerializedDepNodeIndex::from_u32(0))); + assert_eq!(graph.node_to_index_opt(&collision), Some(SerializedDepNodeIndex::from_u32(1))); assert_eq!(graph.node_to_index_opt(&node(DepKind::CompileCodegenUnit, 3, 0)), None); - assert_eq!(graph.node_to_index_opt(&node(DepKind::SideEffect, 1, 2)), None); - assert_eq!(graph.node_to_index_opt(&null), None); - assert_eq!(SerializedDepGraph::default().node_to_index_opt(&first), None); } #[test] fn reverse_index_side_effect_duplicates_use_the_last_index() { let duplicate = node(DepKind::SideEffect, 1, 2); - let collision = node(DepKind::SideEffect, 2, 1); - let graph = graph(vec![duplicate, collision, node(DepKind::Null, 0, 0), duplicate]); - assert_eq!(graph.node_to_index_opt(&duplicate), Some(SerializedDepNodeIndex::from_u32(3))); - assert_eq!(graph.node_to_index_opt(&collision), Some(SerializedDepNodeIndex::from_u32(1))); + let graph = single_kind_graph(vec![duplicate, duplicate]); + assert_eq!(graph.node_to_index_opt(&duplicate), Some(SerializedDepNodeIndex::from_u32(1))); } #[test] #[should_panic(expected = "does not have an unique index")] fn reverse_index_rejects_other_duplicate_nodes() { let duplicate = node(DepKind::CompileCodegenUnit, 1, 2); - graph(vec![duplicate, duplicate]).node_to_index_opt(&duplicate); + single_kind_graph(vec![duplicate, duplicate]).node_to_index_opt(&duplicate); } From 1da114ed5ce6caa36d8351e329c8495eab972db4 Mon Sep 17 00:00:00 2001 From: Andrew Kaster Date: Fri, 16 Oct 2026 23:00:40 -0400 Subject: [PATCH 07/39] compiler: Add `{x86_64,aarch64}-unknown-serenity` targets Co-Authored-By: Daniel Bertalan --- compiler/rustc_target/src/spec/base/mod.rs | 1 + .../rustc_target/src/spec/base/serenity.rs | 21 +++++++ compiler/rustc_target/src/spec/mod.rs | 4 ++ .../spec/targets/aarch64_unknown_serenity.rs | 22 +++++++ .../spec/targets/x86_64_unknown_serenity.rs | 24 ++++++++ src/bootstrap/src/core/sanity.rs | 1 + src/doc/rustc/src/SUMMARY.md | 1 + src/doc/rustc/src/platform-support.md | 2 + .../rustc/src/platform-support/serenity.md | 59 +++++++++++++++++++ src/librustdoc/clean/cfg.rs | 1 + tests/assembly-llvm/targets/targets-elf.rs | 6 ++ tests/ui/check-cfg/cfg-crate-features.stderr | 2 +- tests/ui/check-cfg/well-known-values.stderr | 4 +- 13 files changed, 145 insertions(+), 3 deletions(-) create mode 100644 compiler/rustc_target/src/spec/base/serenity.rs create mode 100644 compiler/rustc_target/src/spec/targets/aarch64_unknown_serenity.rs create mode 100644 compiler/rustc_target/src/spec/targets/x86_64_unknown_serenity.rs create mode 100644 src/doc/rustc/src/platform-support/serenity.md diff --git a/compiler/rustc_target/src/spec/base/mod.rs b/compiler/rustc_target/src/spec/base/mod.rs index 726ec2c228596..5ce44806626f0 100644 --- a/compiler/rustc_target/src/spec/base/mod.rs +++ b/compiler/rustc_target/src/spec/base/mod.rs @@ -31,6 +31,7 @@ pub(crate) mod openbsd; pub(crate) mod qnx_sdp; pub(crate) mod qtee; pub(crate) mod redox; +pub(crate) mod serenity; pub(crate) mod solaris; pub(crate) mod solid; pub(crate) mod teeos; diff --git a/compiler/rustc_target/src/spec/base/serenity.rs b/compiler/rustc_target/src/spec/base/serenity.rs new file mode 100644 index 0000000000000..2be7849193e30 --- /dev/null +++ b/compiler/rustc_target/src/spec/base/serenity.rs @@ -0,0 +1,21 @@ +use crate::spec::{FramePointer, Os, PanicStrategy, RelroLevel, TargetOptions, cvs}; + +pub(crate) fn opts() -> TargetOptions { + TargetOptions { + os: Os::Serenity, + dynamic_linking: true, + frame_pointer: FramePointer::Always, + families: cvs!["unix"], + default_dwarf_version: 5, + has_rpath: true, + no_default_libraries: false, + position_independent_executables: true, + static_position_independent_executables: false, + relro_level: RelroLevel::Full, + has_thread_local: true, + panic_strategy: PanicStrategy::Abort, + crt_static_default: false, + crt_static_respected: false, + ..Default::default() + } +} diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 6c7f5a7772323..304686e90e827 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -1707,6 +1707,9 @@ supported_targets! { ("aarch64-unknown-hyperlight", aarch64_unknown_hyperlight), ("x86_64-unknown-hyperlight", x86_64_unknown_hyperlight), + + ("aarch64-unknown-serenity", aarch64_unknown_serenity), + ("x86_64-unknown-serenity", x86_64_unknown_serenity), } /// Cow-Vec-Str: Cow<'static, [Cow<'static, str>]> @@ -1884,6 +1887,7 @@ crate::target_spec_enum! { Qurt = "qurt", Redox = "redox", Rtems = "rtems", + Serenity = "serenity", Solaris = "solaris", SolidAsp3 = "solid_asp3", TeeOs = "teeos", diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_serenity.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_serenity.rs new file mode 100644 index 0000000000000..9dff331e0b4ff --- /dev/null +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_serenity.rs @@ -0,0 +1,22 @@ +use crate::spec::{Arch, StackProbeType, Target, base}; + +pub(crate) fn target() -> Target { + let mut base = base::serenity::opts(); + base.max_atomic_width = Some(128); + base.stack_probes = StackProbeType::Inline; + base.features = "+v8a".into(); + + Target { + llvm_target: "aarch64-unknown-serenity".into(), + metadata: crate::spec::TargetMetadata { + description: Some("SerenityOS AArch64".into()), + tier: Some(3), + host_tools: Some(false), + std: Some(false), + }, + pointer_width: 64, + data_layout: "e-m:e-p270:32:32-p271:32:32-p272:64:64-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128-Fn32".into(), + arch: Arch::AArch64, + options: base + } +} diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_serenity.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_serenity.rs new file mode 100644 index 0000000000000..7731a185c528c --- /dev/null +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_serenity.rs @@ -0,0 +1,24 @@ +use crate::spec::{Arch, Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; + +pub(crate) fn target() -> Target { + let mut base = base::serenity::opts(); + base.cpu = "x86-64".into(); + base.max_atomic_width = Some(64); + base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m64"]); + base.stack_probes = StackProbeType::Inline; + + Target { + llvm_target: "x86_64-unknown-serenity".into(), + metadata: crate::spec::TargetMetadata { + description: Some("SerenityOS x86_64".into()), + tier: Some(3), + host_tools: Some(false), + std: Some(false), + }, + pointer_width: 64, + data_layout: + "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128".into(), + arch: Arch::X86_64, + options: base, + } +} diff --git a/src/bootstrap/src/core/sanity.rs b/src/bootstrap/src/core/sanity.rs index ac44a4dfca9b1..ba181220a7fb0 100644 --- a/src/bootstrap/src/core/sanity.rs +++ b/src/bootstrap/src/core/sanity.rs @@ -35,6 +35,7 @@ pub struct Finder { /// Targets can be removed from this list during the usual release process bootstrap compiler bumps, /// when the newly-bumped stage 0 compiler now knows about the formerly-missing targets. const STAGE0_MISSING_TARGETS: &[&str] = &[ + "aarch64-unknown-serenity", // just a dummy comment so the list doesn't get onelined "aarch64-unknown-qtee", ]; diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md index 953789648485b..e2bf1193b9366 100644 --- a/src/doc/rustc/src/SUMMARY.md +++ b/src/doc/rustc/src/SUMMARY.md @@ -141,6 +141,7 @@ - [\*-unknown-netbsd\*](platform-support/netbsd.md) - [\*-unknown-openbsd](platform-support/openbsd.md) - [\*-unknown-redox](platform-support/redox.md) + - [\*-unknown-serenity](platform-support/serenity.md) - [\*-unknown-uefi](platform-support/unknown-uefi.md) - [\*-pc-windows-msvc](platform-support/windows-msvc.md) - [\*-uwp-windows-msvc](platform-support/uwp-windows-msvc.md) diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index 2321dec16b8eb..9a8c304d11a5d 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -287,6 +287,7 @@ target | std | host | notes [`aarch64-unknown-nuttx`](platform-support/nuttx.md) | ✓ | | ARM64 with NuttX [`aarch64-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | ARM64 OpenBSD [`aarch64-unknown-redox`](platform-support/redox.md) | ✓ | | ARM64 Redox OS +[`aarch64-unknown-serenity`](platform-support/serenity.md) | ? | | | ARM64 SerenityOS | [`aarch64-unknown-teeos`](platform-support/aarch64-unknown-teeos.md) | ? | | ARM64 TEEOS | [`aarch64-unknown-qtee`](platform-support/aarch64-unknown-qtee.md) | ? | | ARM64 QTEE | [`aarch64-unknown-trusty`](platform-support/trusty.md) | ✓ | | @@ -470,6 +471,7 @@ target | std | host | notes [`x86_64-unknown-managarm-mlibc`](platform-support/managarm.md) | ? | | x86_64 Managarm [`x86_64-unknown-motor`](platform-support/motor.md) | ✓ | | x86_64 Motor OS [`x86_64-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | 64-bit OpenBSD +[`x86_64-unknown-serenity`](platform-support/serenity.md) | ? | | | x86_64 SerenityOS | [`x86_64-unknown-trusty`](platform-support/trusty.md) | ✓ | | `x86_64-uwp-windows-gnu` | ✓ | | [`x86_64-uwp-windows-msvc`](platform-support/uwp-windows-msvc.md) | ✓ | | diff --git a/src/doc/rustc/src/platform-support/serenity.md b/src/doc/rustc/src/platform-support/serenity.md new file mode 100644 index 0000000000000..d195b0f393d86 --- /dev/null +++ b/src/doc/rustc/src/platform-support/serenity.md @@ -0,0 +1,59 @@ +# `*-unknown-serenity` + +**Tier: 3** + +SerenityOS is a graphical Unix-like operating system for 64-bit x86, Arm, and RISC-V computers. + +## Target maintainers + +[@ADKaster](https://github.com/ADKaster) +[@nico](https://github.com/nico) + +## Requirements + +Host tools are not supported. `std` is not yet supported. There are no releases, as +SerenityOS is a hobbyist OS. + +A checkout of [`serenity`](https://github.com/SerenityOS/serenity) is required to build +the operating system image. The simplest cross-compilation environment is the +serenity [Ports tree](https://github.com/SerenityOS/serenity/tree/master/Ports#readme). +Out-of-tree cross-compilation has been shown to work, but is not a typical developer +workflow. + +Target binaries are in the ELF format and are expected to call into the Kernel +via libc. Direct syscalls are not supported due to an [`msyscall` mitigation] +(https://man.serenityos.org/man7/Mitigations.html#syscall-call-from-verification). + +## Building the target + +The targets can be built by enabling them for a `rustc` build, for example: + +```toml +[build] +build-stage = 1 +target = ["aarch64-unknown-serenity", "x86_64-unknown-serenity"] +``` + +## Building Rust programs + +Rust does not yet ship pre-compiled artifacts for this target. To compile for +this target, you will either need to build Rust with the target enabled (see +"Building the target" above), or build your own copy of `core` by using +`build-std` or similar. + +## Testing + +Target binaries can be included in a default developer QEMU image by copying +the binary and any required runtime dependencies into a subfolder under +`Build//Root` or `Build/clang/Root`, depending on the cross-compilation +toolchain used when building. + +Alternatively, a [`sync-local.sh`](https://github.com/SerenityOS/serenity/blob/master/Documentation/AdvancedBuildInstructions.md#customizing-the-disk-image) +script can be used to modify the disk image during an image build. + +Running the rust test suite is not yet supported. + +## Cross-compilation toolchains and C code + +The operating system is written in C++, so a C/C++ compiler is required. +The target triples are as expected, `$ARCH-unknown-serenity`. diff --git a/src/librustdoc/clean/cfg.rs b/src/librustdoc/clean/cfg.rs index de240d8f87092..1255da9d48d39 100644 --- a/src/librustdoc/clean/cfg.rs +++ b/src/librustdoc/clean/cfg.rs @@ -692,6 +692,7 @@ fn human_readable_target_os(os: Symbol) -> Option<&'static str> { Qurt => "QuRT", Redox => "Redox OS", Rtems => "RTEMS OS", + Serenity => "SerenityOS", Solaris => "Solaris", SolidAsp3 => "SOLID ASP3", TeeOs => "TEEOS", diff --git a/tests/assembly-llvm/targets/targets-elf.rs b/tests/assembly-llvm/targets/targets-elf.rs index 075863c673045..f93e6a24a3d60 100644 --- a/tests/assembly-llvm/targets/targets-elf.rs +++ b/tests/assembly-llvm/targets/targets-elf.rs @@ -112,6 +112,9 @@ //@ revisions: aarch64_unknown_nuttx //@ [aarch64_unknown_nuttx] compile-flags: --target aarch64-unknown-nuttx //@ [aarch64_unknown_nuttx] needs-llvm-components: aarch64 +//@ revisions: aarch64_unknown_serenity +//@ [aarch64_unknown_serenity] compile-flags: --target aarch64-unknown-serenity +//@ [aarch64_unknown_serenity] needs-llvm-components: aarch64 //@ revisions: aarch64_unknown_trusty //@ [aarch64_unknown_trusty] compile-flags: --target aarch64-unknown-trusty //@ [aarch64_unknown_trusty] needs-llvm-components: aarch64 @@ -781,6 +784,9 @@ //@ revisions: x86_64_unknown_redox //@ [x86_64_unknown_redox] compile-flags: --target x86_64-unknown-redox //@ [x86_64_unknown_redox] needs-llvm-components: x86 +//@ revisions: x86_64_unknown_serenity +//@ [x86_64_unknown_serenity] compile-flags: --target x86_64-unknown-serenity +//@ [x86_64_unknown_serenity] needs-llvm-components: x86 //@ revisions: x86_64_unknown_trusty //@ [x86_64_unknown_trusty] compile-flags: --target x86_64-unknown-trusty //@ [x86_64_unknown_trusty] needs-llvm-components: x86 diff --git a/tests/ui/check-cfg/cfg-crate-features.stderr b/tests/ui/check-cfg/cfg-crate-features.stderr index f2f7a235c2a0a..19666a8e57611 100644 --- a/tests/ui/check-cfg/cfg-crate-features.stderr +++ b/tests/ui/check-cfg/cfg-crate-features.stderr @@ -24,7 +24,7 @@ warning: unexpected `cfg` condition value: `does_not_exist` LL | #![cfg(not(target(os = "does_not_exist")))] | ^^^^^^^^^^^^^^^^^^^^^ | - = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `cygwin`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `helenos`, `hermit`, `horizon`, `hurd`, `hyperlight`, `illumos`, `ios`, `l4re`, `linux`, `lynxos178`, `macos`, `managarm`, `motor`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `ps3`, `psp`, `psx`, `qnx`, `qtee`, and `qurt` and 18 more + = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `cygwin`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `helenos`, `hermit`, `horizon`, `hurd`, `hyperlight`, `illumos`, `ios`, `l4re`, `linux`, `lynxos178`, `macos`, `managarm`, `motor`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `ps3`, `psp`, `psx`, `qnx`, `qtee`, and `qurt` and 19 more = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/well-known-values.stderr b/tests/ui/check-cfg/well-known-values.stderr index e2f8f8cfb571f..0600b0c33025b 100644 --- a/tests/ui/check-cfg/well-known-values.stderr +++ b/tests/ui/check-cfg/well-known-values.stderr @@ -232,7 +232,7 @@ warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` LL | target_os = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `cygwin`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `helenos`, `hermit`, `horizon`, `hurd`, `hyperlight`, `illumos`, `ios`, `l4re`, `linux`, `lynxos178`, `macos`, `managarm`, `motor`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `ps3`, `psp`, `psx`, `qnx`, `qtee`, `qurt`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `vexos`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm` + = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `cygwin`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `helenos`, `hermit`, `horizon`, `hurd`, `hyperlight`, `illumos`, `ios`, `l4re`, `linux`, `lynxos178`, `macos`, `managarm`, `motor`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `ps3`, `psp`, `psx`, `qnx`, `qtee`, `qurt`, `redox`, `rtems`, `serenity`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `vexos`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm` = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` @@ -305,7 +305,7 @@ LL | #[cfg(target_os = "linuz")] // testing that we suggest `linux` | | | help: there is a expected value with a similar name: `"linux"` | - = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `cygwin`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `helenos`, `hermit`, `horizon`, `hurd`, `hyperlight`, `illumos`, `ios`, `l4re`, `linux`, `lynxos178`, `macos`, `managarm`, `motor`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `ps3`, `psp`, `psx`, `qnx`, `qtee`, `qurt`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `vexos`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm` + = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `cygwin`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `helenos`, `hermit`, `horizon`, `hurd`, `hyperlight`, `illumos`, `ios`, `l4re`, `linux`, `lynxos178`, `macos`, `managarm`, `motor`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `ps3`, `psp`, `psx`, `qnx`, `qtee`, `qurt`, `redox`, `rtems`, `serenity`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `vexos`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm` = note: see for more information about checking conditional configuration warning: 31 warnings emitted From 555a77765455deef563b1adfec07c609e9411e14 Mon Sep 17 00:00:00 2001 From: Jonathan Pallant Date: Mon, 5 Oct 2026 18:16:09 +0100 Subject: [PATCH 08/39] Change all arm-none targets to skip frame pointers in leaf functions. This doesn't affect off-chip unwinding and backtraces, but makes leaf functions smaller and hence improves performance. My sample program went from 40924 to 40864 bytes (-0.15%), but probe-rs could still print a backtrace starting in a leaf function. --- compiler/rustc_target/src/spec/base/arm_none.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_target/src/spec/base/arm_none.rs b/compiler/rustc_target/src/spec/base/arm_none.rs index feb69bdd26cd9..c7cd4e4e70fd4 100644 --- a/compiler/rustc_target/src/spec/base/arm_none.rs +++ b/compiler/rustc_target/src/spec/base/arm_none.rs @@ -23,7 +23,7 @@ pub(crate) fn opts() -> TargetOptions { emit_debug_gdb_scripts: false, // LLVM is eager to trash the link register when calling `noreturn` functions, which // breaks debugging. Preserve LR by default to prevent that from happening. - frame_pointer: FramePointer::Always, + frame_pointer: FramePointer::NonLeaf, // ARM supports multiple ABIs for enums, the linux one matches the default of 32 here // but any arm-none or thumb-none target will be defaulted to 8 on GCC. c_enum_min_bits: Some(8), From 3eecf69b04dea073f5bb63c36cdad1a04787923a Mon Sep 17 00:00:00 2001 From: Jonathan Pallant Date: Tue, 6 Oct 2026 11:36:22 +0100 Subject: [PATCH 09/39] Fixup cmse-clear-padding test. It was relying on the "mov r7, sp" store of the frame pointer, which we now don't have for leaf functions. --- tests/assembly-llvm/cmse-clear-padding.rs | 60 ++++++++--------------- 1 file changed, 21 insertions(+), 39 deletions(-) diff --git a/tests/assembly-llvm/cmse-clear-padding.rs b/tests/assembly-llvm/cmse-clear-padding.rs index 271a844a6e82d..f8c5f317dc508 100644 --- a/tests/assembly-llvm/cmse-clear-padding.rs +++ b/tests/assembly-llvm/cmse-clear-padding.rs @@ -28,16 +28,14 @@ struct InnerPadding { } // CHECK-LABEL: c_ret_with_inner_padding: -// CHECK: mov r7, sp -// CHECK-NEXT: orr.w r0, r0, r1, lsl #16 +// CHECK: orr.w r0, r0, r1, lsl #16 #[no_mangle] extern "C" fn c_ret_with_inner_padding(a: u8, b: u16) -> InnerPadding { InnerPadding { a, b } } // CHECK-LABEL: cmse_ret_with_inner_padding: -// CHECK: mov r7, sp -// CHECK-NEXT: uxtb r0, r0 +// CHECK: uxtb r0, r0 // CHECK-NEXT: orr.w r0, r0, r1, lsl #16 #[no_mangle] extern "cmse-nonsecure-entry" fn cmse_ret_with_inner_padding(a: u8, b: u16) -> InnerPadding { @@ -45,10 +43,9 @@ extern "cmse-nonsecure-entry" fn cmse_ret_with_inner_padding(a: u8, b: u16) -> I } // CHECK-LABEL: c_call_with_inner_padding: -// CHECK: mov r7, sp -// CHECK-NEXT: mov r2, r0 +// CHECK: mov r2, r0 // CHECK-NEXT: bic r0, r1, #65280 -// CHECK-NEXT: pop.w {r7, lr} +// CHECK-NEXT: bx r2 #[no_mangle] extern "C" fn c_call_with_inner_padding(f: unsafe extern "C" fn(InnerPadding), x: InnerPadding) { unsafe { f(x) } @@ -74,16 +71,14 @@ struct TrailingPadding { } // CHECK-LABEL: c_ret_with_trailing_padding: -// CHECK: mov r7, sp -// CHECK-NEXT: orr.w r0, r0, r1, lsl #16 +// CHECK: orr.w r0, r0, r1, lsl #16 #[no_mangle] extern "C" fn c_ret_with_trailing_padding(a: u16, b: u8) -> TrailingPadding { TrailingPadding { a, b } } // CHECK-LABEL: cmse_ret_with_trailing_padding: -// CHECK: mov r7, sp -// CHECK-NEXT: uxtb r1, r1 +// CHECK: uxtb r1, r1 // CHECK-NEXT: uxth r0, r0 // CHECK-NEXT: orr.w r0, r0, r1, lsl #16 #[no_mangle] @@ -92,10 +87,9 @@ extern "cmse-nonsecure-entry" fn cmse_ret_with_trailing_padding(a: u16, b: u8) - } // CHECK-LABEL: c_call_with_trailing_padding: -// CHECK: mov r7, sp -// CHECK-NEXT: mov r2, r0 +// CHECK: mov r2, r0 // CHECK-NEXT: bic r0, r1, #-16777216 -// CHECK-NEXT: pop.w {r7, lr} +// CHECK-NEXT: bx r2 #[no_mangle] extern "C" fn c_call_with_trailing_padding( f: unsafe extern "C" fn(TrailingPadding), @@ -125,8 +119,8 @@ struct WideU8 { // `extern "C"` does not clear the padding. // // CHECK-LABEL: c_ret_with_wide_u8: -// CHECK: mov r7, sp -// CHECK-NEXT: orr.w r0, r0, r1, lsl #16 +// CHECK: orr.w r0, r0, r1, lsl #16 +// CHECK-NEXT: bx lr #[no_mangle] extern "C" fn c_ret_with_wide_u8(a: u8, b: u8) -> [WideU8; 2] { [WideU8 { a }, WideU8 { a: b }] @@ -135,8 +129,7 @@ extern "C" fn c_ret_with_wide_u8(a: u8, b: u8) -> [WideU8; 2] { // Upper bits are cleared by uxtb. // // CHECK-LABEL: cmse_ret_with_wide_u8: -// CHECK: mov r7, sp -// CHECK-NEXT: uxtb r1, r1 +// CHECK: uxtb r1, r1 // CHECK-NEXT: uxtb r0, r0 // CHECK-NEXT: orr.w r0, r0, r1, lsl #16 #[no_mangle] @@ -147,8 +140,7 @@ extern "cmse-nonsecure-entry" fn cmse_ret_with_wide_u8(a: u8, b: u8) -> [WideU8; // Same idea, the padding is recognized even through the MaybeUninit. // // CHECK-LABEL: cmse_ret_with_wide_u8_uninit: -// CHECK: mov r7, sp -// CHECK-NEXT: uxtb r0, r0 +// CHECK: uxtb r0, r0 // CHECK-NEXT: orr.w r0, r0, r1, lsl #16 // CHECK-NEXT: bic r0, r0, #-16711936 #[no_mangle] @@ -162,8 +154,7 @@ extern "cmse-nonsecure-entry" fn cmse_ret_with_wide_u8_uninit( // Same idea, the padding is recognized even through the MaybeUninit. // // CHECK-LABEL: cmse_ret_with_wide_u8_uninit_tuple: -// CHECK: mov r7, sp -// CHECK-NEXT: uxtb r0, r0 +// CHECK: uxtb r0, r0 // CHECK-NEXT: orr.w r0, r0, r1, lsl #16 // CHECK-NEXT: bic r0, r0, #-16711936 #[no_mangle] @@ -176,11 +167,9 @@ extern "cmse-nonsecure-entry" fn cmse_ret_with_wide_u8_uninit_tuple( // CHECK-LABEL: c_call_with_inner_wide_u8: // CHECK: push {r7, lr} -// CHECK-NEXT: .setfp r7, sp -// CHECK-NEXT: mov r7, sp // CHECK-NEXT: mov lr, r3 // CHECK-NEXT: mov r12, r0 -// CHECK-NEXT: ldr r3, [r7, #8] +// CHECK-NEXT: ldr r3, [sp, #8] // CHECK-NEXT: mov r0, r1 // CHECK-NEXT: mov r1, r2 // CHECK-NEXT: mov r2, lr @@ -219,8 +208,7 @@ enum VariantsSameSize { impl Copy for VariantsSameSize {} // CHECK-LABEL: variants_same_size: -// CHECK: mov r7, sp -// CHECK-NEXT: ldrh r1, [r0, #2] +// CHECK: ldrh r1, [r0, #2] // CHECK-NEXT: ldrb r0, [r0] // CHECK-NEXT: orr.w r0, r0, r1, lsl #16 #[no_mangle] @@ -239,8 +227,7 @@ impl Copy for VariantsDifferentSize {} // A uxtbeq conditionally clears the padding only for variant A. // // CHECK-LABEL: variants_different_size: -// CHECK: mov r7, sp -// CHECK-NEXT: ldrh r1, [r0, #2] +// CHECK: ldrh r1, [r0, #2] // CHECK-NEXT: ldrb r0, [r0] // CHECK-NEXT: lsls r2, r0, #31 // CHECK-NEXT: it eq @@ -266,8 +253,7 @@ impl Copy for UninhabitedVariant {} // Only `B` is inhabited, so reading the tag is not needed. // // CHECK-LABEL: uninhabited_variant: -// CHECK: mov r7, sp -// CHECK-NEXT: ldrh r1, [r0, #2] +// CHECK: ldrh r1, [r0, #2] // CHECK-NEXT: ldrb r0, [r0] // CHECK-NEXT: orr.w r0, r0, r1, lsl #16 #[no_mangle] @@ -277,8 +263,7 @@ extern "cmse-nonsecure-entry" fn uninhabited_variant(v: &UninhabitedVariant) -> // The single guaranteed-padding byte is cleared with a `bic` mask over the whole loaded word. // CHECK-LABEL: variants_same_size_array: -// CHECK: mov r7, sp -// CHECK-NEXT: ldr r0, [r0] +// CHECK: ldr r0, [r0] // CHECK-NEXT: bic r0, r0, #65280 #[no_mangle] #[expect(improper_ctypes_definitions)] @@ -289,8 +274,7 @@ extern "cmse-nonsecure-entry" fn variants_same_size_array( } // CHECK-LABEL: variants_different_size_array: -// CHECK: mov r7, sp -// CHECK-NEXT: ldrh r1, [r0, #2] +// CHECK: ldrh r1, [r0, #2] // CHECK-NEXT: ldrb r0, [r0] // CHECK-NEXT: lsls r2, r0, #31 // CHECK-NEXT: it eq @@ -305,8 +289,7 @@ extern "cmse-nonsecure-entry" fn variants_different_size_array( } // CHECK-LABEL: variants_same_size_tuple: -// CHECK: mov r7, sp -// CHECK-NEXT: ldrh r1, [r0, #2] +// CHECK: ldrh r1, [r0, #2] // CHECK-NEXT: ldrb r0, [r0] // CHECK-NEXT: orr.w r0, r0, r1, lsl #16 #[no_mangle] @@ -318,8 +301,7 @@ extern "cmse-nonsecure-entry" fn variants_same_size_tuple( } // CHECK-LABEL: variants_different_size_tuple: -// CHECK: mov r7, sp -// CHECK-NEXT: ldrh r1, [r0, #2] +// CHECK: ldrh r1, [r0, #2] // CHECK-NEXT: ldrb r0, [r0] // CHECK-NEXT: lsls r2, r0, #31 // CHECK-NEXT: it eq From b6aa106eb96325d3b436ba3505557c68fcccf9ab Mon Sep 17 00:00:00 2001 From: Yu Date: Wed, 21 Oct 2026 21:00:45 +0800 Subject: [PATCH 10/39] lint: keep type-changing casts in `raw_borrows_via_references` --- compiler/rustc_lint/src/diagnostics.rs | 2 +- .../src/raw_borrows_via_references.rs | 13 ++++++- .../lint-raw-borrows-via-references.fixed | 19 +++++++++ .../lint/lint-raw-borrows-via-references.rs | 19 +++++++++ .../lint-raw-borrows-via-references.stderr | 39 +++++++++++++++++-- 5 files changed, 87 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_lint/src/diagnostics.rs b/compiler/rustc_lint/src/diagnostics.rs index 6273414e9ccda..efb551d3d1073 100644 --- a/compiler/rustc_lint/src/diagnostics.rs +++ b/compiler/rustc_lint/src/diagnostics.rs @@ -3234,7 +3234,7 @@ pub(crate) enum RawBorrowViaReferenceSuggestion<'a> { #[suggestion_part(code = "&raw {mutbl} ")] left: Span, #[suggestion_part(code = "")] - right: Span, + right: Option, mutbl: &'a str, }, #[help("consider using `&raw {$mutbl}` for a safer and more explicit raw pointer")] diff --git a/compiler/rustc_lint/src/raw_borrows_via_references.rs b/compiler/rustc_lint/src/raw_borrows_via_references.rs index 74ab9ee39fadc..83a20846855dd 100644 --- a/compiler/rustc_lint/src/raw_borrows_via_references.rs +++ b/compiler/rustc_lint/src/raw_borrows_via_references.rs @@ -1,6 +1,7 @@ use rustc_ast::BorrowKind; use rustc_hir::{Expr, ExprKind, TyKind}; use rustc_lint_defs::{declare_lint, declare_lint_pass}; +use rustc_middle::ty::{self, Ty}; use crate::diagnostics::{RawBorrowViaReference, RawBorrowViaReferenceSuggestion}; use crate::{LateContext, LateLintPass, LintContext}; @@ -65,9 +66,19 @@ impl<'tcx> LateLintPass<'tcx> for RawBorrowsViaReferences { && addr_of_span.can_be_used_for_suggestions() && ty_span.can_be_used_for_suggestions() { + let drop_cast = cx.typeck_results().expr_ty_opt(exp).is_some_and(|borrow_ty| { + cx.typeck_results().expr_ty_opt(expr).is_some_and(|cast_ty| { + matches!( + borrow_ty.kind(), + ty::Ref(_, referent, ref_mutbl) + if cast_ty == Ty::new_ptr(cx.tcx, *referent, *ref_mutbl) + ) + }) + }); RawBorrowViaReferenceSuggestion::Spanful { left: borrow_span.until(addr_of_span), - right: addr_of_span.shrink_to_hi().until(ty_span.shrink_to_hi()), + right: drop_cast + .then(|| addr_of_span.shrink_to_hi().until(ty_span.shrink_to_hi())), mutbl: mutbl.ptr_str(), } } else { diff --git a/tests/ui/lint/lint-raw-borrows-via-references.fixed b/tests/ui/lint/lint-raw-borrows-via-references.fixed index 8b81164f60375..e8a9875727174 100644 --- a/tests/ui/lint/lint-raw-borrows-via-references.fixed +++ b/tests/ui/lint/lint-raw-borrows-via-references.fixed @@ -74,6 +74,25 @@ fn from_macro(x: *const i32) -> *const i32 { unsafe { ref_cast!(*x) } } +// Issue #164144: dropping a cast that changes the pointer type does not compile. +fn cast_changes_type() { + let mut x: [usize; 2] = [0, 0]; + let p = &raw mut x as *mut usize; + //~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references] + unsafe { + *p.add(1) = 1; + } + + let x: [usize; 2] = [0, 1]; + let p = &raw const x as *const usize; + //~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references] + assert_eq!(unsafe { *p.add(1) }, 1); + + let mut x = 0; + let _p = &raw mut x as *const i32; + //~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references] +} + fn main() { let a = 0; let a = &raw const a; diff --git a/tests/ui/lint/lint-raw-borrows-via-references.rs b/tests/ui/lint/lint-raw-borrows-via-references.rs index 621907bd15df0..be994e0beeb45 100644 --- a/tests/ui/lint/lint-raw-borrows-via-references.rs +++ b/tests/ui/lint/lint-raw-borrows-via-references.rs @@ -74,6 +74,25 @@ fn from_macro(x: *const i32) -> *const i32 { unsafe { ref_cast!(*x) } } +// Issue #164144: dropping a cast that changes the pointer type does not compile. +fn cast_changes_type() { + let mut x: [usize; 2] = [0, 0]; + let p = &mut x as *mut usize; + //~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references] + unsafe { + *p.add(1) = 1; + } + + let x: [usize; 2] = [0, 1]; + let p = &x as *const usize; + //~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references] + assert_eq!(unsafe { *p.add(1) }, 1); + + let mut x = 0; + let _p = &mut x as *const i32; + //~^ WARN creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers [raw_borrows_via_references] +} + fn main() { let a = 0; let a = &a as *const i32; diff --git a/tests/ui/lint/lint-raw-borrows-via-references.stderr b/tests/ui/lint/lint-raw-borrows-via-references.stderr index e31c467f76ee2..c861eb7f82ee8 100644 --- a/tests/ui/lint/lint-raw-borrows-via-references.stderr +++ b/tests/ui/lint/lint-raw-borrows-via-references.stderr @@ -101,7 +101,40 @@ LL | unsafe { ref_cast!(*x) } = help: consider using `&raw const` for a safer and more explicit raw pointer warning: creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers - --> $DIR/lint-raw-borrows-via-references.rs:79:13 + --> $DIR/lint-raw-borrows-via-references.rs:80:13 + | +LL | let p = &mut x as *mut usize; + | ^^^^^^^^^^^^^^^^^^^^ + | +help: consider using `&raw mut` for a safer and more explicit raw pointer + | +LL | let p = &raw mut x as *mut usize; + | +++ + +warning: creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers + --> $DIR/lint-raw-borrows-via-references.rs:87:13 + | +LL | let p = &x as *const usize; + | ^^^^^^^^^^^^^^^^^^ + | +help: consider using `&raw const` for a safer and more explicit raw pointer + | +LL | let p = &raw const x as *const usize; + | +++++++++ + +warning: creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers + --> $DIR/lint-raw-borrows-via-references.rs:92:14 + | +LL | let _p = &mut x as *const i32; + | ^^^^^^^^^^^^^^^^^^^^ + | +help: consider using `&raw mut` for a safer and more explicit raw pointer + | +LL | let _p = &raw mut x as *const i32; + | +++ + +warning: creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers + --> $DIR/lint-raw-borrows-via-references.rs:98:13 | LL | let a = &a as *const i32; | ^^^^^^^^^^^^^^^^ @@ -113,7 +146,7 @@ LL + let a = &raw const a; | warning: creating an intermediate reference implies aliasing requirements even when immediately cast to a raw pointers - --> $DIR/lint-raw-borrows-via-references.rs:83:13 + --> $DIR/lint-raw-borrows-via-references.rs:102:13 | LL | let b = &mut b as *mut i32; | ^^^^^^^^^^^^^^^^^^ @@ -124,5 +157,5 @@ LL - let b = &mut b as *mut i32; LL + let b = &raw mut b; | -warning: 10 warnings emitted +warning: 13 warnings emitted From 1d8eff3ca76532524ff40a789e47825ff106fa6d Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Thu, 22 Oct 2026 11:10:21 +0200 Subject: [PATCH 11/39] Add wasm64-unknown-emscripten target --- compiler/rustc_target/src/spec/base/wasm.rs | 52 +++++++++++- compiler/rustc_target/src/spec/mod.rs | 1 + .../spec/targets/wasm32_unknown_emscripten.rs | 46 +--------- .../spec/targets/wasm64_unknown_emscripten.rs | 21 +++++ .../spec/targets/wasm64_unknown_unknown.rs | 7 +- src/doc/rustc/book.toml | 3 + src/doc/rustc/src/SUMMARY.md | 2 +- src/doc/rustc/src/platform-support.md | 3 +- ...scripten.md => wasm-unknown-emscripten.md} | 85 ++++++++++++------- .../wasm32-unknown-unknown.md | 2 +- tests/assembly-llvm/targets/targets-elf.rs | 3 + 11 files changed, 141 insertions(+), 84 deletions(-) create mode 100644 compiler/rustc_target/src/spec/targets/wasm64_unknown_emscripten.rs rename src/doc/rustc/src/platform-support/{wasm32-unknown-emscripten.md => wasm-unknown-emscripten.md} (61%) diff --git a/compiler/rustc_target/src/spec/base/wasm.rs b/compiler/rustc_target/src/spec/base/wasm.rs index dd5bcff87cde1..0fb6f05ac2437 100644 --- a/compiler/rustc_target/src/spec/base/wasm.rs +++ b/compiler/rustc_target/src/spec/base/wasm.rs @@ -1,6 +1,8 @@ +use std::borrow::Cow; + use crate::spec::{ - BinaryFormat, Cc, LinkSelfContainedDefault, LinkerFlavor, PanicStrategy, RelocModel, - TargetOptions, TlsModel, add_link_args, cvs, + BinaryFormat, Cc, LinkArgs, LinkSelfContainedDefault, LinkerFlavor, Os, PanicStrategy, + RelocModel, TargetOptions, TlsModel, add_link_args, cvs, }; pub(crate) fn options() -> TargetOptions { @@ -139,3 +141,49 @@ pub(crate) fn options() -> TargetOptions { ..Default::default() } } + +pub(crate) fn emscripten_options() -> TargetOptions { + TargetOptions { + os: Os::Emscripten, + linker_flavor: LinkerFlavor::EmCc, + // emcc emits two files - a .js file to instantiate the wasm and supply platform + // functionality, and a .wasm file. + exe_suffix: ".js".into(), + linker: None, + // Reset flags for non-Em flavors back to empty to satisfy sanity checking tests. + pre_link_args: LinkArgs::new(), + post_link_args: TargetOptions::link_args(LinkerFlavor::EmCc, &["-sABORTING_MALLOC=0"]), + relocation_model: RelocModel::Pic, + // crt_static should always be true for an executable and always false + // for a shared library. There is no easy way to indicate this and it + // doesn't seem to matter much so we set crt_static_allows_dylibs to + // true and leave crt_static as true when linking dynamic libraries. + // wasi also sets crt_static_allows_dylibs: true so this is at least + // aligned between wasm targets. + crt_static_respected: true, + crt_static_default: true, + crt_static_allows_dylibs: true, + main_needs_argc_argv: true, + // Use the wasm C-ABI entry name from the tool-conventions BasicCABI + // spec rather than a raw `main`, as referenced by emscripten's crt/libc. + // Required for entry paths like `-sPROXY_TO_PTHREAD`, whose + // `crt1_proxy_main` links against `__main_argc_argv`. + entry_name: "__main_argc_argv".into(), + panic_strategy: PanicStrategy::Unwind, + no_default_libraries: false, + families: cvs!["unix", "wasm"], + // Explicitly override the `base::wasm`'s `llvm_args` back to empty. The + // base is to force using the most standard exception-handling + // instructions, when enabled, but this target is intended to follow + // Emscripten, which is whatever LLVM defaults to. + llvm_args: cvs![], + ..options() + } +} + +pub(crate) fn default_wasm64_features() -> Cow<'static, str> { + // Any engine that implements wasm64 will surely implement the rest of + // these features since they were all merged into the official spec by the + // time wasm64 was designed. + "+bulk-memory,+mutable-globals,+sign-ext,+nontrapping-fptoint".into() +} diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index ae17e37e29f86..fb8817382fa8a 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -1520,6 +1520,7 @@ supported_targets! { ("wasm32-wasip3", wasm32_wasip3), ("wasm32-wasip1-threads", wasm32_wasip1_threads), ("wasm32-wali-linux-musl", wasm32_wali_linux_musl), + ("wasm64-unknown-emscripten", wasm64_unknown_emscripten), ("wasm64-unknown-unknown", wasm64_unknown_unknown), ("thumbv6m-none-eabi", thumbv6m_none_eabi), diff --git a/compiler/rustc_target/src/spec/targets/wasm32_unknown_emscripten.rs b/compiler/rustc_target/src/spec/targets/wasm32_unknown_emscripten.rs index a084e71a0c71f..479b39d580494 100644 --- a/compiler/rustc_target/src/spec/targets/wasm32_unknown_emscripten.rs +++ b/compiler/rustc_target/src/spec/targets/wasm32_unknown_emscripten.rs @@ -1,48 +1,6 @@ -use crate::spec::{ - Arch, LinkArgs, LinkerFlavor, Os, PanicStrategy, RelocModel, Target, TargetMetadata, - TargetOptions, base, cvs, -}; +use crate::spec::{Arch, Target, TargetMetadata, base}; pub(crate) fn target() -> Target { - // Reset flags for non-Em flavors back to empty to satisfy sanity checking tests. - let pre_link_args = LinkArgs::new(); - let post_link_args = TargetOptions::link_args(LinkerFlavor::EmCc, &["-sABORTING_MALLOC=0"]); - - let opts = TargetOptions { - os: Os::Emscripten, - linker_flavor: LinkerFlavor::EmCc, - // emcc emits two files - a .js file to instantiate the wasm and supply platform - // functionality, and a .wasm file. - exe_suffix: ".js".into(), - linker: None, - pre_link_args, - post_link_args, - relocation_model: RelocModel::Pic, - // crt_static should always be true for an executable and always false - // for a shared library. There is no easy way to indicate this and it - // doesn't seem to matter much so we set crt_static_allows_dylibs to - // true and leave crt_static as true when linking dynamic libraries. - // wasi also sets crt_static_allows_dylibs: true so this is at least - // aligned between wasm targets. - crt_static_respected: true, - crt_static_default: true, - crt_static_allows_dylibs: true, - main_needs_argc_argv: true, - // Use the wasm C-ABI entry name from the tool-conventions BasicCABI - // spec rather than a raw `main`, as referenced by emscripten's crt/libc. - // Required for entry paths like `-sPROXY_TO_PTHREAD`, whose - // `crt1_proxy_main` links against `__main_argc_argv`. - entry_name: "__main_argc_argv".into(), - panic_strategy: PanicStrategy::Unwind, - no_default_libraries: false, - families: cvs!["unix", "wasm"], - // Explicitly override the `base::wasm`'s `llvm_args` back to empty. The - // base is to force using the most standard exception-handling - // instructions, when enabled, but this target is intended to follow - // Emscripten, which is whatever LLVM defaults to. - llvm_args: cvs![], - ..base::wasm::options() - }; Target { llvm_target: "wasm32-unknown-emscripten".into(), metadata: TargetMetadata { @@ -55,6 +13,6 @@ pub(crate) fn target() -> Target { data_layout: "e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-i128:128-f128:64-n32:64-S128-ni:1:10:20" .into(), arch: Arch::Wasm32, - options: opts, + options: base::wasm::emscripten_options(), } } diff --git a/compiler/rustc_target/src/spec/targets/wasm64_unknown_emscripten.rs b/compiler/rustc_target/src/spec/targets/wasm64_unknown_emscripten.rs new file mode 100644 index 0000000000000..1321ae85a1f25 --- /dev/null +++ b/compiler/rustc_target/src/spec/targets/wasm64_unknown_emscripten.rs @@ -0,0 +1,21 @@ +use crate::spec::{Arch, Target, TargetMetadata, TargetOptions, base}; + +pub(crate) fn target() -> Target { + Target { + llvm_target: "wasm64-unknown-emscripten".into(), + metadata: TargetMetadata { + description: Some("WebAssembly with Memory64 via Emscripten".into()), + tier: Some(3), + host_tools: Some(false), + std: Some(true), + }, + pointer_width: 64, + data_layout: "e-m:e-p:64:64-p10:8:8-p20:8:8-i64:64-i128:128-f128:64-n32:64-S128-ni:1:10:20" + .into(), + arch: Arch::Wasm64, + options: TargetOptions { + features: base::wasm::default_wasm64_features(), + ..base::wasm::emscripten_options() + }, + } +} diff --git a/compiler/rustc_target/src/spec/targets/wasm64_unknown_unknown.rs b/compiler/rustc_target/src/spec/targets/wasm64_unknown_unknown.rs index 7f9341b3ef91b..a512b5cc55675 100644 --- a/compiler/rustc_target/src/spec/targets/wasm64_unknown_unknown.rs +++ b/compiler/rustc_target/src/spec/targets/wasm64_unknown_unknown.rs @@ -32,15 +32,12 @@ pub(crate) fn target() -> Target { ], ); - // Any engine that implements wasm64 will surely implement the rest of these - // features since they were all merged into the official spec by the time - // wasm64 was designed. - options.features = "+bulk-memory,+mutable-globals,+sign-ext,+nontrapping-fptoint".into(); + options.features = base::wasm::default_wasm64_features(); Target { llvm_target: "wasm64-unknown-unknown".into(), metadata: TargetMetadata { - description: Some("WebAssembly".into()), + description: Some("WebAssembly with Memory64".into()), tier: Some(3), host_tools: Some(false), std: None, // ? diff --git a/src/doc/rustc/book.toml b/src/doc/rustc/book.toml index 565f6247dcb2d..abf2cb6571dd2 100644 --- a/src/doc/rustc/book.toml +++ b/src/doc/rustc/book.toml @@ -10,3 +10,6 @@ use-boolean-and = true [output.html.playground] runnable = false + +[output.html.redirect] +"/platform-support/wasm32-unknown-emscripten.html" = "/platform-support/wasm-unknown-emscripten.html" diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md index 7588b749a9bce..d0b1a0c6ab35d 100644 --- a/src/doc/rustc/src/SUMMARY.md +++ b/src/doc/rustc/src/SUMMARY.md @@ -145,13 +145,13 @@ - [\*-pc-windows-msvc](platform-support/windows-msvc.md) - [\*-uwp-windows-msvc](platform-support/uwp-windows-msvc.md) - [\*-wrs-vxworks](platform-support/vxworks.md) + - [wasm*-unknown-emscripten](platform-support/wasm-unknown-emscripten.md) - [wasm32-none-component](platform-support/wasm32-none-component.md) - [wasm32-wasip1](platform-support/wasm32-wasip1.md) - [wasm32-wasip1-threads](platform-support/wasm32-wasip1-threads.md) - [wasm32-wasip2](platform-support/wasm32-wasip2.md) - [wasm32-wasip3](platform-support/wasm32-wasip3.md) - [wasm32-wali-linux-musl](platform-support/wasm32-wali-linux.md) - - [wasm32-unknown-emscripten](platform-support/wasm32-unknown-emscripten.md) - [wasm32-unknown-unknown](platform-support/wasm32-unknown-unknown.md) - [wasm32v1-none](platform-support/wasm32v1-none.md) - [wasm64-unknown-unknown](platform-support/wasm64-unknown-unknown.md) diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index e890c83dbe9c7..0878ec1e8b194 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -215,7 +215,7 @@ target | std | notes [`thumbv8m.base-none-eabi`](platform-support/thumbv8m.base-none-eabi.md) | * | Bare Armv8-M Baseline [`thumbv8m.main-none-eabi`](platform-support/thumbv8m.main-none-eabi.md) | * | Bare Armv8-M Mainline [`thumbv8m.main-none-eabihf`](platform-support/thumbv8m.main-none-eabi.md) | * | Bare Armv8-M Mainline, hardfloat -[`wasm32-unknown-emscripten`](platform-support/wasm32-unknown-emscripten.md) | ✓ | WebAssembly via Emscripten +[`wasm32-unknown-emscripten`](platform-support/wasm-unknown-emscripten.md) | ✓ | WebAssembly via Emscripten [`wasm32-unknown-unknown`](platform-support/wasm32-unknown-unknown.md) | ✓ | WebAssembly [`wasm32-wasip1`](platform-support/wasm32-wasip1.md) | ✓ | WebAssembly with WASIp1 [`wasm32-wasip1-threads`](platform-support/wasm32-wasip1-threads.md) | ✓ | WebAssembly with WASI Preview 1 and threads @@ -449,6 +449,7 @@ target | std | host | notes [`thumbv8m.main-nuttx-eabi`](platform-support/nuttx.md) | ✓ | | ARMv8M Mainline with NuttX [`thumbv8m.main-nuttx-eabihf`](platform-support/nuttx.md) | ✓ | | ARMv8M Mainline with NuttX, hardfloat [`wasm32-none-component`](platform-support/wasm32-none-component.md) | * | | WebAssembly bare components +[`wasm64-unknown-emscripten`](platform-support/wasm-unknown-emscripten.md) | ✓ | WebAssembly with Memory64 via Emscripten [`wasm64-unknown-unknown`](platform-support/wasm64-unknown-unknown.md) | ? | | WebAssembly [`wasm32-wali-linux-musl`](platform-support/wasm32-wali-linux.md) | ? | | WebAssembly with [WALI](https://github.com/arjunr2/WALI) [`x86_64-apple-tvos`](platform-support/apple-tvos.md) | ✓ | | x86 64-bit tvOS diff --git a/src/doc/rustc/src/platform-support/wasm32-unknown-emscripten.md b/src/doc/rustc/src/platform-support/wasm-unknown-emscripten.md similarity index 61% rename from src/doc/rustc/src/platform-support/wasm32-unknown-emscripten.md rename to src/doc/rustc/src/platform-support/wasm-unknown-emscripten.md index af95f9bccb94c..c3c71b604319b 100644 --- a/src/doc/rustc/src/platform-support/wasm32-unknown-emscripten.md +++ b/src/doc/rustc/src/platform-support/wasm-unknown-emscripten.md @@ -1,29 +1,35 @@ -# `wasm32-unknown-emscripten` +# `wasm*-unknown-emscripten` -**Tier: 2** +Emscripten WebAssembly targets. -The `wasm32-unknown-emscripten` target is a WebAssembly compilation target which -uses the [Emscripten](https://emscripten.org/) compiler toolchain. Emscripten is +**Tier: 2 (without Host Tools)** + +- `wasm32-unknown-emscripten`: WebAssembly via Emscripten. + +**Tier: 3** + +- `wasm64-unknown-emscripten`: WebAssembly with Memory64 via Emscripten. + +These targets are WebAssembly compilation targets which use the +[Emscripten](https://emscripten.org/) compiler toolchain. Emscripten is primarily a C/C++ toolchain designed to make it as easy as possible to port C/C++ code written for Linux to run on the web or in other JavaScript runtimes such as Node. It thus provides POSIX-compatible (musl) `libc` and `libstd` implementations and many Linux APIs, access to the OpenGL and SDL APIs, and the ability to run arbitrary JavaScript code, all based on web APIs using JS glue code. With the -`wasm32-unknown-emscripten` target, Rust code can interoperate with Emscripten's +`wasm*-unknown-emscripten` targets, Rust code can interoperate with Emscripten's ecosystem, C/C++ and JS code, and web APIs. -One existing user of this target is the -[`pyodide` project](https://pyodide.org/) which provides a Python runtime in -WebAssembly using Emscripten and compiles Python extension modules written in Rust -to the `wasm32-unknown-emscripten` target. +One example user of these targets is the [`pyodide` project](https://pyodide.org/) +which provides a Python runtime in WebAssembly using Emscripten and compiles Python +extension modules written in Rust to the `wasm32-unknown-emscripten` target. If you want to generate a standalone WebAssembly binary that does not require access to the web APIs or the Rust standard library, the -[`wasm32-unknown-unknown`](./wasm32-unknown-unknown.md) target may be better -suited for you. However, [`wasm32-unknown-unknown`](./wasm32-unknown-unknown.md) -does not (easily) support interop with C/C++ code. Please refer to the -[wasm-bindgen](https://crates.io/crates/wasm-bindgen) crate in case you want to -interoperate with JavaScript with this target. +[`wasm32-unknown-unknown`](./wasm32-unknown-unknown.md) or +[`wasm64-unknown-unknown`](./wasm64-unknown-unknown.md) targets may be better +suited for you. Those targets however do not (easily) support interop with +C/C++ code. Like Emscripten, the WASI targets [`wasm32-wasip1`](./wasm32-wasip1.md), [`wasm32-wasip2`](./wasm32-wasip2.md), and @@ -33,17 +39,21 @@ of the Rust standard library. While the WASI targets are portable across different hosts (web and non-web), WASI has no standard way of accessing web APIs, whereas Emscripten has the ability to run arbitrary JS from WASM and access many web APIs. If you are only targeting the web and need to access web -APIs, the `wasm32-unknown-emscripten` target may be preferable. +APIs, these targets may be preferable. ## Target maintainers +`wasm32-unknown-emscripten`: [@hoodmane](https://github.com/hoodmane) [@juntyr](https://github.com/juntyr) +`wasm64-unknown-emscripten`: +[@hoodmane](https://github.com/hoodmane) + ## Requirements -This target is cross-compiled. The Emscripten compiler toolchain `emcc` must be -installed to link WASM binaries for this target. Emscripten 4.0.0 or newer is +These targets are cross-compiled. The Emscripten compiler toolchain `emcc` must be +installed to link WASM binaries for these targets. Emscripten 4.0.0 or newer is required. You can install `emcc` using: ```sh @@ -60,11 +70,12 @@ further details and instructions. Building this target can be done by: -* Configure the `wasm32-unknown-emscripten` target to get built. +* Configure the `wasm32-unknown-emscripten` or `wasm64-unknown-emscripten` target + to get built. * Ensure the `WebAssembly` target backend is not disabled in LLVM. These are all controlled through `bootstrap.toml` options. It should be possible -to build this target on any platform. A minimal example configuration would be: +to build these targets on any platform. A minimal example configuration would be: ```toml [llvm] @@ -72,12 +83,16 @@ targets = "WebAssembly" [build] build-stage = 1 -target = ["wasm32-unknown-emscripten"] +target = ["wasm32-unknown-emscripten", "wasm64-unknown-emscripten"] + +[rust] +lldb = true ``` ## Building Rust programs -Rust programs can be compiled by adding this target via rustup: +The `wasm32-unknown-emscripten` target is tier 2 and has a prebuilt standard library +available, so using it can be done by adding it via rustup: ```sh $ rustup target add wasm32-unknown-emscripten @@ -90,9 +105,16 @@ $ rustc foo.rs --target wasm32-unknown-emscripten $ file foo.wasm ``` +The `wasm64-unknown-emscripten` target is tier 3, and you must compile the standard +library yourself, such as with `-Zbuild-std`: + +```sh +$ cargo +nightly build -Zbuild-std --target wasm64-unknown-emscripten +``` + ## Cross-compilation -This target can be cross-compiled from any host. +These targets can be cross-compiled from any host. ## Emscripten ABI Compatibility @@ -117,11 +139,11 @@ any `-C link-arg`s that you compiled your Rust code with. ## Testing -This target is not extensively tested in CI for the rust-lang/rust repository. It +These targets are not extensively tested in CI for the rust-lang/rust repository. It can be tested locally, for example, with: ```sh -EMCC_CFLAGS="-s MAXIMUM_MEMORY=2GB" ./x.py test --target wasm32-unknown-emscripten --skip src/tools/linkchecker +EMCC_CFLAGS="-sSTACK_SIZE=1MB -sMAXIMUM_MEMORY=2GB -sALLOW_MEMORY_GROWTH -Wno-limited-postlink-optimizations" ./x.py test --target wasm32-unknown-emscripten,wasm64-unknown-emscripten --skip src/tools/linkchecker --skip src/tools/html-checker ``` To run these tests, both `emcc` and `node` need to be in your `$PATH`. You can @@ -133,7 +155,7 @@ to test the [`wasm32-wasip1`](./wasm32-wasip1.md) target instead. ## Conditionally compiling code -It's recommended to conditionally compile code for this target with: +It's recommended to conditionally compile code for these targets with: ```text #[cfg(target_os = "emscripten")] @@ -149,10 +171,10 @@ which do *not* use emscripten, which can be achieved with: ## Enabled WebAssembly features WebAssembly is an evolving standard which adds new features such as new -instructions over time. This target's default set of supported WebAssembly -features will additionally change over time. The `wasm32-unknown-emscripten` target -inherits the default settings of LLVM which typically, but not necessarily, matches -the default settings of Emscripten as well. At link time, `emcc` configures the +instructions over time. These targets' default set of supported WebAssembly +features will additionally change over time. These targets inherit the default +settings of LLVM which typically, but not necessarily, matches the default +settings of Emscripten as well. At link time, `emcc` configures the linker to use Emscripten's settings. Please refer to the [`wasm32-unknown-unknown`](./wasm32-unknown-unknown.md) @@ -160,7 +182,10 @@ target's documentation on which WebAssembly features Rust enables by default, ho features can be disabled, and how Rust code can be conditionally compiled based on which features are enabled. -Note that Rust code compiled for `wasm32-unknown-emscripten` currently enables +`wasm64-unknown-emscripten` has a different set of default target features, see +[`wasm64-unknown-unknown`](./wasm64-unknown-unknown.md) for details on those. + +Note that Rust code compiled for these targets currently enables `-fwasm-exceptions` (legacy WASM exceptions) by default unless the Rust code is compiled with `-Cpanic=abort`. diff --git a/src/doc/rustc/src/platform-support/wasm32-unknown-unknown.md b/src/doc/rustc/src/platform-support/wasm32-unknown-unknown.md index 362bf6f255d9d..3854eeda5eef9 100644 --- a/src/doc/rustc/src/platform-support/wasm32-unknown-unknown.md +++ b/src/doc/rustc/src/platform-support/wasm32-unknown-unknown.md @@ -47,7 +47,7 @@ This target currently has no equivalent in C/C++. There is no C/C++ toolchain for this target. While interop is theoretically possible it's recommended to instead use one of: -* [`wasm32-unknown-emscripten`](./wasm32-unknown-emscripten.md) - for web-based +* [`wasm32-unknown-emscripten`](./wasm-unknown-emscripten.md) - for web-based use cases the Emscripten toolchain is typically chosen for running C/C++. * [`wasm32-wasip1`](./wasm32-wasip1.md) - the wasi-sdk toolchain is used to compile C/C++ on this target and can interop with Rust code. WASI works on diff --git a/tests/assembly-llvm/targets/targets-elf.rs b/tests/assembly-llvm/targets/targets-elf.rs index 2908c659f9f02..2df7799cf3a52 100644 --- a/tests/assembly-llvm/targets/targets-elf.rs +++ b/tests/assembly-llvm/targets/targets-elf.rs @@ -682,6 +682,9 @@ //@ revisions: wasm32_wali_linux_musl //@ [wasm32_wali_linux_musl] compile-flags: --target wasm32-wali-linux-musl //@ [wasm32_wali_linux_musl] needs-llvm-components: webassembly +//@ revisions: wasm64_unknown_emscripten +//@ [wasm64_unknown_emscripten] compile-flags: --target wasm64-unknown-emscripten +//@ [wasm64_unknown_emscripten] needs-llvm-components: webassembly //@ revisions: wasm64_unknown_unknown //@ [wasm64_unknown_unknown] compile-flags: --target wasm64-unknown-unknown //@ [wasm64_unknown_unknown] needs-llvm-components: webassembly From 4b605e014cea1832245806b6020a653732a0f65b Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Mon, 5 Oct 2026 15:37:18 +0200 Subject: [PATCH 12/39] Disable a few more tests on wasm64 --- tests/ui/attributes/fn-align-dyn.rs | 2 +- tests/ui/cfg/conditional-compile-arch.rs | 3 +++ tests/ui/codegen/huge-stacks.rs | 1 + tests/ui/process/env-funky-keys.rs | 2 +- tests/ui/process/exec-env.rs | 2 +- tests/ui/std/fs-nul-byte-paths.rs | 2 +- tests/ui/threads-sendsync/sync-send-in-std.rs | 2 +- 7 files changed, 9 insertions(+), 5 deletions(-) diff --git a/tests/ui/attributes/fn-align-dyn.rs b/tests/ui/attributes/fn-align-dyn.rs index 91e2dab65a3cc..8b7b96a953762 100644 --- a/tests/ui/attributes/fn-align-dyn.rs +++ b/tests/ui/attributes/fn-align-dyn.rs @@ -1,5 +1,5 @@ //@ run-pass -//@ ignore-wasm32 aligning functions is not currently supported on wasm (#143368) +//@ ignore-wasm aligning functions is not currently supported on wasm (#143368) //@ ignore-backends: gcc // FIXME(#82232, #143834): temporarily renamed to mitigate `#[align]` nameres ambiguity diff --git a/tests/ui/cfg/conditional-compile-arch.rs b/tests/ui/cfg/conditional-compile-arch.rs index 0d57a50be530d..0ba76683a5c83 100644 --- a/tests/ui/cfg/conditional-compile-arch.rs +++ b/tests/ui/cfg/conditional-compile-arch.rs @@ -32,6 +32,9 @@ pub fn main() { } #[cfg(target_arch = "wasm32")] pub fn main() { } +#[cfg(target_arch = "wasm64")] +pub fn main() { } + #[cfg(target_arch = "sparc64")] pub fn main() { } diff --git a/tests/ui/codegen/huge-stacks.rs b/tests/ui/codegen/huge-stacks.rs index f661d8728be1f..a34cc8cf5d041 100644 --- a/tests/ui/codegen/huge-stacks.rs +++ b/tests/ui/codegen/huge-stacks.rs @@ -2,6 +2,7 @@ //@[optimized]compile-flags: -O //@ run-pass //@ only-64bit +//@ ignore-emscripten thread support requires -lpthread // Regression test for https://github.com/rust-lang/rust/issues/83060 // Verifies a program is not miscompiled if it includes a 4GB array on the stack diff --git a/tests/ui/process/env-funky-keys.rs b/tests/ui/process/env-funky-keys.rs index 193659bea293e..a9043e3e0fc97 100644 --- a/tests/ui/process/env-funky-keys.rs +++ b/tests/ui/process/env-funky-keys.rs @@ -3,7 +3,7 @@ //@ ignore-android segfaults //@ ignore-windows -//@ ignore-wasm32 no execve +//@ ignore-wasm no execve //@ ignore-sgx no execve //@ ignore-vxworks no execve //@ ignore-fuchsia no 'execve' diff --git a/tests/ui/process/exec-env.rs b/tests/ui/process/exec-env.rs index 9054b378f5679..39acb9b8b0814 100644 --- a/tests/ui/process/exec-env.rs +++ b/tests/ui/process/exec-env.rs @@ -1,6 +1,6 @@ //@ run-pass //@ exec-env:TEST_EXEC_ENV=22 -//@ ignore-wasm32 wasm runtimes aren't configured to inherit env vars yet +//@ ignore-wasm wasm runtimes aren't configured to inherit env vars yet //@ ignore-sgx unsupported use std::env; diff --git a/tests/ui/std/fs-nul-byte-paths.rs b/tests/ui/std/fs-nul-byte-paths.rs index 790123623474d..bc450c3398cb6 100644 --- a/tests/ui/std/fs-nul-byte-paths.rs +++ b/tests/ui/std/fs-nul-byte-paths.rs @@ -2,7 +2,7 @@ //@ run-pass #![allow(deprecated)] -//@ ignore-wasm32 no cwd +//@ ignore-wasm no cwd //@ ignore-sgx no files use std::{fs, io}; diff --git a/tests/ui/threads-sendsync/sync-send-in-std.rs b/tests/ui/threads-sendsync/sync-send-in-std.rs index ddf026236a8ed..f4034cf66a84f 100644 --- a/tests/ui/threads-sendsync/sync-send-in-std.rs +++ b/tests/ui/threads-sendsync/sync-send-in-std.rs @@ -1,6 +1,6 @@ //@ run-pass -//@ ignore-wasm32 networking not available +//@ ignore-wasm networking not available //@ ignore-sgx ToSocketAddrs cannot be used for DNS Resolution //@ ignore-fuchsia Req. test-harness networking privileges From f6b4997e9fcac12b677ef58dbcc3267aa7b245bb Mon Sep 17 00:00:00 2001 From: hina-kura49 <237669530+hina-kura49@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:38:34 +0900 Subject: [PATCH 13/39] Add regression tests for next-solver recursion overflows With `-Znext-solver=globally`, the examples in the reported issue used to ICE with "failed to resolve instance" during monomorphization. They now fail with a normal error instead. The first example was fixed by an earlier compiler change. `recursion-issue-164253-1.rs` is the example from the issue description. It should fail with "reached the recursion limit while instantiating". `recursion-issue-164253-2.rs` is a smaller example posted in a comment on the issue. It should fail with E0275 ("overflow evaluating the requirement"). Both tests run with the current and the next solver. They are `build-fail` because the ICE happened during monomorphization, and use `forbid-output: internal compiler error` so that the ICE cannot come back unnoticed. `recursion_depth_exceeding_limit` is allowed because it is unrelated to this issue and is planned to become an error. --- .../recursion-issue-164253-1.rs | 32 +++++++++++++++++++ .../recursion-issue-164253-2.rs | 32 +++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 tests/ui/codegen/normalization-overflow/recursion-issue-164253-1.rs create mode 100644 tests/ui/codegen/normalization-overflow/recursion-issue-164253-2.rs diff --git a/tests/ui/codegen/normalization-overflow/recursion-issue-164253-1.rs b/tests/ui/codegen/normalization-overflow/recursion-issue-164253-1.rs new file mode 100644 index 0000000000000..741b458777d5a --- /dev/null +++ b/tests/ui/codegen/normalization-overflow/recursion-issue-164253-1.rs @@ -0,0 +1,32 @@ +//@ revisions: current next +//@ ignore-compare-mode-next-solver (explicit revisions) +//@[next] compile-flags: -Znext-solver=globally +//@ compile-flags: -Copt-level=0 -Arecursion_depth_exceeding_limit +//@ build-fail +//@ edition: 2021 +//@ dont-check-compiler-stderr +//@ forbid-output: internal compiler error + +use std::{ + fs::File, + io::{Result, Write}}; +enum Tree { + Leaf(bool), + Parent(Vec)} +impl Tree { + fn serialize(self, mut writer: T) -> Result<()> { + match self { + Tree::Leaf(_) => Ok(()), + Tree::Parent(children) => { + for child in children { + child.serialize(writer.by_ref())?} + //~^ ERROR reached the recursion limit while instantiating + Ok(()) + } + } + } +} +fn main() -> Result<()> { + let buffer = File::create("")?; + Tree::Parent(vec![]).serialize(buffer) +} diff --git a/tests/ui/codegen/normalization-overflow/recursion-issue-164253-2.rs b/tests/ui/codegen/normalization-overflow/recursion-issue-164253-2.rs new file mode 100644 index 0000000000000..c0658829c5994 --- /dev/null +++ b/tests/ui/codegen/normalization-overflow/recursion-issue-164253-2.rs @@ -0,0 +1,32 @@ +//@ revisions: current next +//[current]~^ ERROR overflow evaluating the requirement +//@ ignore-compare-mode-next-solver (explicit revisions) +//@[next] compile-flags: -Znext-solver=globally +//@ compile-flags: -Copt-level=0 -Arecursion_depth_exceeding_limit +//@ build-fail +//@ dont-check-compiler-stderr +//@ forbid-output: internal compiler error +//[next]~? ERROR overflow evaluating the requirement + +fn main() { + decode(vec![]) +} +fn decode(bitstream: Vec) { + let mut bitstream_itr = bitstream.into_iter(); + match decode_packet(&mut bitstream_itr) { + _ => (), + } +} +fn decode_packets>(itr: &mut I) { + let res; + loop { + match decode_packet(itr) { + _ => {} + } + } + res +} +fn decode_packet>(itr: &mut I) -> Option<()> { + decode_packets(&mut itr.take(0)); + Some(()) +} From 3219037bbeb6666f7fbaa7601bd96c1cd4a1e614 Mon Sep 17 00:00:00 2001 From: Laine Taffin Altman Date: Wed, 14 Oct 2026 20:32:52 -0700 Subject: [PATCH 14/39] Update FEAT_FP8 to only depend on NEON/ASIMD This reflects the relaxation already present in LLVM. --- compiler/rustc_target/src/target_features.rs | 2 +- library/std_detect/src/detect/os/linux/aarch64.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index b209fe188bf86..572e194b5ac68 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -260,7 +260,7 @@ static AARCH64_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ &[], ), // FEAT_FP8 - ("fp8", Unstable(sym::aarch64_unstable_target_feature), &["faminmax", "lut", "bf16"]), + ("fp8", Unstable(sym::aarch64_unstable_target_feature), &["neon"]), // FEAT_FP8DOT2 ("fp8dot2", Unstable(sym::aarch64_unstable_target_feature), &["fp8dot4"]), // FEAT_FP8DOT4 diff --git a/library/std_detect/src/detect/os/linux/aarch64.rs b/library/std_detect/src/detect/os/linux/aarch64.rs index 936f06859491e..1bc5c7e1a6c47 100644 --- a/library/std_detect/src/detect/os/linux/aarch64.rs +++ b/library/std_detect/src/detect/os/linux/aarch64.rs @@ -369,7 +369,7 @@ impl AtHwcap { enable_feature(Feature::cssc, self.cssc); enable_feature(Feature::fpmr, self.fpmr); enable_feature(Feature::faminmax, self.faminmax); - let fp8 = self.f8cvt && self.faminmax && self.lut && self.bf16; + let fp8 = self.f8cvt && self.asimd; enable_feature(Feature::fp8, fp8); let fp8fma = self.f8fma && fp8; enable_feature(Feature::fp8fma, fp8fma); From c1cf18705fa49357a66a87020c6050405b2243c4 Mon Sep 17 00:00:00 2001 From: Laine Taffin Altman Date: Tue, 29 Sep 2026 16:56:20 -0700 Subject: [PATCH 15/39] Update std_detect support for AArch64 Darwin Current as of late September, 2026. --- .../src/detect/os/darwin/aarch64.rs | 40 +++++++++++++++---- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/library/std_detect/src/detect/os/darwin/aarch64.rs b/library/std_detect/src/detect/os/darwin/aarch64.rs index 35009a2b147cd..bf6d4d6bfdb8e 100644 --- a/library/std_detect/src/detect/os/darwin/aarch64.rs +++ b/library/std_detect/src/detect/os/darwin/aarch64.rs @@ -36,8 +36,16 @@ pub(crate) fn detect_features() -> cache::Initializer { // Armv8.0 features not using the standard identifiers let fp = _sysctlbyname(c"hw.optional.floatingpoint"); - let asimd = _sysctlbyname(c"hw.optional.AdvSIMD") || _sysctlbyname(c"hw.optional.arm.AdvSIMD"); + let asimd = _sysctlbyname(c"hw.optional.AdvSIMD") + || _sysctlbyname(c"hw.optional.arm.AdvSIMD") + || _sysctlbyname(c"hw.optional.arm.neon"); let crc_old = _sysctlbyname(c"hw.optional.armv8_crc32"); + let lse_old = _sysctlbyname(c"hw.optional.armv8_1_atomics"); + let fp16_old = _sysctlbyname(c"hw.optional.neon_fp16"); + let fhm_old = _sysctlbyname(c"hw.optional.armv8_2_fhm"); + let sha512_old = _sysctlbyname(c"hw.optional.armv8_2_sha512"); + let sha3_old = _sysctlbyname(c"hw.optional.armv8_2_sha3"); + let fcma_old = _sysctlbyname(c"hw.optional.armv8_3_compnum"); // Armv8 and Armv9 features using the standard identifiers let aes = _sysctlbyname(c"hw.optional.arm.FEAT_AES"); @@ -50,11 +58,14 @@ pub(crate) fn detect_features() -> cache::Initializer { let dpb = _sysctlbyname(c"hw.optional.arm.FEAT_DPB"); let dpb2 = _sysctlbyname(c"hw.optional.arm.FEAT_DPB2"); let ecv = _sysctlbyname(c"hw.optional.arm.FEAT_ECV"); + let faminmax = _sysctlbyname(c"hw.optional.arm.FEAT_FAMINMAX"); let fcma = _sysctlbyname(c"hw.optional.arm.FEAT_FCMA"); let fhm = _sysctlbyname(c"hw.optional.arm.FEAT_FHM"); let flagm = _sysctlbyname(c"hw.optional.arm.FEAT_FlagM"); let flagm2 = _sysctlbyname(c"hw.optional.arm.FEAT_FlagM2"); + let fp8 = _sysctlbyname(c"hw.optional.arm.FEAT_FP8"); let fp16 = _sysctlbyname(c"hw.optional.arm.FEAT_FP16"); + let fpmr = _sysctlbyname(c"hw.optional.arm.FEAT_FPMR"); let frintts = _sysctlbyname(c"hw.optional.arm.FEAT_FRINTTS"); let hbc = _sysctlbyname(c"hw.optional.arm.FEAT_HBC"); let i8mm = _sysctlbyname(c"hw.optional.arm.FEAT_I8MM"); @@ -63,23 +74,28 @@ pub(crate) fn detect_features() -> cache::Initializer { let rcpc2 = _sysctlbyname(c"hw.optional.arm.FEAT_LRCPC2"); let lse = _sysctlbyname(c"hw.optional.arm.FEAT_LSE"); let lse2 = _sysctlbyname(c"hw.optional.arm.FEAT_LSE2"); + let lut = _sysctlbyname(c"hw.optional.arm.FEAT_LUT"); let mte = _sysctlbyname(c"hw.optional.arm.FEAT_MTE"); let mte2 = _sysctlbyname(c"hw.optional.arm.FEAT_MTE2"); let pauth = _sysctlbyname(c"hw.optional.arm.FEAT_PAuth"); + let pauth_lr = _sysctlbyname(c"hw.optional.arm.FEAT_PAuth_LR"); let pmull = _sysctlbyname(c"hw.optional.arm.FEAT_PMULL"); let rdm = _sysctlbyname(c"hw.optional.arm.FEAT_RDM"); let sb = _sysctlbyname(c"hw.optional.arm.FEAT_SB"); let sha1 = _sysctlbyname(c"hw.optional.arm.FEAT_SHA1"); let sha256 = _sysctlbyname(c"hw.optional.arm.FEAT_SHA256"); - let sha3 = _sysctlbyname(c"hw.optional.arm.FEAT_SHA3"); let sha512 = _sysctlbyname(c"hw.optional.arm.FEAT_SHA512"); + let sha3 = _sysctlbyname(c"hw.optional.arm.FEAT_SHA3"); let sme = _sysctlbyname(c"hw.optional.arm.FEAT_SME"); let sme2 = _sysctlbyname(c"hw.optional.arm.FEAT_SME2"); let sme2p1 = _sysctlbyname(c"hw.optional.arm.FEAT_SME2p1"); let sme_b16b16 = _sysctlbyname(c"hw.optional.arm.FEAT_SME_B16B16"); + let sme_f8f16 = _sysctlbyname(c"hw.optional.arm.FEAT_SME_F8F16"); + let sme_f8f32 = _sysctlbyname(c"hw.optional.arm.FEAT_SME_F8F32"); let sme_f16f16 = _sysctlbyname(c"hw.optional.arm.FEAT_SME_F16F16"); let sme_f64f64 = _sysctlbyname(c"hw.optional.arm.FEAT_SME_F64F64"); let sme_i16i64 = _sysctlbyname(c"hw.optional.arm.FEAT_SME_I16I64"); + let sme_lutv2 = _sysctlbyname(c"hw.optional.arm.FEAT_SME_LUTv2"); let ssbs = _sysctlbyname(c"hw.optional.arm.FEAT_SSBS"); let sve_b16b16 = _sysctlbyname(c"hw.optional.arm.FEAT_SVE_B16B16"); let wfxt = _sysctlbyname(c"hw.optional.arm.FEAT_WFxT"); @@ -89,6 +105,8 @@ pub(crate) fn detect_features() -> cache::Initializer { // exist, and may potentially be exposed later. /* let afp = _sysctlbyname(c"hw.optional.arm.FEAT_AFP"); + let cpa = _sysctlbyname(c"hw.optional.arm.FEAT_CPA"); + let cpa2 = _sysctlbyname(c"hw.optional.arm.FEAT_CPA2"); let csv2 = _sysctlbyname(c"hw.optional.arm.FEAT_CSV2"); let csv3 = _sysctlbyname(c"hw.optional.arm.FEAT_CSV3"); let ebf16 = _sysctlbyname(c"hw.optional.arm.FEAT_EBF16"); @@ -131,35 +149,43 @@ pub(crate) fn detect_features() -> cache::Initializer { enable_feature(Feature::dpb, dpb); enable_feature(Feature::dpb2, dpb2); enable_feature(Feature::ecv, ecv); - enable_feature(Feature::fcma, fcma); - enable_feature(Feature::fhm, fhm); + enable_feature(Feature::faminmax, faminmax); + enable_feature(Feature::fcma, fcma_old || fcma); + enable_feature(Feature::fhm, fhm_old || fhm); enable_feature(Feature::flagm, flagm); enable_feature(Feature::flagm2, flagm2); enable_feature(Feature::fp, fp); - enable_feature(Feature::fp16, fp16); + enable_feature(Feature::fp8, fp8); + enable_feature(Feature::fp16, fp16_old || fp16); + enable_feature(Feature::fpmr, fpmr); enable_feature(Feature::frintts, frintts); enable_feature(Feature::hbc, hbc); enable_feature(Feature::i8mm, i8mm); enable_feature(Feature::jsconv, jsconv); - enable_feature(Feature::lse, lse); + enable_feature(Feature::lse, lse_old || lse); enable_feature(Feature::lse2, lse2); + enable_feature(Feature::lut, lut); enable_feature(Feature::mte, mte && mte2); enable_feature(Feature::paca, pauth); enable_feature(Feature::pacg, pauth); + enable_feature(Feature::pauth_lr, pauth_lr); enable_feature(Feature::pmull, aes && pmull); enable_feature(Feature::rcpc, rcpc); enable_feature(Feature::rcpc2, rcpc2); enable_feature(Feature::rdm, rdm); enable_feature(Feature::sb, sb); enable_feature(Feature::sha2, sha1 && sha256 && asimd); - enable_feature(Feature::sha3, sha512 && sha3 && asimd); + enable_feature(Feature::sha3, (sha512_old || sha512) && (sha3_old || sha3) && asimd); enable_feature(Feature::sme, sme); enable_feature(Feature::sme2, sme2); enable_feature(Feature::sme2p1, sme2p1); enable_feature(Feature::sme_b16b16, sme_b16b16); + enable_feature(Feature::sme_f8f16, sme_f8f16); + enable_feature(Feature::sme_f8f32, sme_f8f32); enable_feature(Feature::sme_f16f16, sme_f16f16); enable_feature(Feature::sme_f64f64, sme_f64f64); enable_feature(Feature::sme_i16i64, sme_i16i64); + enable_feature(Feature::sme_lutv2, sme_lutv2); enable_feature(Feature::ssbs, ssbs); enable_feature(Feature::sve_b16b16, sve_b16b16); enable_feature(Feature::wfxt, wfxt); From 4de7c3cfd4a31a157f5d37c10d9048bd7cc92340 Mon Sep 17 00:00:00 2001 From: Walnut Date: Mon, 26 Oct 2026 04:37:09 -0500 Subject: [PATCH 16/39] add wide pointer lldb visualizer --- src/etc/lldb_lookup.py | 56 +++++++++++++ src/etc/lldb_providers.py | 168 +++++++++++++++++++++++++++++++++++++- 2 files changed, 223 insertions(+), 1 deletion(-) diff --git a/src/etc/lldb_lookup.py b/src/etc/lldb_lookup.py index 957b8bb557f34..763efc898846e 100644 --- a/src/etc/lldb_lookup.py +++ b/src/etc/lldb_lookup.py @@ -39,6 +39,8 @@ StructSyntheticProvider, TupleSummaryProvider, TupleSyntheticProvider, + UnsizedSyntheticProvider, + WidePtrSyntheticProvider, f16SummaryProvider, f128SummaryProvider, ) @@ -194,6 +196,26 @@ def register_providers_compatibility(): DEFAULT_TYPE_OPTIONS | lldb.eTypeOptionHideChildren, ) + # Catches all types of the form `T[]` and `[T]` + # MUST be registered before slice and &str visualizers so that those specialized ones can + # override this one. + register_synth( + UnsizedSyntheticProvider, + lldb.SBTypeNameSpecifier( + MOD_PREFIX + is_empty_array_type.__name__, lldb.eFormatterMatchCallback + ), + ) + + # Handles generic wide pointers. + # MUST be registered before slice and &str visualizers so that those specialized ones can + # override this one. + register_synth( + WidePtrSyntheticProvider, + lldb.SBTypeNameSpecifier( + MOD_PREFIX + is_wide_ptr_type.__name__, lldb.eFormatterMatchCallback + ), + ) + # Tuple-structs register_synth( TupleSyntheticProvider, @@ -519,6 +541,40 @@ def is_msvc_f128(type: lldb.SBType, _dict: LLDBOpaque) -> bool: return type.GetName() == "f128" and type.IsAggregateType() +def is_wide_ptr_type(type: lldb.SBType, _dict: LLDBOpaque) -> bool: + if type.GetNumberOfFields() == 2: + data_ptr = None + length = None + + for f in type.fields: + if f.GetName() == "data_ptr": + data_ptr = f + elif f.GetName() == "length": + length = f + + return ( + length is not None + and data_ptr is not None + and data_ptr.GetType().IsPointerType() + ) + + return False + + +def is_empty_array_type(type: lldb.SBType, _dict: LLDBOpaque) -> bool: + # there's not a great way to check if an array is 0-sized. `GetByteSize` returns the + # same size as an array of length 1. The length isn't considered a template arg. + # `GetNumberOfFields` returns 0 regardless of the number of elements. + # While we could just check if the type name ends in `[]` (normalized) or starts + # with '[' and ends with ']' (non-normalized), it's a bit safer and more general + # purpose to compare it with the expected type. + if not type.IsArrayType(): + return False + expected = type.GetArrayElementType().GetArrayType(0) + + return type.GetName() == expected.GetName() + + def classify_rust_type(type: lldb.SBType, is_msvc: bool) -> RustType: if type.IsPointerType(): return RustType.Indirection diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index 4e0452d4cf77b..46ba7a16f0578 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -3,10 +3,12 @@ import sys from enum import Flag, auto from typing import TYPE_CHECKING, ClassVar, Dict, Generator, List, Optional +from weakref import WeakValueDictionary from lldb import ( SBData, SBError, + SBValue, eBasicTypeChar32, eBasicTypeDouble, eBasicTypeFloat, @@ -24,7 +26,7 @@ from rust_types import is_tuple_fields if TYPE_CHECKING: - from lldb import SBProcess, SBTarget, SBType, SBTypeStaticField, SBValue + from lldb import SBProcess, SBTarget, SBType, SBTypeStaticField # from lldb.formatters import Logger @@ -1733,3 +1735,167 @@ def StdNonZeroNumberSummaryProvider(valobj: SBValue, _dict: LLDBOpaque) -> str: return str(inner_inner.GetValueAsSigned()) else: return inner_inner.GetValue() + + +class WidePtrSyntheticProvider: + """ + Visualizer for pointers to dynamically sized types. This DOES NOT cover slices (`&[T]`) or + `&str`. Those have fast-path providers. This is specifically meant to handle references/pointers + to structs with unsized tails, such as: + + ``` + struct T { + a: u8, + b: f64, + c: [i32], + } + ``` + """ + + WIDE_PTR_BY_UNSIZED_CHILD_ID: ClassVar[WeakValueDictionary[int, SBValue]] = ( + WeakValueDictionary() + ) + + __slots__ = ("data_ptr", "unsized_child_depth", "valobj") + + def __init__(self, valobj: SBValue, _dict: LLDBOpaque): + self.valobj = valobj + self.data_ptr = valobj.GetChildMemberWithName("data_ptr") + self.unsized_child_depth = self._find_unsized_child() + + def _find_unsized_child(self) -> Optional[int]: + """Returns the depth of the unsized child. This is the number of times one must execute: + + ``` + valobj = valobj.GetChildAtIndex(valobj.GetNumChildren() - 1).GetNonSyntheticValue() + ``` + + to retrieve the unsized child + + """ + ty = self.data_ptr.Dereference().GetType() + depth = 0 + + while ty.IsValid() and depth < 1000: + depth += 1 + ty = ty.GetFieldAtIndex(max(0, ty.GetNumberOfFields() - 1)).GetType() + + if ty.IsArrayType(): + # ensure that we actually have a 0-length array as the final field + expected = ty.GetArrayElementType().GetArrayType(0) + if expected.GetName() == ty.GetName(): + return depth + + return None + + def _get_unsized_child(self) -> SBValue: + if self.unsized_child_depth is None: + return SBValue() + + valobj = self.data_ptr.GetNonSyntheticValue() + + for _ in range(self.unsized_child_depth): + valobj = valobj.GetChildAtIndex( + max(0, valobj.GetNumChildren() - 1) + ).GetNonSyntheticValue() + + return valobj + + def update(self): + # If the `UnsizedSyntheticProvider` can't find this by itself, we need to cache this class + # manually so that `UnsizedSyntheticProvider` can still look it up. + if LLDBFeature.GetParent not in FEATURE_FLAGS: + unsized_child = self._get_unsized_child() + if unsized_child.IsValid(): + print(f"found child (id#{unsized_child.GetID()}): {unsized_child}") + WidePtrSyntheticProvider.WIDE_PTR_BY_UNSIZED_CHILD_ID[ + unsized_child.GetID() + ] = self.valobj + + def has_children(self) -> bool: + return True + + def num_children(self) -> int: + return self.data_ptr.GetNumChildren() + + def get_child_idx(self, name: str) -> int: + return self.data_ptr.GetIndexOfChildWithName(name) + + def get_child_at_index(self, idx: int) -> Optional[SBValue]: + return self.data_ptr.GetChildAtIndex(idx) + + +class UnsizedSyntheticProvider: + valobj: SBValue + parent: SBValue + as_array: SBValue + len: int + __slots__ = ("as_array", "len", "parent", "type_name", "valobj") + + def __init__(self, valobj: SBValue, _dict: LLDBOpaque): + self.valobj = valobj + self.as_array = valobj + self.parent = SBValue() + self.len = 0 + + self.type_name = f"[{valobj.GetType().GetArrayElementType().GetName()}]" + + # `GetParent` allows us to traverse up the valobj tree until we find the pointer, which we + # can grab the length from. Without the ability to do that, we need to look up the parent + # from the cache + if LLDBFeature.GetParent in FEATURE_FLAGS: + self._find_parent_wideptr() + else: + self.parent = WidePtrSyntheticProvider.WIDE_PTR_BY_UNSIZED_CHILD_ID.get( + self.valobj.GetID(), self.parent + ) + + def _find_parent_wideptr(self): + valobj = self.valobj + # just in case + no_inf_loop = 0 + + while valobj.IsValid() and no_inf_loop < 1000: + no_inf_loop += 1 + valobj = valobj.GetParent().GetNonSyntheticValue() + + if ( + valobj.GetNumChildren() == 2 + and valobj.GetChildMemberWithName("data_ptr").IsValid() + and (len := valobj.GetChildMemberWithName("length")).IsValid() + ): + self.parent = valobj + self.len = len.GetValueAsUnsigned() + + def update(self): + if self.parent.IsValid(): + self.len = self.parent.GetChildMemberWithName("length").GetValueAsUnsigned( + 0 + ) + + self.as_array = self.valobj.Cast( + self.valobj.GetType().GetArrayElementType().GetArrayType(self.len) + ) + else: + self.as_array = self.valobj + self.len = 0 + + def has_children(self) -> bool: + return self.len != 0 + + def num_children(self): + return self.len + + def get_child_index(self, name: str) -> int: + index = name.lstrip("[").rstrip("]") + if index.isdigit(): + return int(index) + else: + return -1 + + def get_child_at_index(self, index: int) -> Optional[SBValue]: + if index < self.len: + return self.as_array.GetChildAtIndex(index) + + def get_type_name(self) -> str: + return self.type_name From c38cf3787e4178d54c36e365384a462fc2bf6185 Mon Sep 17 00:00:00 2001 From: Walnut Date: Mon, 26 Oct 2026 04:37:29 -0500 Subject: [PATCH 17/39] add wide pointer visualizer test --- .../lldb_input/non_windows.json | 427 ++++++++++++++++++ .../lldb_input/windows_gnu.json | 427 ++++++++++++++++++ tests/debuginfo/wideptr_visualizer/main.rs | 132 ++++++ 3 files changed, 986 insertions(+) create mode 100644 tests/debuginfo/wideptr_visualizer/lldb_input/non_windows.json create mode 100644 tests/debuginfo/wideptr_visualizer/lldb_input/windows_gnu.json create mode 100644 tests/debuginfo/wideptr_visualizer/main.rs diff --git a/tests/debuginfo/wideptr_visualizer/lldb_input/non_windows.json b/tests/debuginfo/wideptr_visualizer/lldb_input/non_windows.json new file mode 100644 index 0000000000000..c5db2e5b097a3 --- /dev/null +++ b/tests/debuginfo/wideptr_visualizer/lldb_input/non_windows.json @@ -0,0 +1,427 @@ +{ + "bless_metadata": { + "python_version": "3.14.8 (main, Oct 1 2026, 00:00:00) [GCC 16.2.1 20260819 (Red Hat 16.2.1-2)]", + "debugger_version": "lldb version 22.1.8", + "feature_flags": "LLDBFeature.StaticFields|TypeRecognizers|Float128" + }, + "breakpoints": [ + { + "a": { + "type": "*mut main::A", + "pretty_print": "{x:1, y:2, data:({f1:3, f2:4, f3:5}, {f1:6, f2:7, f3:8}, {f1:9, f2:10, f3:11})}", + "synthetic": "lldb_lookup.WidePtrSyntheticProvider", + "summary": "lldb_lookup.StructSummaryProvider", + "children": [ + { + "name": "x", + "type": "unsigned long", + "value": 1 + }, + { + "name": "y", + "type": "unsigned short", + "value": 2 + }, + { + "name": "data", + "type": "main::Sized[]", + "children": { + "type": "main::Sized", + "vals": [ + { + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 3 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 4 + }, + { + "name": "f3", + "type": "unsigned char", + "value": 5 + } + ] + }, + { + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 6 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 7 + }, + { + "name": "f3", + "type": "unsigned char", + "value": 8 + } + ] + }, + { + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 9 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 10 + }, + { + "name": "f3", + "type": "unsigned char", + "value": 11 + } + ] + } + ] + } + } + ] + }, + "b": { + "type": "*mut main::B", + "pretty_print": "{x:1, y:2, data:{f1:3, f2:4, f3:(5, 6, 7, 8, 9, 10, 11, 12, 13)}}", + "synthetic": "lldb_lookup.WidePtrSyntheticProvider", + "summary": "lldb_lookup.StructSummaryProvider", + "children": [ + { + "name": "x", + "type": "unsigned long", + "value": 1 + }, + { + "name": "y", + "type": "unsigned short", + "value": 2 + }, + { + "name": "data", + "type": "main::Unsized", + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 3 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 4 + }, + { + "name": "f3", + "type": "unsigned char[]", + "children": { + "type": "unsigned char", + "vals": [ + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13 + ] + } + } + ] + } + ] + }, + "a_ref": { + "type": "&mut main::A", + "pretty_print": "{x:1, y:2, data:({f1:3, f2:4, f3:5}, {f1:6, f2:7, f3:8}, {f1:9, f2:10, f3:11})}", + "synthetic": "lldb_lookup.WidePtrSyntheticProvider", + "summary": "lldb_lookup.StructSummaryProvider", + "children": [ + { + "name": "x", + "type": "unsigned long", + "value": 1 + }, + { + "name": "y", + "type": "unsigned short", + "value": 2 + }, + { + "name": "data", + "type": "main::Sized[]", + "children": { + "type": "main::Sized", + "vals": [ + { + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 3 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 4 + }, + { + "name": "f3", + "type": "unsigned char", + "value": 5 + } + ] + }, + { + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 6 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 7 + }, + { + "name": "f3", + "type": "unsigned char", + "value": 8 + } + ] + }, + { + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 9 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 10 + }, + { + "name": "f3", + "type": "unsigned char", + "value": 11 + } + ] + } + ] + } + } + ] + }, + "b_ref": { + "type": "&mut main::B", + "pretty_print": "{x:1, y:2, data:{f1:3, f2:4, f3:(5, 6, 7, 8, 9, 10, 11, 12, 13)}}", + "synthetic": "lldb_lookup.WidePtrSyntheticProvider", + "summary": "lldb_lookup.StructSummaryProvider", + "children": [ + { + "name": "x", + "type": "unsigned long", + "value": 1 + }, + { + "name": "y", + "type": "unsigned short", + "value": 2 + }, + { + "name": "data", + "type": "main::Unsized", + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 3 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 4 + }, + { + "name": "f3", + "type": "unsigned char[]", + "children": { + "type": "unsigned char", + "vals": [ + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13 + ] + } + } + ] + } + ] + } + } + ], + "types": { + "&mut main::A": { + "size": 16, + "type_class": 16384, + "fields": [ + { + "name": "data_ptr", + "type": "main::A *", + "offset": 0 + }, + { + "name": "length", + "type": "usize", + "offset": 8 + } + ] + }, + "&mut main::B": { + "size": 16, + "type_class": 16384, + "fields": [ + { + "name": "data_ptr", + "type": "main::B *", + "offset": 0 + }, + { + "name": "length", + "type": "usize", + "offset": 8 + } + ] + }, + "*mut main::A": { + "size": 16, + "type_class": 16384, + "fields": [ + { + "name": "data_ptr", + "type": "main::A *", + "offset": 0 + }, + { + "name": "length", + "type": "usize", + "offset": 8 + } + ] + }, + "*mut main::B": { + "size": 16, + "type_class": 16384, + "fields": [ + { + "name": "data_ptr", + "type": "main::B *", + "offset": 0 + }, + { + "name": "length", + "type": "usize", + "offset": 8 + } + ] + }, + "main::A *": { + "size": 8, + "type_class": 4096 + }, + "main::B *": { + "size": 8, + "type_class": 4096 + }, + "main::Sized": { + "size": 4, + "type_class": 16384, + "fields": [ + { + "name": "f1", + "type": "unsigned short", + "offset": 0 + }, + { + "name": "f2", + "type": "unsigned char", + "offset": 2 + }, + { + "name": "f3", + "type": "unsigned char", + "offset": 3 + } + ] + }, + "main::Sized[]": { + "size": 4, + "type_class": 1 + }, + "main::Unsized": { + "size": 4, + "type_class": 16384, + "fields": [ + { + "name": "f1", + "type": "unsigned short", + "offset": 0 + }, + { + "name": "f2", + "type": "unsigned char", + "offset": 2 + }, + { + "name": "f3", + "type": "unsigned char[]", + "offset": 3 + } + ] + }, + "unsigned char": { + "size": 1, + "type_class": 4, + "basic_type": 4 + }, + "unsigned char[]": { + "size": 1, + "type_class": 1 + }, + "unsigned long": { + "size": 8, + "type_class": 4, + "basic_type": 16 + }, + "unsigned short": { + "size": 2, + "type_class": 4, + "basic_type": 12 + }, + "usize": { + "size": 8, + "type_class": 32768, + "basic_type": 16 + } + } +} diff --git a/tests/debuginfo/wideptr_visualizer/lldb_input/windows_gnu.json b/tests/debuginfo/wideptr_visualizer/lldb_input/windows_gnu.json new file mode 100644 index 0000000000000..b9a8b652ee76e --- /dev/null +++ b/tests/debuginfo/wideptr_visualizer/lldb_input/windows_gnu.json @@ -0,0 +1,427 @@ +{ + "bless_metadata": { + "python_version": "3.11.9 (tags/v3.11.9:de54cf5, Apr 2 2024, 10:12:12) [MSC v.1938 64 bit (AMD64)]", + "debugger_version": "lldb version 23.1.3 (https://github.com/llvm/llvm-project revision 0d261d1ca552c95a8f007e061c787ac7132fbcbc)\n clang revision 0d261d1ca552c95a8f007e061c787ac7132fbcbc\n llvm revision 0d261d1ca552c95a8f007e061c787ac7132fbcbc", + "feature_flags": "LLDBFeature.StaticFields|TypeRecognizers|Float128|GetParent|ProviderDecorator" + }, + "breakpoints": [ + { + "a": { + "type": "*mut main::A", + "pretty_print": "{x:1, y:2, data:({f1:3, f2:4, f3:5}, {f1:6, f2:7, f3:8}, {f1:9, f2:10, f3:11})}", + "synthetic": "lldb_lookup.WidePtrSyntheticProvider", + "summary": "lldb_lookup.StructSummaryProvider", + "children": [ + { + "name": "x", + "type": "unsigned long long", + "value": 1 + }, + { + "name": "y", + "type": "unsigned short", + "value": 2 + }, + { + "name": "data", + "type": "main::Sized[]", + "children": { + "type": "main::Sized", + "vals": [ + { + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 3 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 4 + }, + { + "name": "f3", + "type": "unsigned char", + "value": 5 + } + ] + }, + { + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 6 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 7 + }, + { + "name": "f3", + "type": "unsigned char", + "value": 8 + } + ] + }, + { + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 9 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 10 + }, + { + "name": "f3", + "type": "unsigned char", + "value": 11 + } + ] + } + ] + } + } + ] + }, + "b": { + "type": "*mut main::B", + "pretty_print": "{x:1, y:2, data:{f1:3, f2:4, f3:(5, 6, 7, 8, 9, 10, 11, 12, 13)}}", + "synthetic": "lldb_lookup.WidePtrSyntheticProvider", + "summary": "lldb_lookup.StructSummaryProvider", + "children": [ + { + "name": "x", + "type": "unsigned long long", + "value": 1 + }, + { + "name": "y", + "type": "unsigned short", + "value": 2 + }, + { + "name": "data", + "type": "main::Unsized", + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 3 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 4 + }, + { + "name": "f3", + "type": "unsigned char[]", + "children": { + "type": "unsigned char", + "vals": [ + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13 + ] + } + } + ] + } + ] + }, + "a_ref": { + "type": "&mut main::A", + "pretty_print": "{x:1, y:2, data:({f1:3, f2:4, f3:5}, {f1:6, f2:7, f3:8}, {f1:9, f2:10, f3:11})}", + "synthetic": "lldb_lookup.WidePtrSyntheticProvider", + "summary": "lldb_lookup.StructSummaryProvider", + "children": [ + { + "name": "x", + "type": "unsigned long long", + "value": 1 + }, + { + "name": "y", + "type": "unsigned short", + "value": 2 + }, + { + "name": "data", + "type": "main::Sized[]", + "children": { + "type": "main::Sized", + "vals": [ + { + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 3 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 4 + }, + { + "name": "f3", + "type": "unsigned char", + "value": 5 + } + ] + }, + { + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 6 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 7 + }, + { + "name": "f3", + "type": "unsigned char", + "value": 8 + } + ] + }, + { + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 9 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 10 + }, + { + "name": "f3", + "type": "unsigned char", + "value": 11 + } + ] + } + ] + } + } + ] + }, + "b_ref": { + "type": "&mut main::B", + "pretty_print": "{x:1, y:2, data:{f1:3, f2:4, f3:(5, 6, 7, 8, 9, 10, 11, 12, 13)}}", + "synthetic": "lldb_lookup.WidePtrSyntheticProvider", + "summary": "lldb_lookup.StructSummaryProvider", + "children": [ + { + "name": "x", + "type": "unsigned long long", + "value": 1 + }, + { + "name": "y", + "type": "unsigned short", + "value": 2 + }, + { + "name": "data", + "type": "main::Unsized", + "children": [ + { + "name": "f1", + "type": "unsigned short", + "value": 3 + }, + { + "name": "f2", + "type": "unsigned char", + "value": 4 + }, + { + "name": "f3", + "type": "unsigned char[]", + "children": { + "type": "unsigned char", + "vals": [ + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13 + ] + } + } + ] + } + ] + } + } + ], + "types": { + "&mut main::A": { + "size": 16, + "type_class": 16384, + "fields": [ + { + "name": "data_ptr", + "type": "main::A *", + "offset": 0 + }, + { + "name": "length", + "type": "usize", + "offset": 8 + } + ] + }, + "&mut main::B": { + "size": 16, + "type_class": 16384, + "fields": [ + { + "name": "data_ptr", + "type": "main::B *", + "offset": 0 + }, + { + "name": "length", + "type": "usize", + "offset": 8 + } + ] + }, + "*mut main::A": { + "size": 16, + "type_class": 16384, + "fields": [ + { + "name": "data_ptr", + "type": "main::A *", + "offset": 0 + }, + { + "name": "length", + "type": "usize", + "offset": 8 + } + ] + }, + "*mut main::B": { + "size": 16, + "type_class": 16384, + "fields": [ + { + "name": "data_ptr", + "type": "main::B *", + "offset": 0 + }, + { + "name": "length", + "type": "usize", + "offset": 8 + } + ] + }, + "main::A *": { + "size": 8, + "type_class": 4096 + }, + "main::B *": { + "size": 8, + "type_class": 4096 + }, + "main::Sized": { + "size": 4, + "type_class": 16384, + "fields": [ + { + "name": "f1", + "type": "unsigned short", + "offset": 0 + }, + { + "name": "f2", + "type": "unsigned char", + "offset": 2 + }, + { + "name": "f3", + "type": "unsigned char", + "offset": 3 + } + ] + }, + "main::Sized[]": { + "size": 4, + "type_class": 1 + }, + "main::Unsized": { + "size": 4, + "type_class": 16384, + "fields": [ + { + "name": "f1", + "type": "unsigned short", + "offset": 0 + }, + { + "name": "f2", + "type": "unsigned char", + "offset": 2 + }, + { + "name": "f3", + "type": "unsigned char[]", + "offset": 3 + } + ] + }, + "unsigned char": { + "size": 1, + "type_class": 4, + "basic_type": 4 + }, + "unsigned char[]": { + "size": 1, + "type_class": 1 + }, + "unsigned long long": { + "size": 8, + "type_class": 4, + "basic_type": 18 + }, + "unsigned short": { + "size": 2, + "type_class": 4, + "basic_type": 12 + }, + "usize": { + "size": 8, + "type_class": 32768, + "basic_type": 18 + } + } +} diff --git a/tests/debuginfo/wideptr_visualizer/main.rs b/tests/debuginfo/wideptr_visualizer/main.rs new file mode 100644 index 0000000000000..4223b081da0d4 --- /dev/null +++ b/tests/debuginfo/wideptr_visualizer/main.rs @@ -0,0 +1,132 @@ +// Ensures wide pointers to dynamically sized types are visualized properly. Note that this does +// not include slice/str wide pointers, only wide pointers that point to dynamically sized +// user defined types. + +//@ compile-flags:-g +//@ min-llvm-lldb-version: 21.1.0 +//@ min-apple-lldb-version: 1703.0.236.21 + +// LLDB completely omits ZST-typed fields from the parsed *type*: +// ``` +// ignore-tidy-linelength +// (lldb) script lldb.frame.var("a").GetNonSyntheticValue().GetChildMemberWithName("data_ptr").Dereference().GetType() +// struct A { +// unsigned long long x; +// unsigned short y; +// } +// ``` +// +// Because of this, we can't even attempt to make this visualizer work on MSVC because we have no +// way to know that there's an unsized tail *at all*, let alone what type it's supposed to be. + +//@ ignore-msvc + +//@ ignore-backends: gcc + + +// === LLDB TESTS ================================================================================== + +//@ lldb-command:run + +// prevents `unsigned char[]` for printing as a string. +//@ lldb-command:type category disable system + +//@ lldb-repr:a +//@ lldb-repr:b +//@ lldb-repr:a_ref +//@ lldb-repr:b_ref + + +#![allow(unused)] +use std::{ + alloc::{Layout, alloc_zeroed}, + ptr, +}; + +// `Sized` and `Unsized` as well as `A` and `B` are laid out in such a way that if we stop +// outputting the correct debug info for `[T]`, they will be impossible to tell apart from their +// layouts in the DWARF/PDB data. Not only are the types all the same size, the unsized portions +// also "hide" within the natural padding of the parent struct + +#[derive(Clone, Copy)] +#[repr(C)] +struct Sized { + f1: u16, + f2: u8, + f3: u8, +} + +#[repr(C)] +struct Unsized { + f1: u16, + f2: u8, + f3: [u8], +} + +#[repr(C)] +struct A { + x: u64, + y: u16, + data: [Sized], +} + +#[repr(C)] +struct B { + x: u64, + y: u16, + data: Unsized, +} + +fn main() -> Result<(), std::alloc::LayoutError> { + unsafe { + // 10 bytes + let base_l = Layout::new::().extend(Layout::new::())?.0; + + // 10 + (4 * 3) = 22 bytes + let a_l = base_l.extend(Layout::array::(3)?)?.0; + + // 10 + 3 + (1 * 9) = 22 bytes + let b_l = base_l + .extend(Layout::new::())? + .0 + .extend(Layout::new::())? + .0 + .extend(Layout::array::(9)?)? + .0; + + let a = ptr::slice_from_raw_parts(alloc_zeroed(a_l), 3) as *mut A; + let b = ptr::slice_from_raw_parts_mut(alloc_zeroed(b_l), 9) as *mut B; + + let a_ref = a.as_mut().unwrap(); + + a_ref.x = 1; + a_ref.y = 2; + a_ref.data.copy_from_slice(&[ + Sized { + f1: 3, + f2: 4, + f3: 5, + }, + Sized { + f1: 6, + f2: 7, + f3: 8, + }, + Sized { + f1: 9, + f2: 10, + f3: 11, + }, + ]); + + let b_ref = b.as_mut().unwrap(); + + b_ref.x = 1; + b_ref.y = 2; + b_ref.data.f1 = 3; + b_ref.data.f2 = 4; + b_ref.data.f3.copy_from_slice(&[5, 6, 7, 8, 9, 10, 11, 12, 13]); + + Ok(()) // #break + } +} From f41bb6cc3ac27b0d3dfb15b36b5a9caafff67526 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandra=20Gonz=C3=A1lez?= Date: Wed, 4 Nov 2026 13:36:31 +0000 Subject: [PATCH 18/39] Get test hook out of start_codegen --- compiler/rustc_driver_impl/src/lib.rs | 2 ++ compiler/rustc_interface/src/passes.rs | 17 +++++++++-------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index f1919cab3957e..958e42cda583a 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -335,6 +335,8 @@ pub fn compiler_entrypoint(at_args: &[String], callbacks: &mut (dyn Callbacks + } } + passes::finish_and_emit_metadata(tcx); + let linker = Linker::codegen_and_build_linker(tcx, codegen_backend); if let Some(metrics_dir) = &sess.opts.unstable_opts.metrics_dir { diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 7df2ede5053b2..5cd62288503bd 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -895,6 +895,15 @@ pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) { } } +pub fn finish_and_emit_metadata<'tcx>(tcx: TyCtxt<'tcx>) { + // Hook for tests. + if let Some((def_id, _)) = tcx.entry_fn(()) + && find_attr!(tcx, def_id, RustcDelayedBugFromInsideQuery) + { + tcx.ensure_ok().trigger_delayed_bug(def_id); + } +} + pub static DEFAULT_QUERY_PROVIDERS: LazyLock = LazyLock::new(|| { let providers = &mut Providers::default(); providers.queries.analysis = analysis; @@ -1296,14 +1305,6 @@ pub(crate) fn start_codegen<'tcx>( tcx: TyCtxt<'tcx>, ) -> (Box, CrateInfo, EncodedMetadata) { tcx.sess.timings.start_section(tcx.sess.dcx(), TimingSection::Codegen); - - // Hook for tests. - if let Some((def_id, _)) = tcx.entry_fn(()) - && find_attr!(tcx, def_id, RustcDelayedBugFromInsideQuery) - { - tcx.ensure_ok().trigger_delayed_bug(def_id); - } - // Don't run this test assertions when not doing codegen. Compiletest tries to build // build-fail tests in check mode first and expects it to not give an error in that case. if tcx.sess.opts.output_types.should_codegen() { From c3b47017be3ed5094908c7f62a6c7d9ce0e78f72 Mon Sep 17 00:00:00 2001 From: Bee Date: Wed, 28 Oct 2026 15:15:49 +0000 Subject: [PATCH 19/39] Check type alignment is <= type size in data layout parser --- compiler/rustc_abi/src/lib.rs | 43 ++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 6d02f91ff7396..4fe2d7e3b8903 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -394,6 +394,7 @@ pub enum TargetDataLayoutError<'a> { InvalidBits { kind: &'a str, bit: &'a str, cause: &'a str, err: ParseIntError }, MissingAlignment { cause: &'a str }, InvalidAlignment { cause: &'a str, err: AlignFromBytesError }, + AlignmentTooLargeForType { cause: &'a str, align: Align }, InconsistentTargetArchitecture { dl: &'a str, target: &'a str }, InconsistentTargetPointerWidth { pointer_size: u64, target: u16 }, InvalidBitsSize { err: String }, @@ -426,6 +427,9 @@ impl Diagnostic<'_> for TargetDataLayoutError<'_> { .with_arg("cause", cause) .with_arg("err", err.to_string()) } + TargetDataLayoutError::AlignmentTooLargeForType { cause, align } => { + Diag::new(dcx, level, msg!("alignment of `{$align}` bytes in \"data-layout\" is too large for `{$cause}`")).with_arg("align", align.bytes()).with_arg("cause", cause) + } TargetDataLayoutError::InconsistentTargetArchitecture { dl, target } => { Diag::new(dcx, level, msg!("inconsistent target specification: \"data-layout\" claims architecture is {$dl}-endian, while \"target-endian\" is `{$target}`")) .with_arg("dl", dl).with_arg("target", target) @@ -477,22 +481,28 @@ impl TargetDataLayout { |s: &'a str, cause: &'a str| parse_bits(s, "size", cause).map(Size::from_bits); // Parse an alignment string. - let parse_align_str = |s: &'a str, cause: &'a str| { + let parse_align_str = |s: &'a str, cause: &'a str, size_bits: u64| { let align_from_bits = |bits| { Align::from_bits(bits) .map_err(|err| TargetDataLayoutError::InvalidAlignment { cause, err }) }; - let abi = parse_bits(s, "alignment", cause)?; - Ok(align_from_bits(abi)?) + let align_bits = parse_bits(s, "alignment", cause)?; + let align = align_from_bits(align_bits)?; + let max_align_bytes = size_bits.div_ceil(8).next_power_of_two(); + if align.bytes() > max_align_bytes { + Err(TargetDataLayoutError::AlignmentTooLargeForType { cause, align }) + } else { + Ok(align) + } }; // Parse an alignment sequence, possibly in the form `[:]`, // ignoring the secondary alignment specifications. - let parse_align_seq = |s: &[&'a str], cause: &'a str| { + let parse_align_seq = |s: &[&'a str], cause: &'a str, size_bits: u64| { if s.is_empty() { return Err(TargetDataLayoutError::MissingAlignment { cause }); } - parse_align_str(s[0], cause) + parse_align_str(s[0], cause, size_bits) }; let mut dl = TargetDataLayout::default(); @@ -508,12 +518,12 @@ impl TargetDataLayout { [p] if p.starts_with('P') => { dl.instruction_address_space = parse_address_space(&p[1..], "P")? } - ["a", a @ ..] => dl.aggregate_align = parse_align_seq(a, "a")?, - ["f16", a @ ..] => dl.f16_align = parse_align_seq(a, "f16")?, - ["f32", a @ ..] => dl.f32_align = parse_align_seq(a, "f32")?, - ["f64", a @ ..] => dl.f64_align = parse_align_seq(a, "f64")?, - ["f80", a @ ..] => dl.x87_f80_align = parse_align_seq(a, "f80")?, - ["f128", a @ ..] => dl.f128_align = parse_align_seq(a, "f128")?, + ["a", a @ ..] => dl.aggregate_align = parse_align_seq(a, "a", u64::MAX)?, + ["f16", a @ ..] => dl.f16_align = parse_align_seq(a, "f16", 16)?, + ["f32", a @ ..] => dl.f32_align = parse_align_seq(a, "f32", 32)?, + ["f64", a @ ..] => dl.f64_align = parse_align_seq(a, "f64", 64)?, + ["f80", a @ ..] => dl.x87_f80_align = parse_align_seq(a, "f80", 80)?, + ["f128", a @ ..] => dl.f128_align = parse_align_seq(a, "f128", 128)?, [p, s, a @ ..] if p.starts_with("p") => { let mut p = p.strip_prefix('p').unwrap(); let mut _is_fat = false; @@ -541,7 +551,7 @@ impl TargetDataLayout { }; let pointer_size = parse_size(s, "p-")?; - let pointer_align = parse_align_seq(a, "p-")?; + let pointer_align = parse_align_seq(a, "p-", pointer_size.bits())?; let info = PointerSpec { pointer_offset: pointer_size, pointer_size, @@ -585,9 +595,10 @@ impl TargetDataLayout { AddressSpace::ZERO }; + let pointer_size = parse_size(s, "p-")?; let info = PointerSpec { - pointer_size: parse_size(s, "p-")?, - pointer_align: parse_align_str(a, "p-")?, + pointer_size, + pointer_align: parse_align_str(a, "p-", pointer_size.bits())?, pointer_offset: parse_size(i, "p-")?, _is_fat, }; @@ -609,7 +620,7 @@ impl TargetDataLayout { parse_size(&s[1..], "i")?; // For the user error. continue; }; - let a = parse_align_seq(a, s)?; + let a = parse_align_seq(a, s, bits)?; match bits { 1 => dl.i1_align = a, 8 => dl.i8_align = a, @@ -627,7 +638,7 @@ impl TargetDataLayout { } [s, a @ ..] if s.starts_with('v') => { let v_size = parse_size(&s[1..], "v")?; - let a = parse_align_seq(a, s)?; + let a = parse_align_seq(a, s, v_size.bits())?; if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) { v.1 = a; continue; From baff3dc13348494c67e7b71f83fd89d2aa76eeff Mon Sep 17 00:00:00 2001 From: Bee Date: Wed, 28 Oct 2026 15:32:29 +0000 Subject: [PATCH 20/39] Remove `i1_align` and `i8_align` --- compiler/rustc_abi/src/callconv/reg.rs | 3 +-- compiler/rustc_abi/src/layout.rs | 6 +++--- compiler/rustc_abi/src/layout/simple.rs | 24 +++++++++++------------ compiler/rustc_abi/src/lib.rs | 10 +++------- compiler/rustc_codegen_llvm/src/consts.rs | 4 ++-- compiler/rustc_codegen_llvm/src/va_arg.rs | 6 +++--- compiler/rustc_middle/src/ty/layout.rs | 2 +- compiler/rustc_session/src/config/cfg.rs | 2 +- compiler/rustc_ty_utils/src/layout.rs | 4 ++-- 9 files changed, 27 insertions(+), 34 deletions(-) diff --git a/compiler/rustc_abi/src/callconv/reg.rs b/compiler/rustc_abi/src/callconv/reg.rs index dda7a45f9c2b7..393ec3801f577 100644 --- a/compiler/rustc_abi/src/callconv/reg.rs +++ b/compiler/rustc_abi/src/callconv/reg.rs @@ -76,8 +76,7 @@ impl Reg { let dl = cx.data_layout(); match self.kind { RegKind::Integer => match self.size.bits() { - 1 => dl.i1_align, - 2..=8 => dl.i8_align, + 1..=8 => Align::ONE, 9..=16 => dl.i16_align, 17..=32 => dl.i32_align, 33..=64 => dl.i64_align, diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index dd8652a05faab..720efd43dd248 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -365,7 +365,7 @@ impl LayoutCalculator { Some(present_first) => present_first, // Uninhabited because it has no variants, or only absent ones. None if is_enum => { - return Ok(LayoutData::never_type(&self.cx)); + return Ok(LayoutData::never_type()); } // If it's a struct, still compute a layout so that we can still compute the // field offsets. @@ -412,7 +412,7 @@ impl LayoutCalculator { F: Deref> + fmt::Debug + Copy, { let dl = self.cx.data_layout(); - let mut align = if repr.pack.is_some() { dl.i8_align } else { dl.aggregate_align }; + let mut align = if repr.pack.is_some() { Align::ONE } else { dl.aggregate_align }; let mut max_repr_align = repr.align; // If all the non-ZST fields have the same repr and union repr optimizations aren't @@ -601,7 +601,7 @@ impl LayoutCalculator { { let dl = self.cx.data_layout(); let pack = repr.pack; - let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align }; + let mut align = if pack.is_some() { Align::ONE } else { dl.aggregate_align }; let mut max_repr_align = repr.align; let mut in_memory_order: IndexVec = fields.indices().collect(); let optimize_field_order = !repr.inhibit_struct_field_reordering(); diff --git a/compiler/rustc_abi/src/layout/simple.rs b/compiler/rustc_abi/src/layout/simple.rs index f16daccc3c526..dff1f9ee44980 100644 --- a/compiler/rustc_abi/src/layout/simple.rs +++ b/compiler/rustc_abi/src/layout/simple.rs @@ -4,13 +4,13 @@ use rustc_hashes::Hash64; use rustc_index::{Idx, IndexVec}; use crate::{ - BackendRepr, FieldsShape, HasDataLayout, LayoutData, Niche, Primitive, Scalar, Size, Variants, + Align, BackendRepr, FieldsShape, HasDataLayout, LayoutData, Niche, Primitive, Scalar, Size, + Variants, }; /// "Simple" layout constructors that cannot fail. impl LayoutData { - pub fn unit(cx: &C, sized: bool) -> Self { - let dl = cx.data_layout(); + pub fn unit(sized: bool) -> Self { LayoutData { variants: Variants::Single { index: VariantIdx::new(0) }, fields: FieldsShape::Arbitrary { @@ -20,17 +20,16 @@ impl LayoutData { backend_repr: BackendRepr::Memory { sized }, largest_niche: None, uninhabited: false, - align: dl.i8_align, + align: Align::ONE, size: Size::ZERO, max_repr_align: None, - unadjusted_abi_align: dl.i8_align, + unadjusted_abi_align: Align::ONE, repr_c: false, randomization_seed: Hash64::new(0), } } - pub fn never_type(cx: &C) -> Self { - let dl = cx.data_layout(); + pub fn never_type() -> Self { // This is also used for uninhabited enums, so we use `Variants::Empty`. LayoutData { variants: Variants::Empty, @@ -38,10 +37,10 @@ impl LayoutData { backend_repr: BackendRepr::Memory { sized: true }, largest_niche: None, uninhabited: true, - align: dl.i8_align, + align: Align::ONE, size: Size::ZERO, max_repr_align: None, - unadjusted_abi_align: dl.i8_align, + unadjusted_abi_align: Align::ONE, repr_c: false, randomization_seed: Hash64::ZERO, } @@ -128,8 +127,7 @@ impl LayoutData { /// /// Uninhabited variants get pruned as part of the layout calculation, /// so this can be used after the fact to reconstitute a layout. - pub fn uninhabited_variant(cx: &C, index: VariantIdx, fields: usize) -> Self { - let dl = cx.data_layout(); + pub fn uninhabited_variant(index: VariantIdx, fields: usize) -> Self { LayoutData { variants: Variants::Single { index }, fields: match NonZero::new(fields) { @@ -142,10 +140,10 @@ impl LayoutData { backend_repr: BackendRepr::Memory { sized: true }, largest_niche: None, uninhabited: true, - align: dl.i8_align, + align: Align::ONE, size: Size::ZERO, max_repr_align: None, - unadjusted_abi_align: dl.i8_align, + unadjusted_abi_align: Align::ONE, repr_c: false, // Variant layouts never flow back into actual layout computations, // so dummy values are fine here. diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 4fe2d7e3b8903..1f2fcfc389f2c 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -318,8 +318,6 @@ pub struct PointerSpec { #[derive(Debug, PartialEq, Eq)] pub struct TargetDataLayout { pub endian: Endian, - pub i1_align: Align, - pub i8_align: Align, pub i16_align: Align, pub i32_align: Align, pub i64_align: Align, @@ -359,8 +357,6 @@ impl Default for TargetDataLayout { let align = |bits| Align::from_bits(bits).unwrap(); TargetDataLayout { endian: Endian::Big, - i1_align: align(8), - i8_align: align(8), i16_align: align(16), i32_align: align(32), i64_align: align(32), @@ -622,8 +618,8 @@ impl TargetDataLayout { }; let a = parse_align_seq(a, s, bits)?; match bits { - 1 => dl.i1_align = a, - 8 => dl.i8_align = a, + // i1 and i8 always have an alignment of 1 byte - this has already been + // checked by `parse_align_seq` above. 16 => dl.i16_align = a, 32 => dl.i32_align = a, 64 => dl.i64_align = a, @@ -1291,7 +1287,7 @@ impl Integer { let dl = cx.data_layout(); match self { - I8 => dl.i8_align, + I8 => Align::ONE, I16 => dl.i16_align, I32 => dl.i32_align, I64 => dl.i64_align, diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 33d48642812e6..dd6465f7fcf75 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -700,7 +700,7 @@ impl<'ll> CodegenCx<'ll, '_> { let g = self.define_global(&sym, llty).unwrap_or_else(|| { bug!("symbol `{}` is already defined", sym); }); - set_global_alignment(self, g, self.tcx.data_layout.i8_align); + set_global_alignment(self, g, Align::ONE); llvm::set_initializer(g, llval); llvm::set_linkage(g, llvm::Linkage::PrivateLinkage); llvm::set_section(g, c"__TEXT,__cstring,cstring_literals"); @@ -816,7 +816,7 @@ impl<'ll> CodegenCx<'ll, '_> { let methname_g = self.define_global(&methname_sym, methname_llty).unwrap_or_else(|| { bug!("symbol `{}` is already defined", methname_sym); }); - set_global_alignment(self, methname_g, self.tcx.data_layout.i8_align); + set_global_alignment(self, methname_g, Align::ONE); llvm::set_initializer(methname_g, methname_llval); llvm::set_linkage(methname_g, llvm::Linkage::PrivateLinkage); llvm::set_section( diff --git a/compiler/rustc_codegen_llvm/src/va_arg.rs b/compiler/rustc_codegen_llvm/src/va_arg.rs index 7c2c20c2671e4..cd987c4c3351d 100644 --- a/compiler/rustc_codegen_llvm/src/va_arg.rs +++ b/compiler/rustc_codegen_llvm/src/va_arg.rs @@ -351,7 +351,7 @@ fn emit_powerpc_va_arg<'ll, 'tcx>( bx.inbounds_ptradd(va_list_addr, bx.const_usize(1)) // fpr }; - let mut num_regs = bx.load(bx.type_i8(), num_regs_addr, dl.i8_align); + let mut num_regs = bx.load(bx.type_i8(), num_regs_addr, Align::ONE); // "Align" the register count when the type is passed as `i64`. if layout.size.bytes() == 8 && !is_passed_in_fprs { @@ -390,7 +390,7 @@ fn emit_powerpc_va_arg<'ll, 'tcx>( // Increase the used-register count. let new_num_regs = bx.add(num_regs, bx.cx.const_u8(reg_incr)); - bx.store(new_num_regs, num_regs_addr, dl.i8_align); + bx.store(new_num_regs, num_regs_addr, Align::ONE); bx.br(end); @@ -400,7 +400,7 @@ fn emit_powerpc_va_arg<'ll, 'tcx>( let mem_addr = { bx.switch_to_block(in_mem); - bx.store(bx.const_u8(max_regs), num_regs_addr, dl.i8_align); + bx.store(bx.const_u8(max_regs), num_regs_addr, Align::ONE); // Everything in the overflow area is rounded up to a size of at least 4. let overflow_area_align = Align::FOUR; diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 80bfbb5b551e0..cddfc56579e01 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -836,7 +836,7 @@ where ty::Adt(def, _) => def.variant(variant_index).fields.len(), _ => bug!("`ty_and_layout_for_variant` on unexpected type {}", this.ty), }; - tcx.mk_layout(LayoutData::uninhabited_variant(cx, variant_index, fields)) + tcx.mk_layout(LayoutData::uninhabited_variant(variant_index, fields)) } Variants::Multiple { .. } => { diff --git a/compiler/rustc_session/src/config/cfg.rs b/compiler/rustc_session/src/config/cfg.rs index 7df6549a07a70..fc4abc9e4f391 100644 --- a/compiler/rustc_session/src/config/cfg.rs +++ b/compiler/rustc_session/src/config/cfg.rs @@ -270,7 +270,7 @@ pub(crate) fn default_configuration(sess: &Session) -> Cfg { }); let mut has_atomic = false; for (i, align) in [ - (8, layout.i8_align), + (8, Align::ONE), (16, layout.i16_align), (32, layout.i32_align), (64, layout.i64_align), diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index 6404a062f2731..e09ae4497bf67 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -432,7 +432,7 @@ fn layout_of_uncached<'tcx>( } // The never type. - ty::Never => tcx.mk_layout(LayoutData::never_type(cx)), + ty::Never => tcx.mk_layout(LayoutData::never_type()), // Potentially-wide pointers. ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => { @@ -543,7 +543,7 @@ fn layout_of_uncached<'tcx>( // Odd unit types. ty::FnDef(..) | ty::Dynamic(_, _) | ty::Foreign(..) => { let sized = matches!(ty.kind(), ty::FnDef(..)); - tcx.mk_layout(LayoutData::unit(cx, sized)) + tcx.mk_layout(LayoutData::unit(sized)) } ty::Coroutine(def_id, args) => { From 39679b68ac1b6ef5caecba8899c1cc86cd871cb0 Mon Sep 17 00:00:00 2001 From: zakrad <49591476+zakrad@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:23:33 +0330 Subject: [PATCH 21/39] Add regression test for GCA associated const with a pattern type field --- .../assoc-const-pattern-type-field-162336.rs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 tests/ui/const-generics/gca/assoc-const-pattern-type-field-162336.rs diff --git a/tests/ui/const-generics/gca/assoc-const-pattern-type-field-162336.rs b/tests/ui/const-generics/gca/assoc-const-pattern-type-field-162336.rs new file mode 100644 index 0000000000000..c64a0d89e49a7 --- /dev/null +++ b/tests/ui/const-generics/gca/assoc-const-pattern-type-field-162336.rs @@ -0,0 +1,26 @@ +//! Regression test for . +//@ build-pass +//@ compile-flags: -Znext-solver + +#![feature(gca_min_const_items, gca_const_items)] + +use std::time::Duration; + +trait Trait { + const CONST: Duration; +} + +struct Thing; + +impl Trait for Thing { + const CONST: Duration = Duration::ZERO; +} + +fn generic() -> Duration { + T::CONST +} + +fn main() { + let _ = ::CONST; + let _ = generic::(); +} From 0e5af61f4d95b92965da0bc08a485cd01a88916e Mon Sep 17 00:00:00 2001 From: Francisco Gouveia Date: Thu, 12 Nov 2026 11:33:56 +0000 Subject: [PATCH 22/39] Refactor `rustc_show_spans` attribute to easily support more AST fragments --- compiler/rustc_ast_passes/src/show_spans.rs | 26 +++++++++++++-------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_ast_passes/src/show_spans.rs b/compiler/rustc_ast_passes/src/show_spans.rs index b28535653b0ed..d954907bd9356 100644 --- a/compiler/rustc_ast_passes/src/show_spans.rs +++ b/compiler/rustc_ast_passes/src/show_spans.rs @@ -1,3 +1,5 @@ +use std::mem; + use rustc_ast::visit::{self, Visitor}; use rustc_ast::{self as ast, ItemKind}; use rustc_attr_ir::{Attribute, AttributeKind, RustcShowSpansKind}; @@ -9,6 +11,11 @@ use crate::diagnostics; struct ShowSpans<'a> { sess: &'a Session, + kinds: ShowSpanKinds, +} + +#[derive(Clone, Copy, Default)] +struct ShowSpanKinds { expr: bool, ty: bool, path: bool, @@ -16,8 +23,7 @@ struct ShowSpans<'a> { impl<'a> Visitor<'a> for ShowSpans<'a> { fn visit_item(&mut self, item: &'a ast::Item) { - let saved = (self.expr, self.ty, self.path); - (self.expr, self.ty, self.path) = (false, false, false); + let saved = mem::take(&mut self.kinds); if let ItemKind::Fn(_) = &item.kind && let Some(Attribute::Parsed(AttributeKind::RustcShowSpans(kinds))) = @@ -25,37 +31,37 @@ impl<'a> Visitor<'a> for ShowSpans<'a> { { for kind in kinds { match kind { - RustcShowSpansKind::Expr => self.expr = true, - RustcShowSpansKind::Ty => self.ty = true, - RustcShowSpansKind::Path => self.path = true, + RustcShowSpansKind::Expr => self.kinds.expr = true, + RustcShowSpansKind::Ty => self.kinds.ty = true, + RustcShowSpansKind::Path => self.kinds.path = true, } } } visit::walk_item(self, item); // Recover the state. Needed if we are looking into nested items. - (self.expr, self.ty, self.path) = saved; + self.kinds = saved; } // We override it as to not report attribute paths as paths. fn visit_attribute(&mut self, _: &'a ast::Attribute) {} fn visit_expr(&mut self, e: &'a ast::Expr) { - if self.expr { + if self.kinds.expr { self.sess.dcx().emit_note(diagnostics::ShowSpan { span: e.span, kind: "expr" }); } visit::walk_expr(self, e); } fn visit_ty(&mut self, t: &'a ast::Ty) { - if self.ty { + if self.kinds.ty { self.sess.dcx().emit_note(diagnostics::ShowSpan { span: t.span, kind: "ty" }); } visit::walk_ty(self, t); } fn visit_path(&mut self, p: &'a ast::Path) { - if self.path { + if self.kinds.path { self.sess.dcx().emit_note(diagnostics::ShowSpan { span: p.span, kind: "path" }); } visit::walk_path(self, p); @@ -63,5 +69,5 @@ impl<'a> Visitor<'a> for ShowSpans<'a> { } pub fn check_crate(sess: &Session, krate: &ast::Crate) { - visit::walk_crate(&mut ShowSpans { sess, expr: false, ty: false, path: false }, krate); + visit::walk_crate(&mut ShowSpans { sess, kinds: ShowSpanKinds::default() }, krate); } From 031b8b4db4d0e33ac4aeea503d1ef4457f309da3 Mon Sep 17 00:00:00 2001 From: Francisco Gouveia Date: Thu, 12 Nov 2026 12:18:07 +0000 Subject: [PATCH 23/39] Support showing generic arguments in the `rustc_show_spans` attribute --- compiler/rustc_ast_passes/src/show_spans.rs | 11 +++++++++++ compiler/rustc_attr_ir/src/data_structures.rs | 1 + .../rustc_attr_parsing/src/attributes/rustc_dump.rs | 7 +++++-- compiler/rustc_span/src/symbol.rs | 1 + 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_ast_passes/src/show_spans.rs b/compiler/rustc_ast_passes/src/show_spans.rs index d954907bd9356..6e2ff11c5fd4b 100644 --- a/compiler/rustc_ast_passes/src/show_spans.rs +++ b/compiler/rustc_ast_passes/src/show_spans.rs @@ -19,6 +19,7 @@ struct ShowSpanKinds { expr: bool, ty: bool, path: bool, + generic_args: bool, } impl<'a> Visitor<'a> for ShowSpans<'a> { @@ -34,6 +35,7 @@ impl<'a> Visitor<'a> for ShowSpans<'a> { RustcShowSpansKind::Expr => self.kinds.expr = true, RustcShowSpansKind::Ty => self.kinds.ty = true, RustcShowSpansKind::Path => self.kinds.path = true, + RustcShowSpansKind::GenericArgs => self.kinds.generic_args = true, } } } @@ -66,6 +68,15 @@ impl<'a> Visitor<'a> for ShowSpans<'a> { } visit::walk_path(self, p); } + + fn visit_generic_args(&mut self, g: &'a ast::GenericArgs) { + if self.kinds.generic_args { + self.sess + .dcx() + .emit_note(diagnostics::ShowSpan { span: g.span(), kind: "generic_args" }); + } + visit::walk_generic_args(self, g); + } } pub fn check_crate(sess: &Session, krate: &ast::Crate) { diff --git a/compiler/rustc_attr_ir/src/data_structures.rs b/compiler/rustc_attr_ir/src/data_structures.rs index e32a31ea7e458..f6dc8ad651303 100644 --- a/compiler/rustc_attr_ir/src/data_structures.rs +++ b/compiler/rustc_attr_ir/src/data_structures.rs @@ -612,6 +612,7 @@ pub enum RustcShowSpansKind { Expr, Ty, Path, + GenericArgs, } #[derive(Clone, Debug, StableHash, Encodable, Decodable, PrintAttribute)] diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_dump.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_dump.rs index 07ce47b8858e2..9a2a9681f78ea 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_dump.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_dump.rs @@ -331,9 +331,12 @@ impl SingleAttributeParser for RustcShowSpans { sym::expr => RustcShowSpansKind::Expr, sym::ty => RustcShowSpansKind::Ty, sym::path => RustcShowSpansKind::Path, + sym::generic_args => RustcShowSpansKind::GenericArgs, _ => { - cx.adcx() - .expected_specific_argument(ident.span, &[sym::expr, sym::ty, sym::path]); + cx.adcx().expected_specific_argument( + ident.span, + &[sym::expr, sym::ty, sym::path, sym::generic_args], + ); continue; } }; diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index ea360c953afe8..c6f6417872e6c 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1091,6 +1091,7 @@ symbols! { generator_clone, generators, generic_arg_infer, + generic_args, generic_assert, generic_associated_types, generic_associated_types_extended, From 34d188d3ee9c4e12e37a3ed0887cd427b598cfc4 Mon Sep 17 00:00:00 2001 From: Alex Rao Date: Fri, 31 Jul 2026 12:07:33 -0400 Subject: [PATCH 24/39] Add new target: `i686-unknown-none` --- compiler/rustc_target/src/spec/mod.rs | 1 + .../src/spec/targets/i686_unknown_none.rs | 40 +++++++++++ src/doc/rustc/src/SUMMARY.md | 1 + src/doc/rustc/src/platform-support.md | 1 + .../src/platform-support/i686-unknown-none.md | 69 +++++++++++++++++++ tests/assembly-llvm/targets/targets-elf.rs | 3 + 6 files changed, 115 insertions(+) create mode 100644 compiler/rustc_target/src/spec/targets/i686_unknown_none.rs create mode 100644 src/doc/rustc/src/platform-support/i686-unknown-none.md diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 476970b10ea3a..b611696cb267f 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -1649,6 +1649,7 @@ supported_targets! { ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf), ("x86_64-unknown-none", x86_64_unknown_none), + ("i686-unknown-none", i686_unknown_none), ("aarch64-unknown-teeos", aarch64_unknown_teeos), diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_none.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_none.rs new file mode 100644 index 0000000000000..ef5573401c36e --- /dev/null +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_none.rs @@ -0,0 +1,40 @@ +use crate::spec::{ + Arch, Cc, LinkerFlavor, Lld, PanicStrategy, RelroLevel, RustcAbi, SanitizerSet, StackProbeType, + Target, TargetMetadata, TargetOptions, +}; + +pub(crate) fn target() -> Target { + let opts = TargetOptions { + cpu: "pentium4".into(), + plt_by_default: false, + max_atomic_width: Some(32), + stack_probes: StackProbeType::Inline, + position_independent_executables: true, + static_position_independent_executables: true, + relro_level: RelroLevel::Full, + linker_flavor: LinkerFlavor::Gnu(Cc::No, Lld::Yes), + linker: Some("rust-lld".into()), + rustc_abi: Some(RustcAbi::Softfloat), + features: "-mmx,-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2,+soft-float".into(), + supported_sanitizers: SanitizerSet::KCFI | SanitizerSet::KERNELADDRESS, + disable_redzone: true, + panic_strategy: PanicStrategy::Abort, + c_int_width: 32, + ..Default::default() + }; + Target { + llvm_target: "i686-unknown-none-elf".into(), + metadata: TargetMetadata { + description: Some("Freestanding/bare-metal x86 softfloat".into()), + tier: Some(3), + host_tools: Some(false), + std: Some(false), + }, + pointer_width: 32, + data_layout: + "e-m:e-p:32:32-p270:32:32-p271:32:32-p272:64:64-i128:128-f64:32:64-f80:32-n8:16:32-S128" + .into(), + arch: Arch::X86, + options: opts, + } +} diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md index abd2bb11104b0..3d4689fca8d0f 100644 --- a/src/doc/rustc/src/SUMMARY.md +++ b/src/doc/rustc/src/SUMMARY.md @@ -93,6 +93,7 @@ - [hexagon-unknown-linux-musl](platform-support/hexagon-unknown-linux-musl.md) - [hexagon-unknown-none-elf](platform-support/hexagon-unknown-none-elf.md) - [hexagon-unknown-qurt](platform-support/hexagon-unknown-qurt.md) + - [i686-unknown-none](platform-support/i686-unknown-none.md) - [illumos](platform-support/illumos.md) - [loongarch\*-unknown-linux-\*](platform-support/loongarch-linux.md) - [loongarch\*-unknown-none\*](platform-support/loongarch-none.md) diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index f5df7c48bee9a..6c21f228c355e 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -346,6 +346,7 @@ target | std | host | notes [`i686-unknown-helenos`](platform-support/helenos.md) | ✓ | | HelenOS IA-32 (see docs for pending issues) [`i686-unknown-hurd-gnu`](platform-support/hurd.md) | ✓ | ✓ | 32-bit GNU/Hurd (Pentium 4) [`i686-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | NetBSD/i386 (Pentium 4) +[`i686-unknown-none`](platform-support/i686-unknown-none.md) | * | | 32-bit Freestanding/bare-metal, softfloat [^x86_32-floats-return-ABI] [`i686-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | 32-bit OpenBSD (Pentium 4) `i686-uwp-windows-gnu` | ✓ | | [`i686-uwp-windows-msvc`](platform-support/uwp-windows-msvc.md) | ✓ | | [^win32-msvc-alignment] diff --git a/src/doc/rustc/src/platform-support/i686-unknown-none.md b/src/doc/rustc/src/platform-support/i686-unknown-none.md new file mode 100644 index 0000000000000..d1aa42322ba81 --- /dev/null +++ b/src/doc/rustc/src/platform-support/i686-unknown-none.md @@ -0,0 +1,69 @@ +# `i686-unknown-none` + +**Tier: 3** + +Freestanding/bare-metal x86 binaries in ELF format: firmware, kernels, etc. + +## Target maintainers + +[@alexhrao](https://github.com/alexhrao) + +## Requirements + +This target is cross-compiled. There is no support for `std`. There is no +default allocator, but it's possible to use `alloc` by supplying an allocator. + +By default, Rust code generated for this target does not use any vector or +floating-point registers (e.g. SSE, AVX). This allows the generated code to run +in environments, such as kernels, which may need to avoid the use of such +registers or which may have special considerations about the use of such +registers (e.g. saving and restoring them to avoid breaking userspace code +using the same registers). You can change code generation to use additional CPU +features via the `-C target-feature=` codegen options to rustc, or via the +`#[target_feature]` mechanism within Rust code. + +By default, code generated with this target should run on any `x86` +hardware; enabling additional target features may raise this baseline. + +On `i686-unknown-none`, `extern "C"` uses the [standard System V i386 calling +convention](https://gitlab.com/x86-psABIs/i386-ABI), without red zones. + +This target generated binaries in the ELF format. Any alternate formats or +special considerations for binary layout will require linker options or linker +scripts. + +## Building the target + +You can build Rust with support for the target by adding it to the `target` +list in `config.toml`: + +```toml +[build] +build-stage = 1 +target = ["i686-unknown-none"] +``` + +## Building Rust programs + +Rust does not yet ship pre-compiled artifacts for these targets. + +## Testing + +As `i686-unknown-none` supports a variety of different environments and does +not support `std`, this target does not support running the Rust testsuite. + +## Cross-compilation toolchains and C code + +If you want to compile C code along with Rust (such as for Rust crates with C +dependencies), you will need an appropriate `i686` toolchain. + +Rust *may* be able to use an `i686-linux-gnu-` toolchain with appropriate +standalone flags to build for this toolchain (depending on the assumptions of +that toolchain, see below), or you may wish to use a separate +`i686-unknown-none` (or `i686-elf-`) toolchain. + +On some `x86` hosts that use ELF binaries, you *may* be able to use the host +C toolchain, if it does not introduce assumptions about the host environment +that don't match the expectations of a standalone environment. Otherwise, you +may need a separate toolchain for standalone/freestanding development, just as +when cross-compiling from a non-`x86` platform. diff --git a/tests/assembly-llvm/targets/targets-elf.rs b/tests/assembly-llvm/targets/targets-elf.rs index 2908c659f9f02..e50cb72296d23 100644 --- a/tests/assembly-llvm/targets/targets-elf.rs +++ b/tests/assembly-llvm/targets/targets-elf.rs @@ -778,6 +778,9 @@ //@ revisions: x86_64_unknown_none //@ [x86_64_unknown_none] compile-flags: --target x86_64-unknown-none //@ [x86_64_unknown_none] needs-llvm-components: x86 +//@ revisions: i686_unknown_none +//@ [i686_unknown_none] compile-flags: --target i686-unknown-none +//@ [i686_unknown_none] needs-llvm-components: x86 //@ revisions: x86_64_unknown_openbsd //@ [x86_64_unknown_openbsd] compile-flags: --target x86_64-unknown-openbsd //@ [x86_64_unknown_openbsd] needs-llvm-components: x86 From d18cd3ef5b558437a4d4188f700463c6939b7fef Mon Sep 17 00:00:00 2001 From: Rain Date: Mon, 16 Nov 2026 10:45:07 -0800 Subject: [PATCH 25/39] illumos dist should enable ThinLTO and codegen-units=1 Currently, the x86_64-unknown-illumos dist builder doesn't enable ThinLTO for the compiler. Enable it, and `codegen-units=1`, for illumos. This speeds up builds by around 10%. Benchmarking on an AMD Ryzen 9 9955HX running Oxide's distribution of illumos ([Helios](https://github.com/oxidecomputer/helios)), with some of the crates in https://github.com/oxidecomputer/omicron/commit/e11a929aa2cbbd6e476cbcc836b871409492ff65: | crate | 1.99.1 official | 1.99.1 + this change | |-----------------|-----------------|----------------------| | nexus-db-schema | 21.29s | 19.04s (-10.6%) | | oxide-client | 21.29s | 19.19s (-9.9% | Another nice benefit is that librustc_driver shrinks from 298 MB to 253 MB. --- src/ci/docker/host-x86_64/dist-x86_64-illumos/Dockerfile | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/ci/docker/host-x86_64/dist-x86_64-illumos/Dockerfile b/src/ci/docker/host-x86_64/dist-x86_64-illumos/Dockerfile index 948c958595e08..2b4987da11a23 100644 --- a/src/ci/docker/host-x86_64/dist-x86_64-illumos/Dockerfile +++ b/src/ci/docker/host-x86_64/dist-x86_64-illumos/Dockerfile @@ -36,5 +36,8 @@ ENV \ ENV HOSTS=x86_64-unknown-illumos -ENV RUST_CONFIGURE_ARGS="--enable-extended --disable-docs" +ENV RUST_CONFIGURE_ARGS="--enable-extended \ + --disable-docs \ + --set rust.lto=thin \ + --set rust.codegen-units=1" ENV SCRIPT="python2.7 ../x.py dist --host $HOSTS --target $HOSTS" From c7432907158d91e029c8c4abef3e5512bcf3bc58 Mon Sep 17 00:00:00 2001 From: yan Date: Mon, 16 Nov 2026 11:33:02 -0800 Subject: [PATCH 26/39] rustc: avoid path dependent queries in source presence checks --- Cargo.lock | 1 + compiler/rustc_codegen_ssa/src/base.rs | 5 +-- compiler/rustc_crate_store/Cargo.toml | 1 + compiler/rustc_crate_store/src/cstore.rs | 35 ++++++++++++++++++ .../rustc_metadata/src/dependency_format.rs | 30 +++++++++------- .../src/rmeta/decoder/cstore_impl.rs | 1 + compiler/rustc_middle/src/queries.rs | 9 ++++- compiler/rustc_middle/src/query/erase.rs | 1 + tests/run-make/incremental-extern-path/foo.rs | 9 +++++ .../run-make/incremental-extern-path/rmake.rs | 36 +++++++++++++++++++ 10 files changed, 113 insertions(+), 15 deletions(-) create mode 100644 tests/run-make/incremental-extern-path/foo.rs create mode 100644 tests/run-make/incremental-extern-path/rmake.rs diff --git a/Cargo.lock b/Cargo.lock index a1eb7b0164f9d..209f14d2a6c87 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3924,6 +3924,7 @@ dependencies = [ name = "rustc_crate_store" version = "0.0.0" dependencies = [ + "bitflags", "rustc_abi", "rustc_attr_ir", "rustc_data_structures", diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 4361e192972f4..e165bb0ce4d4d 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -12,6 +12,7 @@ use rustc_ast::expand::allocator::{ use rustc_attr_ir::lang_items::LangItem; use rustc_attr_ir::target::Target; use rustc_attr_ir::{DebuggerVisualizerType, EiiDecl, EiiImpl, find_attr}; +use rustc_crate_store::CrateSourceFlags; use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet}; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; use rustc_data_structures::sync::{IntoDynSyncSend, par_map}; @@ -646,8 +647,8 @@ pub fn collect_debugger_visualizers_transitive( tcx.crates(()) .iter() .filter(|&cnum| { - let used_crate_source = tcx.used_crate_source(*cnum); - used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some() + tcx.used_crate_source_flags(*cnum) + .intersects(CrateSourceFlags::RMETA | CrateSourceFlags::RLIB) }) .flat_map(|&cnum| tcx.debugger_visualizers(cnum)), ) diff --git a/compiler/rustc_crate_store/Cargo.toml b/compiler/rustc_crate_store/Cargo.toml index 1857ae8130c10..4e965ec1c7378 100644 --- a/compiler/rustc_crate_store/Cargo.toml +++ b/compiler/rustc_crate_store/Cargo.toml @@ -5,6 +5,7 @@ edition = "2024" [dependencies] # tidy-alphabetical-start +bitflags = "2.4.1" rustc_abi = { path = "../rustc_abi" } rustc_attr_ir = { path = "../rustc_attr_ir" } rustc_data_structures = { path = "../rustc_data_structures" } diff --git a/compiler/rustc_crate_store/src/cstore.rs b/compiler/rustc_crate_store/src/cstore.rs index c8fe5562bdd59..bd674cbf33503 100644 --- a/compiler/rustc_crate_store/src/cstore.rs +++ b/compiler/rustc_crate_store/src/cstore.rs @@ -27,12 +27,47 @@ pub struct CrateSource { pub rmeta: Option, pub sdylib_interface: Option, } +/// Flags about where a crate came from on the local filesystem. +/// +/// Used to avoid introducing dependencies on absolute paths for incrementals when +/// the caller only needs to know if a field of `CrateSource` is_some. +#[derive(PartialEq, Clone, StableHash, Copy)] +pub struct CrateSourceFlags(u8); +bitflags::bitflags! { + impl CrateSourceFlags: u8 { + const DYLIB = 1 << 0; + const RLIB = 1 << 1; + const RMETA = 1 << 2; + const SDYLIB_INTERFACE = 1 << 3; + } +} +rustc_data_structures::external_bitflags_debug! { CrateSourceFlags } impl CrateSource { #[inline] pub fn paths(&self) -> impl Iterator { self.dylib.iter().chain(self.rlib.iter()).chain(self.rmeta.iter()) } + + #[inline] + pub fn flags(&self) -> CrateSourceFlags { + let mut flags = CrateSourceFlags::empty(); + + if self.dylib.is_some() { + flags |= CrateSourceFlags::DYLIB; + } + if self.rlib.is_some() { + flags |= CrateSourceFlags::RLIB; + } + if self.rmeta.is_some() { + flags |= CrateSourceFlags::RMETA; + } + if self.sdylib_interface.is_some() { + flags |= CrateSourceFlags::SDYLIB_INTERFACE; + } + + flags + } } #[derive(Encodable, BlobDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)] diff --git a/compiler/rustc_metadata/src/dependency_format.rs b/compiler/rustc_metadata/src/dependency_format.rs index 4a6c23a10c3af..37f369d9078da 100644 --- a/compiler/rustc_metadata/src/dependency_format.rs +++ b/compiler/rustc_metadata/src/dependency_format.rs @@ -51,8 +51,8 @@ //! Additionally, the algorithm is geared towards finding *any* solution rather //! than finding a number of solutions (there are normally quite a few). -use rustc_crate_store::CrateDepKind; use rustc_crate_store::LinkagePreference::{self, RequireDynamic, RequireStatic}; +use rustc_crate_store::{CrateDepKind, CrateSourceFlags}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir::def_id::{CrateNum, LOCAL_CRATE}; use rustc_index::IndexVec; @@ -148,8 +148,8 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList { if tcx.crate_dep_kind(cnum).macros_only() { continue; } - let src = tcx.used_crate_source(cnum); - if src.rlib.is_some() { + + if tcx.used_crate_source_flags(cnum).contains(CrateSourceFlags::RLIB) { continue; } sess.dcx().emit_err(RlibRequired { crate_name: tcx.crate_name(cnum) }); @@ -163,8 +163,9 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList { let all_dylibs = || { tcx.crates(()).iter().filter(|&&cnum| { !tcx.crate_dep_kind(cnum).macros_only() - && (tcx.used_crate_source(cnum).dylib.is_some() - || tcx.used_crate_source(cnum).sdylib_interface.is_some()) + && (tcx + .used_crate_source_flags(cnum) + .intersects(CrateSourceFlags::DYLIB | CrateSourceFlags::SDYLIB_INTERFACE)) }) }; @@ -237,12 +238,12 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList { // If the crate hasn't been included yet and it's not actually required // (e.g., it's a panic runtime) then we skip it here as well. for &cnum in tcx.crates(()).iter() { - let src = tcx.used_crate_source(cnum); - if src.dylib.is_none() + let src_flags = tcx.used_crate_source_flags(cnum); + if !src_flags.contains(CrateSourceFlags::DYLIB) && !formats.contains_key(&cnum) && tcx.crate_dep_kind(cnum) == CrateDepKind::Unconditional { - assert!(src.rlib.is_some() || src.rmeta.is_some()); + assert!(src_flags.intersects(CrateSourceFlags::RLIB | CrateSourceFlags::RMETA)); info!("adding staticlib: {}", tcx.crate_name(cnum)); add_library(tcx, cnum, RequireStatic, &mut formats, &mut unavailable_as_static); ret[cnum] = Linkage::Static; @@ -268,11 +269,16 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList { if cnum == LOCAL_CRATE { continue; } - let src = tcx.used_crate_source(cnum); + let src_flags = tcx.used_crate_source_flags(cnum); match *kind { Linkage::NotLinked | Linkage::IncludedFromDylib => {} - Linkage::Static if src.rlib.is_some() => continue, - Linkage::Dynamic if src.dylib.is_some() || src.sdylib_interface.is_some() => continue, + Linkage::Static if src_flags.contains(CrateSourceFlags::RLIB) => continue, + Linkage::Dynamic + if src_flags + .intersects(CrateSourceFlags::DYLIB | CrateSourceFlags::SDYLIB_INTERFACE) => + { + continue; + } kind => { let kind = match kind { Linkage::Static => "rlib", @@ -335,7 +341,7 @@ fn attempt_static(tcx: TyCtxt<'_>, unavailable: &mut Vec) -> Option { Arc::clone(&cdata.source) } + used_crate_source_flags => { cdata.source.flags() } debugger_visualizers => { cdata.get_debugger_visualizers(tcx) } exportable_items => { tcx.arena.alloc_from_iter(cdata.get_exportable_items(tcx)) } diff --git a/compiler/rustc_middle/src/queries.rs b/compiler/rustc_middle/src/queries.rs index 95b4364da4703..c869ee8ba1a7b 100644 --- a/compiler/rustc_middle/src/queries.rs +++ b/compiler/rustc_middle/src/queries.rs @@ -57,7 +57,8 @@ use rustc_attr_ir::diagnostic_items::DiagnosticItems; use rustc_attr_ir::lang_items::{LangItem, LanguageItems}; use rustc_attr_ir::{CanonicalSymbols, EiiDecl, EiiImpl, NotableTraitColor, StrippedCfgItem}; use rustc_crate_store::{ - CrateDepKind, CrateSource, ExternCrate, ForeignModule, LinkagePreference, NativeLib, + CrateDepKind, CrateSource, CrateSourceFlags, ExternCrate, ForeignModule, LinkagePreference, + NativeLib, }; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::sorted_map::SortedMap; @@ -2375,6 +2376,12 @@ rustc_queries! { separate_provide_extern } + query used_crate_source_flags(_: CrateNum) -> CrateSourceFlags { + eval_always + desc { "looking at source presence in a crate" } + separate_provide_extern + } + /// Returns the debugger visualizers defined for this crate. /// NOTE: This query has to be marked `eval_always` because it reads data /// directly from disk that is not tracked anywhere else. I.e. it diff --git a/compiler/rustc_middle/src/query/erase.rs b/compiler/rustc_middle/src/query/erase.rs index cee5bf6dccb80..6e9b2dfd0df6e 100644 --- a/compiler/rustc_middle/src/query/erase.rs +++ b/compiler/rustc_middle/src/query/erase.rs @@ -224,6 +224,7 @@ impl_erasable_for_types_with_no_type_params! { Ty<'_>, bool, rustc_crate_store::CrateDepKind, + rustc_crate_store::CrateSourceFlags, rustc_data_structures::svh::Svh, rustc_hir::Constness, rustc_hir::Defaultness, diff --git a/tests/run-make/incremental-extern-path/foo.rs b/tests/run-make/incremental-extern-path/foo.rs new file mode 100644 index 0000000000000..1aa26083937ac --- /dev/null +++ b/tests/run-make/incremental-extern-path/foo.rs @@ -0,0 +1,9 @@ +#![feature(no_core, rustc_attrs)] +#![no_core] +#![no_main] +#![rustc_partition_reused(module = "repro", cfg = "reuse")] + +extern crate minicore; + +#[unsafe(no_mangle)] +pub fn entry() {} diff --git a/tests/run-make/incremental-extern-path/rmake.rs b/tests/run-make/incremental-extern-path/rmake.rs new file mode 100644 index 0000000000000..4a37496a6b87e --- /dev/null +++ b/tests/run-make/incremental-extern-path/rmake.rs @@ -0,0 +1,36 @@ +// Test file compiling a program with incrementals under dir `a` then renaming to dir `b` and +// compiling again. Expects incremental reuse on the second invocation. +// +// Used to ensure incrementals aren't invalidated due to a dependency on the +// filesystem path. +//@ only-linux +//@ needs-backends: llvm + +use run_make_support::{rfs, rustc, rustc_minicore}; + +fn build(dir: &str, revision: &str) { + rustc() + .current_dir(dir) + .input("foo.rs") + .crate_name("repro") + .crate_type("bin") + .emit("obj") + .cfg(revision) + .extern_("minicore", "libminicore.rlib") + .incremental("incremental") + .debuginfo("2") + .arg("-Cpanic=abort") + .arg("-Zremap-cwd-prefix=.") + .arg("-Zquery-dep-graph") + .arg("-Zincremental-verify-ich") + .run(); +} + +fn main() { + rfs::create_dir("a"); + rustc_minicore().arg("-Cpanic=abort").output("a/libminicore.rlib").run(); + rfs::copy("foo.rs", "a/foo.rs"); + build("a", "cold"); + rfs::rename("a", "b"); + build("b", "reuse"); +} From c66f091b0acb3bae66dffbd16dc3cd0101261028 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:24:58 +0100 Subject: [PATCH 27/39] Prune un/under used methods of `ast::Attribute` --- compiler/rustc_ast/src/ast.rs | 11 ----- compiler/rustc_ast/src/attr/mod.rs | 48 ++----------------- .../rustc_attr_parsing/src/attributes/cfg.rs | 2 +- .../src/deriving/default.rs | 2 +- compiler/rustc_expand/src/diagnostics.rs | 18 ------- compiler/rustc_expand/src/expand.rs | 27 +---------- .../rustc_resolve/src/build_reduced_graph.rs | 2 +- .../src/attrs/allow_attributes.rs | 2 +- src/tools/clippy/clippy_utils/src/attrs.rs | 13 ++--- 9 files changed, 17 insertions(+), 108 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 8338df0c46e8f..43519d22848fc 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -3556,17 +3556,6 @@ impl GeneratedAttr { } } - pub fn is_word(&self) -> bool { - match self { - GeneratedAttr::AutomaticallyDerived => true, - GeneratedAttr::RustcConstUnstableDerived => false, - GeneratedAttr::Inline => true, - GeneratedAttr::DocHidden => false, - GeneratedAttr::CoverageOff => false, - GeneratedAttr::RustcTestMarker(_) => false, - GeneratedAttr::RustcTrivialFieldReads => false, - } - } pub fn value_str(&self) -> Option { match self { GeneratedAttr::AutomaticallyDerived => None, diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index 185650489fb32..92ed584076c97 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -8,7 +8,6 @@ use std::sync::atomic::{AtomicU32, Ordering}; use rustc_index::bit_set::GrowableBitSet; use rustc_span::{Ident, Span, Symbol, sym}; -use smallvec::{SmallVec, smallvec}; use thin_vec::{ThinVec, thin_vec}; use crate::ast::{ @@ -135,15 +134,6 @@ impl Attribute { } } - pub fn meta_kind(&self) -> Option { - match &self.kind { - AttrKind::Normal(normal) => normal.item.meta_kind(), - AttrKind::Synthetic(..) => unreachable!(), - AttrKind::DocComment(..) => None, - AttrKind::Generated(..) => None, - } - } - pub fn append_token_trees_to(&self, res: &mut Vec) { match &self.kind { AttrKind::Normal(normal) => normal @@ -202,15 +192,6 @@ impl Attribute { AttrKind::Synthetic(..) | AttrKind::DocComment(..) | AttrKind::Generated(..) => None, } } - - pub fn path_span(&self) -> Option { - match &self.kind { - AttrKind::Normal(attr) => Some(attr.item.path.span), - AttrKind::Synthetic(..) => unreachable!(), - AttrKind::DocComment(_, _) => None, - AttrKind::Generated(generated) => generated.path_span(), - } - } } impl AttrItem { @@ -282,6 +263,11 @@ impl AttrItem { pub fn meta_kind(&self) -> Option { MetaItemKind::from_attr_args(&self.args) } + + /// Returns whether the attribute is a path, without any arguments. + pub fn is_word(&self) -> bool { + matches!(self.args, AttrArgs::Empty) + } } impl MetaItem { @@ -891,30 +877,6 @@ impl Attribute { names.iter().any(|&name| self.has_name(name)) } - /// Returns whether the attribute is a path, without any arguments. - pub fn is_word(&self) -> bool { - match &self.kind { - AttrKind::Normal(normal) => matches!(normal.item.args, AttrArgs::Empty), - AttrKind::Synthetic(..) => unreachable!(), - AttrKind::DocComment(..) => false, - AttrKind::Generated(generated) => generated.is_word(), - } - } - - pub fn path(&self) -> SmallVec<[Symbol; 1]> { - use SyntheticAttr::*; - match &self.kind { - AttrKind::Normal(normal) => { - normal.item.path.segments.iter().map(|i| i.ident.name).collect() - } - AttrKind::Synthetic(CfgTrace(_)) => smallvec![sym::cfg], - AttrKind::Synthetic(CfgAttrTrace(_)) => smallvec![sym::cfg_attr], - AttrKind::Synthetic(TestEntrypoint) => smallvec![], - AttrKind::DocComment(_, _) => smallvec![sym::doc], - AttrKind::Generated(generated) => generated.path().iter().copied().collect(), - } - } - /// Returns the documentation if this is a doc comment or a sugared doc comment. /// * `///doc` returns `Some("doc")`. /// * `#[doc = "doc"]` returns `Some("doc")`. diff --git a/compiler/rustc_attr_parsing/src/attributes/cfg.rs b/compiler/rustc_attr_parsing/src/attributes/cfg.rs index d904e120eb349..8846ed766e7f3 100644 --- a/compiler/rustc_attr_parsing/src/attributes/cfg.rs +++ b/compiler/rustc_attr_parsing/src/attributes/cfg.rs @@ -395,7 +395,7 @@ fn parse_cfg_attr_internal<'a>( attribute.span, item.span, attribute.style, - AttrPath { segments: attribute.path().into_boxed_slice(), span: attribute.span }, + AttrPath::from_ast(&item.path, identity), Some(item.unsafety), AttributeSafety::Normal, ParsedDescription::Attribute, diff --git a/compiler/rustc_builtin_macros/src/deriving/default.rs b/compiler/rustc_builtin_macros/src/deriving/default.rs index efefcf0006387..6aa45b9d41126 100644 --- a/compiler/rustc_builtin_macros/src/deriving/default.rs +++ b/compiler/rustc_builtin_macros/src/deriving/default.rs @@ -293,7 +293,7 @@ fn validate_default_attribute( return Err(guar); } }; - if !attr.is_word() { + if !attr.get_normal_item().is_word() { let guar = cx.dcx().emit_err(diagnostics::DefaultHasArg { span: attr.span }); return Err(guar); diff --git a/compiler/rustc_expand/src/diagnostics.rs b/compiler/rustc_expand/src/diagnostics.rs index 43da7a03a6454..481b2d5346300 100644 --- a/compiler/rustc_expand/src/diagnostics.rs +++ b/compiler/rustc_expand/src/diagnostics.rs @@ -602,21 +602,3 @@ pub(crate) struct TrailingMacro { pub is_trailing: bool, pub name: Ident, } - -#[derive(Diagnostic)] -#[diag("unused attribute `{$attr_name}`")] -pub(crate) struct UnusedBuiltinAttribute { - #[note( - "the built-in attribute `{$attr_name}` will be ignored, since it's applied to the macro invocation `{$macro_name}`" - )] - pub invoc_span: Span, - pub attr_name: Symbol, - pub macro_name: String, - #[suggestion( - "remove the attribute", - code = "", - applicability = "machine-applicable", - style = "tool-only" - )] - pub attr_span: Span, -} diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index bdcebadcee929..935532fddcc9e 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -23,7 +23,7 @@ use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_errors::PResult; use rustc_feature::Features; use rustc_hir::def::MacroKinds; -use rustc_lint_defs::builtin::{UNUSED_ATTRIBUTES, UNUSED_DOC_COMMENTS}; +use rustc_lint_defs::builtin::UNUSED_DOC_COMMENTS; use rustc_parse::parser::{ AllowConstBlockItems, AttemptLocalParseRecovery, CommaRecoveryMode, ForceCollect, Parser, RecoverColon, RecoverComma, Recovery, token_descr, @@ -2229,7 +2229,6 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { // Run attributes through the attribute parser // since they will not be detected after macro expansion. fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) { - use SyntheticAttr::*; let mut attrs = attrs.iter().peekable(); let mut span: Option = None; while let Some(attr) = attrs.next() { @@ -2265,30 +2264,6 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { ); continue; } - - match &attr.kind { - AttrKind::Normal(normal) - if rustc_attr_parsing::is_builtin_attr(&normal.item) - && !AttributeParser::is_parsed_attribute(&attr.path()) => - { - let attr_name = attr.name().unwrap(); - self.cx.sess.psess.buffer_lint( - UNUSED_ATTRIBUTES, - attr.span, - self.cx.current_expansion.lint_node_id, - crate::diagnostics::UnusedBuiltinAttribute { - attr_name, - macro_name: pprust::path_to_string(&call.path), - invoc_span: call.path.span, - attr_span: attr.span, - }, - ); - } - AttrKind::Normal(_) => {} - AttrKind::Synthetic(CfgTrace(_) | CfgAttrTrace(_) | TestEntrypoint) - | AttrKind::Generated(..) => {} - AttrKind::DocComment(..) => unreachable!(), // handled above - } } } diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 53bf60d038123..11fde009f9a7c 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -1248,7 +1248,7 @@ impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> { continue; } - if !attr.is_word() { + if !attr.get_normal_item().is_word() { self.r.dcx().emit_err(diagnostics::ArgumentsMacroUseNotAllowed { span: attr.span }); } return true; diff --git a/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs b/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs index 01d442133ccf0..7c185702f3194 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs @@ -8,10 +8,10 @@ use rustc_lint::EarlyContext; // Separate each crate's features. pub fn check<'cx>(cx: &EarlyContext<'cx>, attr: &'cx Attribute) { if let AttrStyle::Outer = attr.style - && let Some(path_span) = attr.path_span() && !attr.span.from_expansion() && !is_from_proc_macro(cx, attr) { + let path_span = attr.get_normal_item().path.span; #[expect(clippy::collapsible_span_lint_calls, reason = "rust-clippy#7797")] span_lint_and_then(cx, ALLOW_ATTRIBUTES, path_span, "#[allow] attribute found", |diag| { diag.span_suggestion(path_span, "replace it with", "expect", Applicability::MachineApplicable); diff --git a/src/tools/clippy/clippy_utils/src/attrs.rs b/src/tools/clippy/clippy_utils/src/attrs.rs index fbb3d65238a0a..be9d6761f3625 100644 --- a/src/tools/clippy/clippy_utils/src/attrs.rs +++ b/src/tools/clippy/clippy_utils/src/attrs.rs @@ -2,6 +2,7 @@ use crate::source::SpanExt as _; use crate::{sym, tokenize_with_text}; +use rustc_ast::AttrKind; use rustc_attr_ir::{AttrArgs, find_attr}; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; @@ -14,14 +15,14 @@ use std::str::FromStr as _; /// Validates a single clippy attribute and emits errors for unknown or deprecated ones. pub fn check_clippy_attr(sess: &Session, attr: &rustc_ast::ast::Attribute) { - if let [clippy, segment2] = &*attr.path() - && *clippy == sym::clippy + let AttrKind::Normal(normal) = &attr.kind else { return }; + let attr_item = &normal.item; + if let [clippy, segment2] = &*attr_item.path.segments + && clippy.ident.name == sym::clippy { - let path_span = attr - .path_span() - .expect("Clippy attributes are tool attributes, so they have a span"); + let path_span = attr_item.path.span; - match *segment2 { + match segment2.ident.name { sym::cyclomatic_complexity => { sess.dcx() .struct_span_err(path_span, "usage of deprecated attribute") From 18e604a96d4878346f19a4135ce375062c395195 Mon Sep 17 00:00:00 2001 From: Francisco Gouveia Date: Thu, 12 Nov 2026 14:44:16 +0000 Subject: [PATCH 28/39] Combine the spans of generic arguments without dropping the `Token::RArrow` --- compiler/rustc_ast/src/ast.rs | 2 +- compiler/rustc_ast_lowering/src/lib.rs | 2 +- compiler/rustc_ast_lowering/src/path.rs | 8 ++- .../rustc_ast_passes/src/ast_validation.rs | 4 +- compiler/rustc_parse/src/parser/path.rs | 17 +++--- compiler/rustc_parse/src/parser/ty.rs | 2 +- .../ui/attributes/show_spans_generic_args.rs | 36 ++++++++++++ .../attributes/show_spans_generic_args.stderr | 58 +++++++++++++++++++ .../gat-trait-path-parenthesised-args.stderr | 10 ++-- .../type-parameters-in-field-exprs.stderr | 4 +- .../parenthesized-type-params-in-paths.stderr | 4 +- 11 files changed, 120 insertions(+), 27 deletions(-) create mode 100644 tests/ui/attributes/show_spans_generic_args.rs create mode 100644 tests/ui/attributes/show_spans_generic_args.stderr diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 968566feab637..c660ff59e0b75 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -354,7 +354,7 @@ impl From for Box { pub struct ParenthesizedArgs { /// ```text /// Foo(A, B) -> C - /// ^^^^^^^^^^^^^^ + /// ^^^^^^^^^^^ /// ``` pub span: Span, diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 6b4240b666532..4bc5f61b4ab50 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1280,7 +1280,7 @@ impl<'hir> LoweringContext<'_, 'hir> { args: Default::default(), constraints: &[], parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation, - span: data.span, + span: constraint.ident.span.to(data.span), } } else { let guar = self.emit_bad_parenthesized_trait_in_assoc_ty(data); diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index 49ad9ea4a98a1..61baf6b8d9d04 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -318,6 +318,7 @@ impl<'hir> LoweringContext<'_, 'hir> { GenericArgsMode::ParenSugar | GenericArgsMode::Silence => self .lower_parenthesized_parameter_data( data, + segment.span(), itctx, bound_modifier_allowed_features, hir_id, @@ -347,7 +348,7 @@ impl<'hir> LoweringContext<'_, 'hir> { }; let guar = self .dcx() - .emit_err(GenericTypeWithParentheses { span: data.span, sub }); + .emit_err(GenericTypeWithParentheses { span: segment.span(), sub }); ( self.lower_angle_bracketed_parameter_data( &data.as_angle_bracketed_args(), @@ -509,6 +510,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_parenthesized_parameter_data( &mut self, data: &ParenthesizedArgs, + segment_span: Span, itctx: ImplTraitContext, bound_modifier_allowed_features: Option>, segment_hir_id: HirId, @@ -518,7 +520,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // a hidden lifetime parameter. This is needed for backwards // compatibility, even in contexts like an impl header where // we generally don't permit such things (see #51008). - let ParenthesizedArgs { span, inputs, inputs_span, output } = data; + let ParenthesizedArgs { span: _, inputs, inputs_span, output } = data; // FIXME uses the segments HIR id which is not correct, it should // be the parameters HIR id instead. This is currently not lowered. @@ -550,7 +552,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } FnRetTy::Ty(ty) => self .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitReturn)), - FnRetTy::Default(_) => self.arena.alloc(self.ty_tup(*span, &[])), + FnRetTy::Default(_) => self.arena.alloc(self.ty_tup(segment_span, &[])), }; let args = smallvec![GenericArg::Type( self.arena.alloc(self.ty_tup(*inputs_span, inputs)).try_as_ambig_ty().unwrap() diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index b8dc84f76c3ef..20c09d34bb98c 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -1908,10 +1908,10 @@ impl Visitor<'_> for AstValidator<'_> { } } // The lowered form of parenthesized generic args contains an associated type binding. - Some(ast::GenericArgs::Parenthesized(args)) => { + Some(ast::GenericArgs::Parenthesized(_)) => { self.dcx().emit_err( diagnostics::NegativeBoundWithParentheticalNotation { - span: args.span, + span: segment.span(), }, ); } diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index 5fe796d08cb1e..139e3d31cce8b 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -488,19 +488,18 @@ impl<'a> Parser<'a> { Err(error) => return Err(error), }; let inputs_span = lo.to(self.prev_token.span); + let mut span = inputs_span; + if self.token == token::RArrow { + span = span.to(self.token.span); + } let output = self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?; - let span = ident.span.to(self.prev_token.span); + if let ast::FnRetTy::Ty(ret_ty) = &output { + span = span.to(ret_ty.span); + } ParenthesizedArgs { span, inputs, inputs_span, output }.into() }; - - match &args { - GenericArgs::Parenthesized(data) => { - chain_span(path_span, data.inputs_span); - chain_span(path_span, data.output.span()); - } - _ => chain_span(path_span, args.span()), - } + chain_span(path_span, args.span()); PathSegment { ident, args: Some(args), id: ast::DUMMY_NODE_ID } } else { diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index f09faad96e16a..f3e9dc00cd5ed 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -1671,7 +1671,7 @@ impl<'a> Parser<'a> { } }; let args = ast::ParenthesizedArgs { - span: fn_path_segment.span().to(self.prev_token.span), + span: inputs_lo.to(self.prev_token.span), inputs, inputs_span, output, diff --git a/tests/ui/attributes/show_spans_generic_args.rs b/tests/ui/attributes/show_spans_generic_args.rs new file mode 100644 index 0000000000000..d7475803a0b49 --- /dev/null +++ b/tests/ui/attributes/show_spans_generic_args.rs @@ -0,0 +1,36 @@ +// Illustrates the behavior of the `rustc_show_spans` internal attribute +// on generic arguments. + +//@ check-pass +#![feature(rustc_attrs)] + +#[rustc_show_spans(generic_args)] +fn angle_bracketed() { + let _: Vec; + let _: Vec>; + let _ = Vec::::new(); +} + +macro_rules! parenthesized { + ($f:ident) => { + let _: &dyn $f(u8) -> u8; + }; +} + +#[rustc_show_spans(generic_args)] +fn parenthesized_from_ident() { + parenthesized!(Fn); +} + +macro_rules! arrow { + ($f:tt $args:tt, $o:tt) => { + let _: &dyn $f $args -> $o; + }; +} + +#[rustc_show_spans(path)] +fn arrow_from_macro() { + arrow!(Fn (u8), u8); +} + +fn main() {} diff --git a/tests/ui/attributes/show_spans_generic_args.stderr b/tests/ui/attributes/show_spans_generic_args.stderr new file mode 100644 index 0000000000000..61186bf4b2298 --- /dev/null +++ b/tests/ui/attributes/show_spans_generic_args.stderr @@ -0,0 +1,58 @@ +note: showing the spans of the generic_args + --> $DIR/show_spans_generic_args.rs:9:15 + | +LL | let _: Vec; + | ^^^^ + +note: showing the spans of the generic_args + --> $DIR/show_spans_generic_args.rs:10:15 + | +LL | let _: Vec>; + | ^^^^^^^^^^^^ + +note: showing the spans of the generic_args + --> $DIR/show_spans_generic_args.rs:10:22 + | +LL | let _: Vec>; + | ^^^^ + +note: showing the spans of the generic_args + --> $DIR/show_spans_generic_args.rs:11:18 + | +LL | let _ = Vec::::new(); + | ^^^^ + +note: showing the spans of the generic_args + --> $DIR/show_spans_generic_args.rs:16:23 + | +LL | macro_rules! parenthesized { +LL | ($f:ident) => { +LL | let _: &dyn $f(u8) -> u8; + | ^^^^^^^^^^ +... +LL | parenthesized!(Fn); + | ------------------ in this macro invocation + +note: showing the spans of the path + --> $DIR/show_spans_generic_args.rs:27:21 + | +LL | macro_rules! arrow { +LL | ($f:tt $args:tt, $o:tt) => { +LL | let _: &dyn $f $args -> $o; + | ^^^^^^^^^^^^^^ +... +LL | arrow!(Fn (u8), u8); + | ------------------- in this macro invocation + +note: showing the spans of the path + --> $DIR/show_spans_generic_args.rs:33:16 + | +LL | arrow!(Fn (u8), u8); + | ^^ + +note: showing the spans of the path + --> $DIR/show_spans_generic_args.rs:33:21 + | +LL | arrow!(Fn (u8), u8); + | ^^ + diff --git a/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.stderr b/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.stderr index ee625dc4c79f5..7d15b6e6c3017 100644 --- a/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.stderr +++ b/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.stderr @@ -10,10 +10,10 @@ LL | fn foo<'a>(arg: Box>) {} | +++++++++++++ error: parenthesized generic arguments cannot be used in associated type constraints - --> $DIR/gat-trait-path-parenthesised-args.rs:6:27 + --> $DIR/gat-trait-path-parenthesised-args.rs:6:28 | LL | fn foo<'a>(arg: Box>) {} - | ^^^^^ + | ^^^^ | help: use angle brackets instead | @@ -22,12 +22,10 @@ LL + fn foo<'a>(arg: Box = &'a ()>>) {} | error: parenthesized generic arguments cannot be used in associated type constraints - --> $DIR/gat-trait-path-parenthesised-args.rs:13:27 + --> $DIR/gat-trait-path-parenthesised-args.rs:13:28 | LL | fn bar<'a>(arg: Box>) {} - | ^-- - | | - | help: remove these parentheses + | ^^ help: remove these parentheses error[E0107]: associated type takes 1 lifetime argument but 0 lifetime arguments were supplied --> $DIR/gat-trait-path-parenthesised-args.rs:6:27 diff --git a/tests/ui/parser/type-parameters-in-field-exprs.stderr b/tests/ui/parser/type-parameters-in-field-exprs.stderr index ce7364d3534f6..5a15e7ca29021 100644 --- a/tests/ui/parser/type-parameters-in-field-exprs.stderr +++ b/tests/ui/parser/type-parameters-in-field-exprs.stderr @@ -11,10 +11,10 @@ LL | f.x::<>; | ^^ error: field expressions cannot have generic arguments - --> $DIR/type-parameters-in-field-exprs.rs:15:7 + --> $DIR/type-parameters-in-field-exprs.rs:15:10 | LL | f.x::(); - | ^^^^^ + | ^^ error: aborting due to 3 previous errors diff --git a/tests/ui/typeck/parenthesized-type-params-in-paths.stderr b/tests/ui/typeck/parenthesized-type-params-in-paths.stderr index f22d9c06edead..68ed444755ac4 100644 --- a/tests/ui/typeck/parenthesized-type-params-in-paths.stderr +++ b/tests/ui/typeck/parenthesized-type-params-in-paths.stderr @@ -71,10 +71,10 @@ LL + fn issue_161062() -> A {} | error: parenthesized generic arguments cannot be used in associated type constraints - --> $DIR/parenthesized-type-params-in-paths.rs:52:58 + --> $DIR/parenthesized-type-params-in-paths.rs:52:63 | LL | fn issue_161062_assoc_constraint() -> &'static dyn Trait { - | ^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | help: use angle brackets instead | From b1b547564b176d43855d184a4f34db649434ef53 Mon Sep 17 00:00:00 2001 From: Luca Versari Date: Tue, 27 Oct 2026 13:06:43 +0100 Subject: [PATCH 29/39] Implement `rustc_intrinsic(llvm = "...")` --- compiler/rustc_ast_lowering/src/item.rs | 3 +- compiler/rustc_attr_ir/src/data_structures.rs | 6 +- .../rustc_attr_ir/src/encode_cross_crate.rs | 4 +- .../src/attributes/rustc_internal.rs | 21 ++++- compiler/rustc_attr_parsing/src/context.rs | 2 +- compiler/rustc_borrowck/src/type_check/mod.rs | 9 +- .../src/intrinsics/mod.rs | 36 ++++--- compiler/rustc_codegen_cranelift/src/lib.rs | 4 +- compiler/rustc_codegen_gcc/src/context.rs | 6 +- .../rustc_codegen_gcc/src/intrinsic/mod.rs | 11 ++- .../rustc_codegen_gcc/src/intrinsic/simd.rs | 8 +- compiler/rustc_codegen_gcc/src/lib.rs | 4 +- .../src/back/llvm_backend.rs | 4 +- compiler/rustc_codegen_llvm/src/context.rs | 6 +- compiler/rustc_codegen_llvm/src/intrinsic.rs | 78 ++++++++++++--- compiler/rustc_codegen_ssa/src/diagnostics.rs | 8 +- compiler/rustc_codegen_ssa/src/mir/block.rs | 7 +- .../rustc_codegen_ssa/src/mir/intrinsic.rs | 49 +++++++--- compiler/rustc_codegen_ssa/src/traits/misc.rs | 5 +- .../src/check_consts/check.rs | 2 +- .../rustc_const_eval/src/check_consts/ops.rs | 8 +- .../src/const_eval/machine.rs | 37 +++++--- compiler/rustc_const_eval/src/diagnostics.rs | 6 +- .../src/interpret/intrinsics.rs | 9 +- .../rustc_hir_analysis/src/check/check.rs | 10 +- compiler/rustc_hir_typeck/src/expr.rs | 4 +- compiler/rustc_lint/src/builtin.rs | 2 +- compiler/rustc_lint/src/transmute.rs | 2 +- compiler/rustc_middle/src/ty/intrinsic.rs | 33 ++++++- compiler/rustc_middle/src/ty/layout.rs | 2 +- compiler/rustc_middle/src/ty/mod.rs | 2 +- compiler/rustc_middle/src/ty/util.rs | 12 ++- .../rustc_mir_build/src/builder/expr/into.rs | 11 ++- compiler/rustc_mir_dataflow/src/rustc_peek.rs | 4 +- .../src/cross_crate_inline.rs | 4 +- compiler/rustc_mir_transform/src/inline.rs | 16 +++- .../rustc_mir_transform/src/inline/cycle.rs | 2 +- .../rustc_mir_transform/src/instsimplify.rs | 17 ++-- compiler/rustc_mir_transform/src/lib.rs | 2 +- .../src/lower_intrinsics.rs | 15 +-- compiler/rustc_monomorphize/src/collector.rs | 18 ++-- compiler/rustc_passes/src/check_attr.rs | 2 +- .../rustc_public_bridge/src/context/impls.rs | 12 ++- compiler/rustc_session/src/session.rs | 16 ++-- compiler/rustc_span/src/symbol.rs | 1 + .../clippy_lints/src/loops/empty_loop.rs | 2 +- .../clippy_utils/src/qualify_min_const_fn.rs | 2 +- src/tools/miri/src/intrinsics/mod.rs | 6 +- .../tests/pass/intrinsics/backend-fallback.rs | 18 ++++ .../pass/intrinsics/backend-fallback.stderr | 1 + .../ui/consts/auxiliary/unstable_intrinsic.rs | 11 ++- tests/ui/consts/const-unstable-intrinsic.rs | 36 +++++++ .../ui/consts/const-unstable-intrinsic.stderr | 94 ++++++++++++++++++- tests/ui/intrinsics/rustc-llvm-intrinsic.rs | 54 +++++++++++ 54 files changed, 569 insertions(+), 175 deletions(-) create mode 100644 src/tools/miri/tests/pass/intrinsics/backend-fallback.rs create mode 100644 src/tools/miri/tests/pass/intrinsics/backend-fallback.stderr create mode 100644 tests/ui/intrinsics/rustc-llvm-intrinsic.rs diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index bbbabf75d0805..900fbac6b2356 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1326,7 +1326,8 @@ impl<'hir> LoweringContext<'_, 'hir> { // create a fake body so that the entire rest of the compiler doesn't have to deal with // this as a special case. return self.lower_fn_body(decl, contract, |this| { - if find_attr!(attrs, RustcIntrinsic) || this.tcx.is_sdylib_interface_build() { + if find_attr!(attrs, RustcIntrinsic { .. }) || this.tcx.is_sdylib_interface_build() + { let span = this.lower_span(span); let empty_block = hir::Block { hir_id: this.next_id(), diff --git a/compiler/rustc_attr_ir/src/data_structures.rs b/compiler/rustc_attr_ir/src/data_structures.rs index 6e86fd3f3aa5c..0f7b9c43ee4a9 100644 --- a/compiler/rustc_attr_ir/src/data_structures.rs +++ b/compiler/rustc_attr_ir/src/data_structures.rs @@ -1365,8 +1365,10 @@ pub enum AttributeKind { /// Represents `#[rustc_insignificant_dtor]` RustcInsignificantDtor, - /// Represents `#[rustc_intrinsic]` - RustcIntrinsic, + /// Represents `#[rustc_intrinsic]` / `#[rustc_intrinsic(llvm = "...")]` + RustcIntrinsic { + llvm: Option, + }, /// Represents `#[rustc_intrinsic_const_stable_indirect]` RustcIntrinsicConstStableIndirect, diff --git a/compiler/rustc_attr_ir/src/encode_cross_crate.rs b/compiler/rustc_attr_ir/src/encode_cross_crate.rs index 0f4bb8f167d9f..73c7c5598f36a 100644 --- a/compiler/rustc_attr_ir/src/encode_cross_crate.rs +++ b/compiler/rustc_attr_ir/src/encode_cross_crate.rs @@ -157,7 +157,7 @@ impl AttributeKind { RustcIfThisChanged(..) => No, RustcInheritOverflowChecks => No, RustcInsignificantDtor => Yes, - RustcIntrinsic => Yes, + RustcIntrinsic { .. } => Yes, RustcIntrinsicConstStableIndirect => No, RustcLegacyConstGenerics { .. } => Yes, RustcLintOptDenyFieldAccess { .. } => Yes, @@ -376,7 +376,7 @@ impl AttributeKind { RustcIfThisChanged(..) => false, RustcInheritOverflowChecks => false, RustcInsignificantDtor => false, - RustcIntrinsic => false, + RustcIntrinsic { .. } => false, RustcIntrinsicConstStableIndirect => false, RustcLegacyConstGenerics { .. } => false, RustcLintOptDenyFieldAccess { .. } => false, diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index 0c056240a81d4..cf1209f717d22 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -1113,11 +1113,28 @@ impl SingleAttributeParser for RustcDocPrimitiveParser { pub(crate) struct RustcIntrinsicParser; -impl NoArgsAttributeParser for RustcIntrinsicParser { +impl SingleAttributeParser for RustcIntrinsicParser { const PATH: &[Symbol] = &[sym::rustc_intrinsic]; const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[Allow(Target::Fn)]); + const TEMPLATE: AttributeTemplate = template!(Word, List: &[r#"llvm = "...""#]); const STABILITY: AttributeStability = unstable!(intrinsics); - const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcIntrinsic; + + fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option { + match args { + ArgParser::NoArgs => Some(AttributeKind::RustcIntrinsic { llvm: None }), + ArgParser::List(_) => { + let item = cx.expect_single_element_list(args, cx.attr_span)?; + let nv = cx.expect_name_value(item, item.span(), Some(sym::llvm))?; + let name = cx.expect_string_literal(nv.1)?; + Some(AttributeKind::RustcIntrinsic { llvm: Some(name) }) + } + ArgParser::NameValue(_) => { + let span = cx.attr_span; + cx.adcx().expected_list_or_no_args(span); + None + } + } + } } pub(crate) struct RustcIntrinsicConstStableIndirectParser; diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 547649313ac44..cb70e10b2d92f 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -244,6 +244,7 @@ attribute_parsers!( Single, Single, Single, + Single, Single, Single, Single, @@ -332,7 +333,6 @@ attribute_parsers!( Single>, Single>, Single>, - Single>, Single>, Single>, Single>, diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index d745bb68ff757..97b0c0f12fc10 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -25,8 +25,8 @@ use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::cast::CastTy; use rustc_middle::ty::{ - self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, GenericArgs, Ty, TyCtxt, - TypeVisitableExt, UserArgs, UserTypeAnnotationIndex, fold_regions, + self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, GenericArgs, Intrinsic, Ty, + TyCtxt, TypeVisitableExt, UserArgs, UserTypeAnnotationIndex, fold_regions, }; use rustc_mir_dataflow::move_paths::MoveData; use rustc_mir_dataflow::points::DenseLocationMap; @@ -2032,8 +2032,9 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { // Some of the SIMD intrinsics are special: they need a particular argument to be a // constant. (Eventually this should use const-generics, but those are not up for the // task yet: https://github.com/rust-lang/rust/issues/85229.) - if let Some(name @ (sym::simd_shuffle | sym::simd_insert | sym::simd_extract)) = - self.tcx().intrinsic(def_id).map(|i| i.name) + if let Some(Intrinsic::Rustc( + name @ (sym::simd_shuffle | sym::simd_insert | sym::simd_extract), + )) = self.tcx().intrinsic(def_id).map(|i| i.name) { let idx = match name { sym::simd_shuffle => 2, diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index e5cbca01aa051..d2e5a4e6661e2 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -20,10 +20,9 @@ mod simd; use cranelift_codegen::ir::{ AtomicRmwOp, BlockArg, ExceptionTableData, ExceptionTableItem, ExceptionTag, }; -use rustc_middle::ty; -use rustc_middle::ty::GenericArgs; use rustc_middle::ty::layout::{HasTypingEnv as _, ValidityRequirement}; use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths}; +use rustc_middle::ty::{self, GenericArgs, Intrinsic, IntrinsicDef}; use rustc_span::{Spanned, Symbol, sym}; use rustc_target::spec::PanicStrategy; @@ -284,9 +283,14 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( return Err(Instance::new_raw(instance.def_id(), instance.args)); } - let intrinsic = fx.tcx.item_name(instance.def_id()); + let intrinsic = fx.tcx.intrinsic(instance.def_id()).unwrap(); let instance_args = instance.args; + let Intrinsic::Rustc(intrinsic) = intrinsic.name else { + // Backend intrinsics use their fallback bodies for now. + return intrinsic_fallback(instance, intrinsic, source_info); + }; + if intrinsic.as_str().starts_with("simd_") { self::simd::codegen_simd_intrinsic_call( fx, @@ -591,7 +595,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let ty = generic_args.type_at(0); - let requirement = ValidityRequirement::from_intrinsic(intrinsic); + let requirement = ValidityRequirement::from_rustc_intrinsic(intrinsic); if let Some(requirement) = requirement { let do_panic = !fx @@ -1450,14 +1454,7 @@ fn codegen_regular_intrinsic_call<'tcx>( // by converting the `InstanceKind::Intrinsic` to an `InstanceKind::Item`. _ => { let intrinsic = fx.tcx.intrinsic(instance.def_id()).unwrap(); - if intrinsic.must_be_overridden { - span_bug!( - source_info.span, - "intrinsic {} must be overridden by codegen_cranelift, but isn't", - intrinsic.name, - ); - } - return Err(Instance::new_raw(instance.def_id(), instance.args)); + return intrinsic_fallback(instance, intrinsic, source_info); } } @@ -1465,3 +1462,18 @@ fn codegen_regular_intrinsic_call<'tcx>( fx.bcx.ins().jump(ret_block, &[]); Ok(()) } + +fn intrinsic_fallback<'tcx>( + instance: Instance<'tcx>, + intrinsic: IntrinsicDef, + source_info: mir::SourceInfo, +) -> Result<(), Instance<'tcx>> { + if intrinsic.must_be_overridden { + span_bug!( + source_info.span, + "intrinsic {} must be overridden by codegen_cranelift, but isn't", + intrinsic.name, + ); + } + return Err(Instance::new_raw(instance.def_id(), instance.args)); +} diff --git a/compiler/rustc_codegen_cranelift/src/lib.rs b/compiler/rustc_codegen_cranelift/src/lib.rs index a30dd1c3ebef3..1ff093f9cc556 100644 --- a/compiler/rustc_codegen_cranelift/src/lib.rs +++ b/compiler/rustc_codegen_cranelift/src/lib.rs @@ -155,8 +155,8 @@ impl CodegenBackend for CraneliftCodegenBackend { CodegenBackendInit { global_backend_features: vec![], - replaced_intrinsics: vec![], - fallback_intrinsics: vec![sym::type_id_eq], + replaced_rustc_intrinsics: vec![], + fallback_rustc_intrinsics: vec![sym::type_id_eq], thin_lto_supported: false, } } diff --git a/compiler/rustc_codegen_gcc/src/context.rs b/compiler/rustc_codegen_gcc/src/context.rs index f4461a268c2d5..2811057bab1bd 100644 --- a/compiler/rustc_codegen_gcc/src/context.rs +++ b/compiler/rustc_codegen_gcc/src/context.rs @@ -16,11 +16,11 @@ use rustc_middle::ty::layout::{ FnAbiError, FnAbiOf, FnAbiOfHelpers, FnAbiRequest, HasTyCtxt, HasTypingEnv, LayoutError, LayoutOfHelpers, codegen_handle_fn_abi_err, }; -use rustc_middle::ty::{self, ExistentialTraitRef, Instance, Ty, TyCtxt}; +use rustc_middle::ty::{self, ExistentialTraitRef, Instance, Intrinsic, Ty, TyCtxt}; #[cfg(feature = "master")] use rustc_session::config::DebugInfo; use rustc_session::{PointerAuthSchema, Session}; -use rustc_span::{DUMMY_SP, Span, Symbol}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, TlsModel, X86Abi}; #[cfg(feature = "master")] @@ -560,7 +560,7 @@ impl<'gcc, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { } } - fn intrinsic_call_expects_place_always(&self, _name: Symbol) -> bool { + fn intrinsic_call_expects_place_always(&self, _name: Intrinsic) -> bool { true } } diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index ca98ae6319b7f..350fb01df53c8 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -23,7 +23,7 @@ use rustc_data_structures::fx::FxHashSet; #[cfg(feature = "master")] use rustc_middle::ty::layout::FnAbiOf; use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::ty::{self, Instance, Ty}; +use rustc_middle::ty::{self, Instance, Intrinsic, Ty}; use rustc_session::config::OptLevel; use rustc_span::{Span, Symbol, bug, span_bug, sym}; use rustc_target::callconv::{ArgAbi, PassMode}; @@ -133,7 +133,12 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc let result = PlaceRef { val: result_place.unwrap(), layout: result_layout }; - let name = tcx.item_name(instance.def_id()); + let intrinsic = tcx.intrinsic(instance.def_id()).unwrap(); + let Intrinsic::Rustc(name) = intrinsic.name else { + // Backend intrinsics use their fallback bodies for now. + let fallback = Instance::new_raw(instance.def_id(), instance.args); + return IntrinsicResult::Fallback(fallback); + }; let name_str = name.as_str(); let fn_args = instance.args; @@ -242,7 +247,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc None => { let err = tcx.dcx().emit_err(InvalidMonomorphization::BasicIntegerType { span, - name, + name: Intrinsic::Rustc(name), ty: args[0].layout.ty, }); return IntrinsicResult::Err(err); diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs index 6d3b447e66d1c..971f2f43cd8d2 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs @@ -16,7 +16,7 @@ use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, BuilderMethods}; use rustc_hir as hir; use rustc_middle::mir::BinOp; use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv as _, LayoutOf}; -use rustc_middle::ty::{self, Ty}; +use rustc_middle::ty::{self, Intrinsic, Ty}; use rustc_span::{ErrorGuaranteed, Span, Symbol, span_bug, sym}; use crate::builder::Builder; @@ -864,7 +864,11 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( }}; } let ty::Float(ref f) = *in_elem.kind() else { - return_error!(InvalidMonomorphization::BasicFloatType { span, name, ty: in_ty }); + return_error!(InvalidMonomorphization::BasicFloatType { + span, + name: Intrinsic::Rustc(name), + ty: in_ty + }); }; let elem_ty = bx.cx.type_float_from_ty(*f); let (elem_ty_str, elem_ty, cast_type) = match f.bit_width() { diff --git a/compiler/rustc_codegen_gcc/src/lib.rs b/compiler/rustc_codegen_gcc/src/lib.rs index fa15ec2838b24..896059c6897fb 100644 --- a/compiler/rustc_codegen_gcc/src/lib.rs +++ b/compiler/rustc_codegen_gcc/src/lib.rs @@ -290,8 +290,8 @@ impl CodegenBackend for GccCodegenBackend { CodegenBackendInit { global_backend_features, - replaced_intrinsics: vec![], - fallback_intrinsics: vec![sym::type_id_eq], + replaced_rustc_intrinsics: vec![], + fallback_rustc_intrinsics: vec![sym::type_id_eq], thin_lto_supported: false, } } diff --git a/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs b/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs index c0349b6003319..ee04b6770618f 100644 --- a/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs +++ b/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs @@ -288,8 +288,8 @@ impl CodegenBackend for LlvmCodegenBackend { CodegenBackendInit { global_backend_features, - replaced_intrinsics, - fallback_intrinsics, + replaced_rustc_intrinsics: replaced_intrinsics, + fallback_rustc_intrinsics: fallback_intrinsics, thin_lto_supported: true, } } diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 999613db146a3..7151dcd32418d 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -18,7 +18,7 @@ use rustc_middle::ty::layout::{ FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers, codegen_handle_fn_abi_err, }; -use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; +use rustc_middle::ty::{self, Instance, Intrinsic, Ty, TyCtxt}; use rustc_sanitizers::ignorelist::{SanitizerIgnoreList, typename_for_ignore_list}; use rustc_session::config::{ BranchProtection, CFGuard, CFProtection, DebugInfo, FunctionReturn, PAuthKey, PacRet, @@ -1100,8 +1100,8 @@ impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { } } - fn intrinsic_call_expects_place_always(&self, name: Symbol) -> bool { - matches!(name, sym::black_box) + fn intrinsic_call_expects_place_always(&self, name: Intrinsic) -> bool { + matches!(name, Intrinsic::Rustc(sym::black_box)) } } diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 0b442b3bdedeb..2f00202146f15 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -22,7 +22,7 @@ use rustc_middle::mir::interpret::{AllocId, Allocation, ErrorHandled, GlobalAllo use rustc_middle::mir::{self, BinOp}; use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf}; use rustc_middle::ty::offload_meta::OffloadMetadata; -use rustc_middle::ty::{self, GenericArgs, Instance, SimdAlign, Ty, TyCtxt}; +use rustc_middle::ty::{self, GenericArgs, Instance, Intrinsic, SimdAlign, Ty, TyCtxt}; use rustc_session::diagnostics::feature_err; use rustc_span::{ErrorGuaranteed, Span, Symbol, bug, span_bug, sym}; use rustc_structures::CrateType; @@ -84,19 +84,18 @@ impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { } } -impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { - fn codegen_intrinsic_call( +impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { + fn codegen_rustc_intrinsic_call( &mut self, instance: ty::Instance<'tcx>, args: &[OperandRef<'tcx, Value<'ll>>], result_layout: ty::layout::TyAndLayout<'tcx>, result_place: Option>>, span: Span, + name: Symbol, ) -> IntrinsicResult<'tcx, Value<'ll>> { let tcx = self.tcx; let llvm_version = crate::llvm_util::get_version(); - - let name = tcx.item_name(instance.def_id()); let fn_args = instance.args; let llval = match name { @@ -381,7 +380,7 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { if !ty.is_integral() { let err = tcx.dcx().emit_err(InvalidMonomorphization::BasicIntegerType { span, - name, + name: Intrinsic::Rustc(name), ty, }); return IntrinsicResult::Err(err); @@ -853,6 +852,15 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { } }; + self.llvm_value_to_intrinsicresult(llval, result_layout, result_place) + } + + fn llvm_value_to_intrinsicresult( + &mut self, + llval: Value<'ll>, + result_layout: ty::layout::TyAndLayout<'tcx>, + result_place: Option>>, + ) -> IntrinsicResult<'tcx, Value<'ll>> { if let BackendRepr::Memory { .. } = result_layout.backend_repr { // We have an llvm immediate, but that's not what cg_ssa expects, // so write it into the place (that always exists for memory) @@ -867,12 +875,12 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { } } - fn codegen_llvm_intrinsic_call( + fn codegen_llvm_intrinsic_call_impl( &mut self, instance: ty::Instance<'tcx>, - args: &[OperandRef<'tcx, Self::Value>], - _is_cleanup: bool, - ) -> Self::Value { + intrinsic_name: &str, + args: &[OperandRef<'tcx, Value<'ll>>], + ) -> Value<'ll> { let tcx = self.tcx(); let fn_ty = instance.ty(tcx, self.typing_env()); @@ -903,12 +911,10 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { let fn_ptr = if let Some(&llfn) = self.intrinsic_instances.borrow().get(&instance) { llfn } else { - let sym = tcx.symbol_name(instance).name; - - let llfn = if let Some(llfn) = self.get_declared_value(sym) { + let llfn = if let Some(llfn) = self.get_declared_value(intrinsic_name) { llfn } else { - intrinsic_fn(self, sym, llreturn_ty, llargument_tys, instance) + intrinsic_fn(self, intrinsic_name, llreturn_ty, llargument_tys, instance) }; self.intrinsic_instances.borrow_mut().insert(instance, llfn); @@ -953,6 +959,44 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { autocast(self, llret, src_ty, dest_ty) } +} + +impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { + fn codegen_intrinsic_call( + &mut self, + instance: ty::Instance<'tcx>, + args: &[OperandRef<'tcx, Value<'ll>>], + result_layout: ty::layout::TyAndLayout<'tcx>, + result_place: Option>>, + span: Span, + ) -> IntrinsicResult<'tcx, Value<'ll>> { + let tcx = self.tcx; + let name = tcx.intrinsic(instance.def_id()).unwrap().name; + + match name { + Intrinsic::Rustc(name) => self.codegen_rustc_intrinsic_call( + instance, + args, + result_layout, + result_place, + span, + name, + ), + Intrinsic::Backend { llvm } => { + let value = self.codegen_llvm_intrinsic_call_impl(instance, llvm.as_str(), args); + self.llvm_value_to_intrinsicresult(value, result_layout, result_place) + } + } + } + + fn codegen_llvm_intrinsic_call( + &mut self, + instance: ty::Instance<'tcx>, + args: &[OperandRef<'tcx, Self::Value>], + _is_cleanup: bool, + ) -> Self::Value { + self.codegen_llvm_intrinsic_call_impl(instance, self.tcx().symbol_name(instance).name, args) + } fn abort_immediate(&mut self) { self.call_intrinsic("llvm.trap", &[], &[]); @@ -2410,7 +2454,11 @@ fn generic_simd_intrinsic<'ll, 'tcx>( } let ty::Float(f) = in_elem.kind() else { - return_error!(InvalidMonomorphization::BasicFloatType { span, name, ty: in_ty }); + return_error!(InvalidMonomorphization::BasicFloatType { + span, + name: Intrinsic::Rustc(name), + ty: in_ty + }); }; let elem_ty = bx.cx.type_float_from_ty(*f); diff --git a/compiler/rustc_codegen_ssa/src/diagnostics.rs b/compiler/rustc_codegen_ssa/src/diagnostics.rs index 09faa71468bf7..160eb82c11f85 100644 --- a/compiler/rustc_codegen_ssa/src/diagnostics.rs +++ b/compiler/rustc_codegen_ssa/src/diagnostics.rs @@ -12,8 +12,8 @@ use rustc_errors::{ Diag, DiagArgValue, DiagCtxtHandle, DiagSymbolList, Diagnostic, IntoDiagArg, Level, msg, }; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_middle::ty::Ty; use rustc_middle::ty::layout::LayoutError; +use rustc_middle::ty::{Intrinsic, Ty}; use rustc_span::{Span, Symbol}; use crate::assert_module_sources::CguReuse; @@ -724,7 +724,7 @@ pub enum InvalidMonomorphization<'tcx> { BasicIntegerType { #[primary_span] span: Span, - name: Symbol, + name: Intrinsic, ty: Ty<'tcx>, }, @@ -732,7 +732,7 @@ pub enum InvalidMonomorphization<'tcx> { BasicIntegerOrPtrType { #[primary_span] span: Span, - name: Symbol, + name: Intrinsic, ty: Ty<'tcx>, }, @@ -740,7 +740,7 @@ pub enum InvalidMonomorphization<'tcx> { BasicFloatType { #[primary_span] span: Span, - name: Symbol, + name: Intrinsic, ty: Ty<'tcx>, }, diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index 4c07eeea757cd..678d8c00c68dc 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -14,7 +14,7 @@ use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, Scalar}; use rustc_middle::mir::{self, AssertKind, InlineAsmMacro, SwitchTargets, UnwindTerminateReason}; use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout, ValidityRequirement}; use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths}; -use rustc_middle::ty::{self, Instance, Ty, TypeVisitableExt}; +use rustc_middle::ty::{self, Instance, Intrinsic, Ty, TypeVisitableExt}; use rustc_session::config::OptLevel; use rustc_span::{Span, Spanned, bug, span_bug}; use rustc_target::callconv::{ @@ -902,7 +902,10 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // Emit a panic or a no-op for `assert_*` intrinsics. // These are intrinsics that compile to panics so that we can get a message // which mentions the offending type, even from a const context. - let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else { + let Intrinsic::Rustc(name) = intrinsic.name else { + return None; + }; + let Some(requirement) = ValidityRequirement::from_rustc_intrinsic(name) else { return None; }; diff --git a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs index 3504823450e75..1bfd977c2fce3 100644 --- a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs @@ -1,6 +1,6 @@ use rustc_abi::{Align, FieldIdx, WrappingRange}; use rustc_middle::mir::SourceInfo; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Intrinsic, Ty, TyCtxt}; use rustc_session::config::OptLevel; use rustc_span::{ErrorGuaranteed, bug, span_bug, sym}; use rustc_target::spec::Arch; @@ -75,9 +75,27 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let span = source_info.span; - let name = bx.tcx().item_name(instance.def_id()); + let name = bx.tcx().intrinsic(instance.def_id()).unwrap().name; let fn_args = instance.args; + let check_value = |op: OperandValue<::Value>| { + debug_assert!( + op.is_expected_variant_for_type(result_layout), + "[{name:?}] Value {op:?} is wrong for type {result_layout:?}", + ); + }; + + let Intrinsic::Rustc(name) = name else { + // Backend intrinsics go directly to the backend. + let result = + bx.codegen_intrinsic_call(instance, args, result_layout, result_place, span); + + if let IntrinsicResult::Operand(op) = result { + check_value(op); + } + return result; + }; + // If we're swapping something that's *not* an `OperandValue::Ref`, // then we can do it directly and avoid the alloca. // Otherwise, we'll let the fallback MIR body take care of it. @@ -103,12 +121,16 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } let invalid_monomorphization_int_type = |ty| -> ErrorGuaranteed { - bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerType { span, name, ty }) + bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerType { + span, + name: Intrinsic::Rustc(name), + ty, + }) }; let invalid_monomorphization_int_or_ptr_type = |ty| -> ErrorGuaranteed { bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerOrPtrType { span, - name, + name: Intrinsic::Rustc(name), ty, }) }; @@ -284,10 +306,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bx.exactudiv(args[0].immediate(), args[1].immediate()) }), None => { - let err = bx - .tcx() - .dcx() - .emit_err(InvalidMonomorphization::BasicIntegerType { span, name, ty }); + let err = + bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerType { + span, + name: Intrinsic::Rustc(name), + ty, + }); return IntrinsicResult::Err(err); } } @@ -306,7 +330,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let err = bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicFloatType { span, - name, + name: Intrinsic::Rustc(name), ty: args[0].layout.ty, }); return IntrinsicResult::Err(err); @@ -339,7 +363,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { None => { let err = bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicFloatType { span, - name, + name: Intrinsic::Rustc(name), ty: args[0].layout.ty, }); return IntrinsicResult::Err(err); @@ -606,10 +630,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } }; - debug_assert!( - op_val.is_expected_variant_for_type(result_layout), - "[{name:?}] Value {op_val:?} is wrong for type {result_layout:?}", - ); + check_value(op_val); IntrinsicResult::Operand(op_val) } diff --git a/compiler/rustc_codegen_ssa/src/traits/misc.rs b/compiler/rustc_codegen_ssa/src/traits/misc.rs index 08da31fd1efa2..2be250e78b80a 100644 --- a/compiler/rustc_codegen_ssa/src/traits/misc.rs +++ b/compiler/rustc_codegen_ssa/src/traits/misc.rs @@ -1,9 +1,8 @@ use std::cell::RefCell; use rustc_data_structures::fx::FxHashMap; -use rustc_middle::ty::{self, Instance, Ty}; +use rustc_middle::ty::{self, Instance, Intrinsic, Ty}; use rustc_session::{PointerAuthSchema, Session}; -use rustc_span::Symbol; use super::BackendTypes; @@ -38,5 +37,5 @@ pub trait MiscCodegenMethods<'tcx>: BackendTypes { /// when emitting code for the intrinsic `name`. /// /// This is discouraged, but here for now to simplify migration to using OperandValues - fn intrinsic_call_expects_place_always(&self, name: Symbol) -> bool; + fn intrinsic_call_expects_place_always(&self, name: Intrinsic) -> bool; } diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 11f1b2a7a8210..092a6823db07c 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -831,7 +831,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { return; } - // Intrinsics are language primitives, not regular calls, so treat them separately. + // Non-backend intrinsics are language primitives, not regular calls, so treat them separately. if let Some(intrinsic) = tcx.intrinsic(callee) { if !tcx.is_const_fn(callee) { // Non-const intrinsic. diff --git a/compiler/rustc_const_eval/src/check_consts/ops.rs b/compiler/rustc_const_eval/src/check_consts/ops.rs index 3a1c083fa835f..b4c0b6030e371 100644 --- a/compiler/rustc_const_eval/src/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/check_consts/ops.rs @@ -11,8 +11,8 @@ use rustc_infer::traits::{ImplSource, Obligation, ObligationCause}; use rustc_middle::mir::CallSource; use rustc_middle::ty::print::{PrintTraitRefExt as _, with_no_trimmed_paths}; use rustc_middle::ty::{ - self, AssocContainer, Closure, FnDef, FnPtr, GenericArgKind, GenericArgs, Param, TraitRef, Ty, - suggest_constraining_type_param, + self, AssocContainer, Closure, FnDef, FnPtr, GenericArgKind, GenericArgs, Intrinsic, Param, + TraitRef, Ty, suggest_constraining_type_param, }; use rustc_session::diagnostics::add_feature_diagnostics; use rustc_span::{BytePos, Pos, Span, Symbol, span_bug, sym}; @@ -491,7 +491,7 @@ impl<'tcx> NonConstOp<'tcx> for CallUnstable { /// A call to an intrinsic that is just not const-callable at all. #[derive(Debug)] pub(crate) struct IntrinsicNonConst { - pub name: Symbol, + pub name: Intrinsic, } impl<'tcx> NonConstOp<'tcx> for IntrinsicNonConst { @@ -507,7 +507,7 @@ impl<'tcx> NonConstOp<'tcx> for IntrinsicNonConst { /// A call to an intrinsic that is just not const-callable at all. #[derive(Debug)] pub(crate) struct IntrinsicUnstable { - pub name: Symbol, + pub name: Intrinsic, pub feature: Symbol, pub const_stable_indirect: bool, } diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 2ad6ee2a88a43..3e6329cfe0a12 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -14,7 +14,7 @@ use rustc_middle::mir::AssertMessage; use rustc_middle::mir::interpret::ReportedErrorInfo; use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, TyAndLayout, ValidityRequirement}; -use rustc_middle::ty::{self, FieldInfo, ScalarInt, Ty, TyCtxt}; +use rustc_middle::ty::{self, FieldInfo, Intrinsic, ScalarInt, Ty, TyCtxt}; use rustc_middle::{mir, throw_machine_stop}; use rustc_span::{Span, Symbol, bug, span_bug, sym}; use rustc_target::callconv::FnAbi; @@ -486,7 +486,26 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { if ecx.eval_intrinsic(instance, args, dest, target)? { return interp_ok(None); } - let intrinsic_name = ecx.tcx.item_name(instance.def_id()); + let intrinsic_name = ecx.tcx.intrinsic(instance.def_id()).unwrap().name; + + let do_fallback = || { + // We haven't handled the intrinsic, let's see if we can use a fallback body. + if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden { + throw_unsup_format!( + "intrinsic `{intrinsic_name}` is not supported at compile-time" + ); + } + return interp_ok(Some(ty::Instance { + def: ty::InstanceKind::Item(instance.def_id()), + args: instance.args, + })); + }; + + // Backend intrinsics are not supported in const eval except with their fallback + // bodies. + let Intrinsic::Rustc(intrinsic_name) = intrinsic_name else { + return do_fallback(); + }; // CTFE-specific intrinsics. match intrinsic_name { @@ -566,7 +585,8 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { | sym::assert_zero_valid | sym::assert_mem_uninitialized_valid => { let ty = instance.args.type_at(0); - let requirement = ValidityRequirement::from_intrinsic(intrinsic_name).unwrap(); + let requirement = + ValidityRequirement::from_rustc_intrinsic(intrinsic_name).unwrap(); let should_panic = !ecx .tcx @@ -962,16 +982,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { } _ => { - // We haven't handled the intrinsic, let's see if we can use a fallback body. - if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden { - throw_unsup_format!( - "intrinsic `{intrinsic_name}` is not supported at compile-time" - ); - } - return interp_ok(Some(ty::Instance { - def: ty::InstanceKind::Item(instance.def_id()), - args: instance.args, - })); + return do_fallback(); } } diff --git a/compiler/rustc_const_eval/src/diagnostics.rs b/compiler/rustc_const_eval/src/diagnostics.rs index f7c5d6c36cecb..13a7096d11e64 100644 --- a/compiler/rustc_const_eval/src/diagnostics.rs +++ b/compiler/rustc_const_eval/src/diagnostics.rs @@ -5,7 +5,7 @@ use rustc_errors::formatting::DiagMessageAddArg; use rustc_errors::{Diag, DiagArgValue, MultiSpan, Subdiagnostic, msg}; use rustc_hir::ConstContext; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_middle::ty::{Mutability, Ty}; +use rustc_middle::ty::{Intrinsic, Mutability, Ty}; use rustc_span::{Span, Symbol}; use crate::interpret::InternKind; @@ -167,7 +167,7 @@ pub(crate) struct UnstableConstTrait { pub(crate) struct UnstableIntrinsic { #[primary_span] pub span: Span, - pub name: Symbol, + pub name: Intrinsic, pub feature: Symbol, #[suggestion( "add `#![feature({$feature})]` to the crate attributes to enable", @@ -243,7 +243,7 @@ pub(crate) struct NonConstFnCall { pub(crate) struct NonConstIntrinsic { #[primary_span] pub span: Span, - pub name: Symbol, + pub name: Intrinsic, pub kind: ConstContext, } diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index d9278c1d97a5e..2c7da64def4ce 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -13,7 +13,7 @@ use rustc_ast::{IntTy, UintTy}; use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, read_target_uint, write_target_uint}; use rustc_middle::mir::{self, BinOp, ConstValue, NonDivergingIntrinsic}; use rustc_middle::ty::layout::TyAndLayout; -use rustc_middle::ty::{self, FloatTy, ScalarInt, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{self, FloatTy, Intrinsic, ScalarInt, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::{Symbol, bug, kw, span_bug, sym}; use tracing::trace; @@ -176,7 +176,12 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ret: Option, ) -> InterpResult<'tcx, bool> { let instance_args = instance.args; - let intrinsic_name = self.tcx.item_name(instance.def_id()); + let intrinsic_name = self.tcx.intrinsic(instance.def_id()).unwrap().name; + + // We only support rustc intrinsics for now. + let Intrinsic::Rustc(intrinsic_name) = intrinsic_name else { + return interp_ok(false); + }; if intrinsic_name.as_str().starts_with("atomic_") { return self.eval_atomic_intrinsic(intrinsic_name, instance_args, args, dest, ret); diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 495e8e5590eed..3c9a6b5697eeb 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -24,8 +24,8 @@ use rustc_middle::ty::error::TypeErrorToStringExt; use rustc_middle::ty::layout::LayoutError; use rustc_middle::ty::util::Discr; use rustc_middle::ty::{ - AdtDef, BottomUpFolder, GenericArgKind, RegionKind, TypeFoldable, TypeSuperVisitable, - TypeVisitable, TypeVisitableExt, Unnormalized, fold_regions, + AdtDef, BottomUpFolder, GenericArgKind, Intrinsic, RegionKind, TypeFoldable, + TypeSuperVisitable, TypeVisitable, TypeVisitableExt, Unnormalized, fold_regions, }; use rustc_span::sym; use rustc_target::spec::{AbiMap, AbiMapping}; @@ -835,12 +835,14 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), tcx.ensure_ok().clauses_of(def_id); tcx.ensure_ok().fn_sig(def_id); tcx.ensure_ok().codegen_fn_attrs(def_id); - if let Some(i) = tcx.intrinsic(def_id) { + if let Some(i) = tcx.intrinsic(def_id) + && let Intrinsic::Rustc(name) = i.name + { intrinsic::check_intrinsic_type( tcx, def_id, tcx.def_ident_span(def_id).unwrap(), - i.name, + name, ) } } diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 7f187180c3a06..3c8b4f125ff78 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -648,7 +648,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let ty::FnDef(did, args) = *ty.kind() { let fn_sig = ty.fn_sig(tcx); - if tcx.is_intrinsic(did, sym::transmute) { + if tcx.is_rustc_intrinsic(did, sym::transmute) { let Some(from) = fn_sig.inputs().skip_binder().get(0) else { span_bug!( tcx.def_span(did), @@ -663,7 +663,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.deferred_transmute_checks.borrow_mut().push((*from, to, expr.hir_id)); } if !tcx.sess.opts.unstable_opts.offload.is_empty() - && tcx.is_intrinsic(did, sym::offload) + && tcx.is_rustc_intrinsic(did, sym::offload) { let args = args.skip_binder(); let f = args.type_at(0); diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index a376252ad1038..124afc1ebb646 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -991,7 +991,7 @@ impl<'tcx> LateLintPass<'tcx> for MutableTransmutes { } fn def_id_is_transmute(cx: &LateContext<'_>, def_id: DefId) -> bool { - cx.tcx.is_intrinsic(def_id, sym::transmute) + cx.tcx.is_rustc_intrinsic(def_id, sym::transmute) } } } diff --git a/compiler/rustc_lint/src/transmute.rs b/compiler/rustc_lint/src/transmute.rs index 3b269a215cb6b..de2b299d9be81 100644 --- a/compiler/rustc_lint/src/transmute.rs +++ b/compiler/rustc_lint/src/transmute.rs @@ -122,7 +122,7 @@ impl<'tcx> LateLintPass<'tcx> for CheckTransmutes { let Res::Def(DefKind::Fn, def_id) = cx.qpath_res(&qpath, callee.hir_id) else { return; }; - if !cx.tcx.is_intrinsic(def_id, sym::transmute) { + if !cx.tcx.is_rustc_intrinsic(def_id, sym::transmute) { return; }; let body_owner_def_id = cx.tcx.hir_enclosing_body_owner(expr.hir_id); diff --git a/compiler/rustc_middle/src/ty/intrinsic.rs b/compiler/rustc_middle/src/ty/intrinsic.rs index 63c2eae384da1..37e2cda1cf67e 100644 --- a/compiler/rustc_middle/src/ty/intrinsic.rs +++ b/compiler/rustc_middle/src/ty/intrinsic.rs @@ -1,12 +1,39 @@ +use std::fmt::Display; + +use rustc_errors::IntoDiagArg; use rustc_macros::{Decodable, Encodable, StableHash}; use rustc_span::Symbol; use rustc_span::def_id::DefId; use super::TyCtxt; +/// The name of an intrinsic. +#[derive(Copy, Clone, Debug, Decodable, Encodable, StableHash, PartialEq, Eq)] +pub enum Intrinsic { + /// A Rust intrinsic (common to all backends). + Rustc(Symbol), + /// A backend-specific intrinsic. For now, we only support llvm-specific intrinsics. + Backend { llvm: Symbol }, +} + +impl Display for Intrinsic { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Intrinsic::Rustc(i) => write!(f, "{i}"), + Intrinsic::Backend { llvm } => write!(f, "{llvm}"), + } + } +} + +impl IntoDiagArg for Intrinsic { + fn into_diag_arg(self, path: &mut Option) -> rustc_errors::DiagArgValue { + self.to_string().into_diag_arg(path) + } +} + #[derive(Copy, Clone, Debug, Decodable, Encodable, StableHash)] pub struct IntrinsicDef { - pub name: Symbol, + pub name: Intrinsic, /// Whether the intrinsic has no meaningful body and all backends need to shim all calls to it. pub must_be_overridden: bool, /// Whether the intrinsic can be invoked from stable const fn (`#[rustc_intrinsic_const_stable_indirect]`). @@ -14,8 +41,8 @@ pub struct IntrinsicDef { } impl TyCtxt<'_> { - pub fn is_intrinsic(self, def_id: DefId, name: Symbol) -> bool { + pub fn is_rustc_intrinsic(self, def_id: DefId, name: Symbol) -> bool { let Some(i) = self.intrinsic(def_id) else { return false }; - i.name == name + matches!(i.name, Intrinsic::Rustc(n) if n == name) } } diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 1f1a769665c26..33d8b1a6e6ab0 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -223,7 +223,7 @@ pub enum ValidityRequirement { } impl ValidityRequirement { - pub fn from_intrinsic(intrinsic: Symbol) -> Option { + pub fn from_rustc_intrinsic(intrinsic: Symbol) -> Option { match intrinsic { sym::assert_inhabited => Some(Self::Inhabited), sym::assert_zero_valid => Some(Self::Zero), diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 8de81ccd1e2fb..5a5213be8bda1 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -24,7 +24,7 @@ pub use adt::*; pub use assoc::*; pub use generic_args::{GenericArgKind, TermKind, *}; pub use generics::*; -pub use intrinsic::IntrinsicDef; +pub use intrinsic::{Intrinsic, IntrinsicDef}; use rustc_abi::{ Align, FieldIdx, Integer, IntegerType, ReprFlags, ReprOptions, ScalableElt, Size, VariantIdx, }; diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index a588114cda6ce..9a99598e3b078 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -26,6 +26,7 @@ use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; use crate::mir; use crate::query::Providers; use crate::traits::ObligationCause; +use crate::ty::intrinsic::Intrinsic; use crate::ty::layout::{FloatExt, IntegerExt}; use crate::ty::{ self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgs, Ty, TyCtxt, TypeFoldable, @@ -1733,15 +1734,22 @@ pub fn doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> Option<&'_ NotableTr /// the compiler to make some assumptions about its shape; if the user doesn't use a feature gate, they may /// cause an ICE that we otherwise may want to prevent. pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { - if tcx.features().intrinsics() && find_attr!(tcx, def_id, RustcIntrinsic) { + if tcx.features().intrinsics() + // find any rustc_intrinsic attribute, possibly with a "llvm = ..." argument + && let Some(maybe_llvm) = find_attr!(tcx, def_id, RustcIntrinsic{llvm} => *llvm) + { let must_be_overridden = match tcx.hir_node_by_def_id(def_id) { hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { has_body, .. }, .. }) => { !has_body } _ => true, }; + let name = match maybe_llvm { + Some(s) => Intrinsic::Backend { llvm: s }, + None => Intrinsic::Rustc(tcx.item_name(def_id)), + }; Some(ty::IntrinsicDef { - name: tcx.item_name(def_id), + name, must_be_overridden, const_stable_indirect: find_attr!(tcx, def_id, RustcIntrinsicConstStableIndirect), }) diff --git a/compiler/rustc_mir_build/src/builder/expr/into.rs b/compiler/rustc_mir_build/src/builder/expr/into.rs index 86f781f35f60d..1f641940d10eb 100644 --- a/compiler/rustc_mir_build/src/builder/expr/into.rs +++ b/compiler/rustc_mir_build/src/builder/expr/into.rs @@ -8,7 +8,7 @@ use rustc_data_structures::thin_vec::ThinVec; use rustc_hir as hir; use rustc_middle::mir::*; use rustc_middle::thir::*; -use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty}; +use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Intrinsic, Ty}; use rustc_span::{DUMMY_SP, Spanned, span_bug, sym}; use rustc_trait_selection::infer::InferCtxtExt; use tracing::{debug, instrument}; @@ -407,7 +407,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ExprKind::Call { ty, fun, ref args, .. } if let ty::FnDef(def_id, generic_args) = *ty.kind() && let Some(intrinsic) = this.tcx.intrinsic(def_id) - && matches!(intrinsic.name, sym::write_via_move | sym::write_box_via_move) => + && matches!( + intrinsic.name, + Intrinsic::Rustc(sym::write_via_move | sym::write_box_via_move) + ) => { let generic_args = generic_args.no_bound_vars().unwrap(); // We still have to evaluate the callee expression as normal (but we don't care @@ -415,7 +418,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let _fun = unpack!(block = this.as_local_operand(block, fun)); match intrinsic.name { - sym::write_via_move => { + Intrinsic::Rustc(sym::write_via_move) => { // `write_via_move(ptr, val)` becomes `*ptr = val` but without any dropping. // The destination must have unit type. @@ -434,7 +437,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { this.cfg.push_assign_unit(block, source_info, destination, this.tcx); block.unit() } - sym::write_box_via_move => { + Intrinsic::Rustc(sym::write_box_via_move) => { // The signature is: // `fn write_box_via_move(b: Box>, val: T) -> Box>`. // `write_box_via_move(b, val)` becomes diff --git a/compiler/rustc_mir_dataflow/src/rustc_peek.rs b/compiler/rustc_mir_dataflow/src/rustc_peek.rs index 0e14d1f830492..975b48fc01af7 100644 --- a/compiler/rustc_mir_dataflow/src/rustc_peek.rs +++ b/compiler/rustc_mir_dataflow/src/rustc_peek.rs @@ -1,6 +1,6 @@ use rustc_attr_ir::{RustcMirKind, find_attr}; use rustc_middle::mir::{self, Body, Local, Location}; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Intrinsic, Ty, TyCtxt}; use rustc_span::{Span, sym}; use tracing::{debug, info}; @@ -164,7 +164,7 @@ impl PeekCall { { let fn_args = fn_args.no_bound_vars().unwrap(); - if tcx.intrinsic(def_id)?.name != sym::rustc_peek { + if tcx.intrinsic(def_id)?.name != Intrinsic::Rustc(sym::rustc_peek) { return None; } diff --git a/compiler/rustc_mir_transform/src/cross_crate_inline.rs b/compiler/rustc_mir_transform/src/cross_crate_inline.rs index 53d58439b0434..a57007d9738a8 100644 --- a/compiler/rustc_mir_transform/src/cross_crate_inline.rs +++ b/compiler/rustc_mir_transform/src/cross_crate_inline.rs @@ -35,7 +35,7 @@ fn cross_crate_inlinable(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { return true; } - if find_attr!(tcx, def_id, RustcIntrinsic) { + if find_attr!(tcx, def_id, RustcIntrinsic { .. }) { // Intrinsic fallback bodies are always cross-crate inlineable. // To ensure that the MIR inliner doesn't cluelessly try to inline fallback // bodies even when the backend would implement something better, we stop @@ -163,7 +163,7 @@ impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> { // cross-crate-inlining. Adding a broad exception for all intrinsics benchmarks well // and seems more sustainable than an ever-growing list of intrinsics to ignore. if let Some((fn_def_id, _)) = func.const_fn_def() - && find_attr!(tcx, fn_def_id, RustcIntrinsic) + && find_attr!(tcx, fn_def_id, RustcIntrinsic { .. }) { return; } diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index c932d8c22c6e2..aaf2a3c1fec0a 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -14,7 +14,8 @@ use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; use rustc_middle::ty::{ - self, Instance, InstanceKind, ShimKind, Ty, TyCtxt, TypeFlags, TypeVisitableExt, Unnormalized, + self, Instance, InstanceKind, Intrinsic, ShimKind, Ty, TyCtxt, TypeFlags, TypeVisitableExt, + Unnormalized, }; use rustc_session::config::{DebugInfo, OptLevel}; use rustc_span::{Spanned, bug}; @@ -561,8 +562,17 @@ fn resolve_callsite<'tcx, I: Inliner<'tcx>>( if intrinsic.must_be_overridden { return None; // intrinsic without fallback body } - if !tcx.sess.fallback_intrinsics.contains(&intrinsic.name) { - return None; // intrinsic that the backend may want to overwrite + match intrinsic.name { + // intrinsics that the backend may want to overwrite + Intrinsic::Rustc(name) + if !tcx.sess.fallback_rustc_intrinsics.contains(&name) => + { + return None; + } + Intrinsic::Backend { .. } => { + return None; + } + _ => {} } // The callee is the fallback body. debug!("callsite is fallback body: {def_id:?}"); diff --git a/compiler/rustc_mir_transform/src/inline/cycle.rs b/compiler/rustc_mir_transform/src/inline/cycle.rs index 77ddecabc291f..ecabb3bef0f1e 100644 --- a/compiler/rustc_mir_transform/src/inline/cycle.rs +++ b/compiler/rustc_mir_transform/src/inline/cycle.rs @@ -212,7 +212,7 @@ pub(crate) fn mir_inliner_callees<'tcx>( let ty::FnDef(def_id, generic_args) = ty.kind() else { continue; }; - let call = if tcx.is_intrinsic(*def_id, sym::const_eval_select) { + let call = if tcx.is_rustc_intrinsic(*def_id, sym::const_eval_select) { let func = &call_args[2].node; let ty = func.ty(&body.local_decls, tcx); let ty::FnDef(def_id, generic_args) = ty.kind() else { diff --git a/compiler/rustc_mir_transform/src/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index 11ce25f2f5d7d..6c9c969dbc534 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -7,8 +7,8 @@ use rustc_index::IndexVec; use rustc_middle::mir::visit::MutVisitor; use rustc_middle::mir::*; use rustc_middle::ty::layout::{IntegerExt, ValidityRequirement}; -use rustc_middle::ty::{self, GenericArgs, Ty, TyCtxt, layout}; -use rustc_span::{Symbol, bug, sym}; +use rustc_middle::ty::{self, GenericArgs, Intrinsic, Ty, TyCtxt, layout}; +use rustc_span::{bug, sym}; use crate::PassPolicy; use crate::simplify::simplify_duplicate_switch_targets; @@ -281,9 +281,9 @@ impl<'tcx> InstSimplifyContext<'_, 'tcx> { && args.len() == 1 && let Some((fn_def_id, generics)) = func.const_fn_def() { - let lang_item = if self.tcx.is_intrinsic(fn_def_id, sym::size_of_val) { + let lang_item = if self.tcx.is_rustc_intrinsic(fn_def_id, sym::size_of_val) { LangItem::SizeOf - } else if self.tcx.is_intrinsic(fn_def_id, sym::align_of_val) { + } else if self.tcx.is_rustc_intrinsic(fn_def_id, sym::align_of_val) { LangItem::AlignOf } else { return; @@ -333,7 +333,7 @@ impl<'tcx> InstSimplifyContext<'_, 'tcx> { } = &terminator.kind && args.len() == 2 && let Some((fn_def_id, generics)) = func.const_fn_def() - && tcx.is_intrinsic(fn_def_id, sym::raw_eq) + && tcx.is_rustc_intrinsic(fn_def_id, sym::raw_eq) && let generic_ty = generics.type_at(0) && let Ok(layout) = tcx.layout_of(self.typing_env.as_query_input(generic_ty)) && let Ok(integer) = Integer::from_size(layout.size) @@ -452,9 +452,10 @@ fn intrinsic_assert_panics<'tcx>( tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, arg: ty::GenericArg<'tcx>, - intrinsic_name: Symbol, + intrinsic_name: Intrinsic, ) -> Option { - let requirement = ValidityRequirement::from_intrinsic(intrinsic_name)?; + let Intrinsic::Rustc(intrinsic_name) = intrinsic_name else { return None }; + let requirement = ValidityRequirement::from_rustc_intrinsic(intrinsic_name)?; let ty = arg.expect_ty(); Some(!tcx.check_validity_requirement((requirement, typing_env.as_query_input(ty))).ok()?) } @@ -462,7 +463,7 @@ fn intrinsic_assert_panics<'tcx>( fn resolve_rust_intrinsic<'tcx>( tcx: TyCtxt<'tcx>, func_ty: Ty<'tcx>, -) -> Option<(Symbol, GenericArgs<'tcx>)> { +) -> Option<(Intrinsic, GenericArgs<'tcx>)> { let ty::FnDef(def_id, args) = *func_ty.kind() else { return None }; let intrinsic = tcx.intrinsic(def_id)?; Some((intrinsic.name, args.no_bound_vars().unwrap())) diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index b3d762c18cd26..e8788854a8d82 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -258,7 +258,7 @@ fn remap_mir_for_const_eval_select<'tcx>( fn_span, .. } if let ty::FnDef(def_id, _) = *const_.ty().kind() - && tcx.is_intrinsic(def_id, sym::const_eval_select) => + && tcx.is_rustc_intrinsic(def_id, sym::const_eval_select) => { let Ok([tupled_args, called_in_const, called_at_rt]) = take_array(args) else { unreachable!() diff --git a/compiler/rustc_mir_transform/src/lower_intrinsics.rs b/compiler/rustc_mir_transform/src/lower_intrinsics.rs index 369ef0a6849bc..b7312e1f76b13 100644 --- a/compiler/rustc_mir_transform/src/lower_intrinsics.rs +++ b/compiler/rustc_mir_transform/src/lower_intrinsics.rs @@ -1,7 +1,7 @@ //! Lowers intrinsic calls use rustc_middle::mir::*; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::ty::{self, Intrinsic, TyCtxt}; use rustc_span::{bug, span_bug, sym}; use crate::{PassPolicy, take_array}; @@ -17,14 +17,15 @@ impl<'tcx> crate::MirPass<'tcx> for LowerIntrinsics { &mut terminator.kind && let ty::FnDef(def_id, generic_args) = *func.ty(local_decls, tcx).kind() && let Some(intrinsic) = tcx.intrinsic(def_id) + && let Intrinsic::Rustc(name) = intrinsic.name { let generic_args = generic_args.no_bound_vars().unwrap(); - match intrinsic.name { + match name { sym::unreachable => { terminator.kind = TerminatorKind::Unreachable; } sym::ub_checks | sym::overflow_checks | sym::contract_checks => { - let op = match intrinsic.name { + let op = match name { sym::ub_checks => RuntimeChecks::UbChecks, sym::contract_checks => RuntimeChecks::ContractChecks, sym::overflow_checks => RuntimeChecks::OverflowChecks, @@ -126,9 +127,9 @@ impl<'tcx> crate::MirPass<'tcx> for LowerIntrinsics { | sym::unchecked_shr => { let target = target.unwrap(); let Ok([lhs, rhs]) = take_array(args) else { - bug!("Wrong arguments for {} intrinsic", intrinsic.name); + bug!("Wrong arguments for {} intrinsic", name); }; - let bin_op = match intrinsic.name { + let bin_op = match name { sym::wrapping_add => BinOp::Add, sym::wrapping_sub => BinOp::Sub, sym::wrapping_mul => BinOp::Mul, @@ -154,9 +155,9 @@ impl<'tcx> crate::MirPass<'tcx> for LowerIntrinsics { sym::add_with_overflow | sym::sub_with_overflow | sym::mul_with_overflow => { let target = target.unwrap(); let Ok([lhs, rhs]) = take_array(args) else { - bug!("Wrong arguments for {} intrinsic", intrinsic.name); + bug!("Wrong arguments for {} intrinsic", name); }; - let bin_op = match intrinsic.name { + let bin_op = match name { sym::add_with_overflow => BinOp::AddWithOverflow, sym::sub_with_overflow => BinOp::SubWithOverflow, sym::mul_with_overflow => BinOp::MulWithOverflow, diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 9833b6fafdaf8..8acb3c2d9ff8e 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -225,8 +225,8 @@ use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::adjustment::{CustomCoerceUnsized, PointerCoercion}; use rustc_middle::ty::layout::ValidityRequirement; use rustc_middle::ty::{ - self, GenericArgs, GenericParamDefKind, Instance, InstanceKind, ShimKind, Ty, TyCtxt, - TypeFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor, Unnormalized, VtblEntry, + self, GenericArgs, GenericParamDefKind, Instance, InstanceKind, Intrinsic, ShimKind, Ty, + TyCtxt, TypeFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor, Unnormalized, VtblEntry, }; use rustc_middle::util::Providers; use rustc_session::config::{DebugInfo, EntryFnType, Offload}; @@ -869,7 +869,7 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> { ); if let ty::FnDef(def_id, _) = *callee_ty.kind() - && self.tcx.is_intrinsic(def_id, rustc_span::sym::offload) + && self.tcx.is_rustc_intrinsic(def_id, rustc_span::sym::offload) && let Some(kernel) = args.first() { let kernel_ty = kernel.node.ty(self.body, self.tcx); @@ -1004,7 +1004,14 @@ fn visit_instance_use<'tcx>( return; } if let Some(intrinsic) = tcx.intrinsic(instance.def_id()) { - if let Some(_requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) { + let intrinsic_is_replaced = if let Intrinsic::Rustc(name) = intrinsic.name { + tcx.sess.replaced_rustc_intrinsics.contains(&name) + } else { + false + }; + if let Intrinsic::Rustc(name) = intrinsic.name + && let Some(_requirement) = ValidityRequirement::from_rustc_intrinsic(name) + { // The intrinsics assert_inhabited, assert_zero_valid, and assert_mem_uninitialized_valid will // be lowered in codegen to nothing or a call to panic_nounwind. So if we encounter any // of those intrinsics, we need to include a mono item for panic_nounwind, else we may try to @@ -1015,8 +1022,7 @@ fn visit_instance_use<'tcx>( output.push(create_fn_mono_item(tcx, panic_instance, source)); } } else if !intrinsic.must_be_overridden - && (tcx.sess.opts.unstable_opts.force_intrinsic_fallback - || !tcx.sess.replaced_intrinsics.contains(&intrinsic.name)) + && (tcx.sess.opts.unstable_opts.force_intrinsic_fallback || !intrinsic_is_replaced) { // Codegen the fallback body of intrinsics with fallback bodies. // We have to skip this otherwise as there's no body to codegen. diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 6ba7c81333f40..1c177071d37c0 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -346,7 +346,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { AttributeKind::RustcIfThisChanged(..) => (), AttributeKind::RustcInheritOverflowChecks => (), AttributeKind::RustcInsignificantDtor => (), - AttributeKind::RustcIntrinsic => (), + AttributeKind::RustcIntrinsic { .. } => (), AttributeKind::RustcIntrinsicConstStableIndirect => (), AttributeKind::RustcLegacyConstGenerics { .. } => (), AttributeKind::RustcLintOptDenyFieldAccess { .. } => (), diff --git a/compiler/rustc_public_bridge/src/context/impls.rs b/compiler/rustc_public_bridge/src/context/impls.rs index 945331d14b073..8c9c6ec3001c2 100644 --- a/compiler/rustc_public_bridge/src/context/impls.rs +++ b/compiler/rustc_public_bridge/src/context/impls.rs @@ -18,9 +18,9 @@ use rustc_middle::ty::print::{ use rustc_middle::ty::util::Discr; use rustc_middle::ty::{ AdtDef, AdtKind, AssocItem, Binder, ClosureKind, CoroutineArgsExt, EarlyBinder, - ExistentialTraitRef, FnSig, GenericArgs, Instance, InstanceKind, IntrinsicDef, List, PolyFnSig, - ScalarInt, TraitDef, TraitRef, Ty, TyCtxt, TyKind, TypeVisitableExt, UintTy, ValTree, - VariantDef, VtblEntry, + ExistentialTraitRef, FnSig, GenericArgs, Instance, InstanceKind, Intrinsic, IntrinsicDef, List, + PolyFnSig, ScalarInt, TraitDef, TraitRef, Ty, TyCtxt, TyKind, TypeVisitableExt, UintTy, + ValTree, VariantDef, VtblEntry, }; use rustc_middle::{mir, ty}; use rustc_span::def_id::{CrateNum, DefId, LOCAL_CRATE}; @@ -400,7 +400,11 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { /// Retrieve the plain function name of an intrinsic. pub fn intrinsic_name(&self, def_id: DefId) -> String { - self.tcx.intrinsic(def_id).unwrap().name.to_string() + match self.tcx.intrinsic(def_id).unwrap().name { + Intrinsic::Rustc(s) => s, + Intrinsic::Backend { llvm } => llvm, + } + .to_string() } /// Retrieve the closure signature for the given generic arguments. diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index f829877d95857..2b23284c55f57 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -440,10 +440,10 @@ pub struct CodegenBackendInit { pub global_backend_features: Vec, /// See `Session::replaced_intrinsics`. - pub replaced_intrinsics: Vec, + pub replaced_rustc_intrinsics: Vec, /// See `Session::fallback_intrinsics`. - pub fallback_intrinsics: Vec, + pub fallback_rustc_intrinsics: Vec, /// See `Session::thin_lto_supported`. pub thin_lto_supported: bool = true, @@ -534,11 +534,11 @@ pub struct Session { /// A list of all intrinsics that the current codegen backend definitely replaces with its own /// implementations, which means their fallback bodies do not need to be monomorphized. - pub replaced_intrinsics: FxHashSet, + pub replaced_rustc_intrinsics: FxHashSet, /// A list of all intrinsics that the current codegen backend definitely does *not* replace /// with its own implementations, which means their fallback bodies can be MIR-inlined. - pub fallback_intrinsics: FxHashSet, + pub fallback_rustc_intrinsics: FxHashSet, /// Does the codegen backend support ThinLTO? pub thin_lto_supported: bool, @@ -1497,8 +1497,8 @@ pub fn build_session( let CodegenBackendInit { global_backend_features, - replaced_intrinsics, - fallback_intrinsics, + replaced_rustc_intrinsics: replaced_intrinsics, + fallback_rustc_intrinsics: fallback_intrinsics, thin_lto_supported, } = codegen_backend_init; @@ -1529,8 +1529,8 @@ pub fn build_session( target_filesearch, host_filesearch, wasm_proc_macro_filesearch, - replaced_intrinsics: FxHashSet::from_iter(replaced_intrinsics), - fallback_intrinsics: FxHashSet::from_iter(fallback_intrinsics), + replaced_rustc_intrinsics: FxHashSet::from_iter(replaced_intrinsics), + fallback_rustc_intrinsics: FxHashSet::from_iter(fallback_intrinsics), thin_lto_supported, mir_opt_bisect_eval_count: AtomicUsize::new(0), removed_rustc_main_attr: AtomicBool::new(false), diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 869c4a281f7f5..ab0310473a310 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1263,6 +1263,7 @@ symbols! { lint_reasons, literal, little, big, + llvm, load, loaded_from_disk, local, diff --git a/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs b/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs index 803b3ed7cba13..86b5a515c12c2 100644 --- a/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs @@ -11,7 +11,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, loop_block: &Block<'_ if let Node::Item(parent_node) = cx.tcx.hir_node(parent_hir_id) && matches!(parent_node.kind, ItemKind::Fn { .. }) && let attrs = cx.tcx.hir_attrs(parent_hir_id) - && find_attr!(attrs, RustcIntrinsic) + && find_attr!(attrs, RustcIntrinsic { .. }) { // Intrinsic functions are expanded into an empty loop when lowering the AST // to simplify the job of later passes which might expect any function to have a body. diff --git a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index 50b7cd9bb5c8c..bd14554ef8b82 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs @@ -405,7 +405,7 @@ fn check_terminator<'tcx>( // within const fns. `transmute` is allowed in all other const contexts. // This won't really scale to more intrinsics or functions. Let's allow const // transmutes in const fn before we add more hacks to this. - if cx.tcx.is_intrinsic(fn_def_id, sym::transmute) { + if cx.tcx.is_rustc_intrinsic(fn_def_id, sym::transmute) { return Err(( span, "can only call `transmute` from const items, not `const fn`".into(), diff --git a/src/tools/miri/src/intrinsics/mod.rs b/src/tools/miri/src/intrinsics/mod.rs index 5b5104731ac0b..d6e0e24e8ab15 100644 --- a/src/tools/miri/src/intrinsics/mod.rs +++ b/src/tools/miri/src/intrinsics/mod.rs @@ -50,13 +50,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { if ecx.eval_intrinsic(instance, args, dest, ret)? { return interp_ok(None); } - let intrinsic_name = ecx.tcx.item_name(instance.def_id()); - let intrinsic_name = intrinsic_name.as_str(); + let intrinsic = ecx.tcx.intrinsic(instance.def_id()).unwrap(); + let intrinsic_name = &intrinsic.name.to_string(); let res = ecx.emulate_intrinsic_by_name(intrinsic_name, instance.args, args, dest, ret)?; res.jump_to_next_block(ecx, dest, ret, Some(unwind), |ecx| { // We haven't handled the intrinsic, let's see if we can use a fallback body. - if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden { + if intrinsic.must_be_overridden { throw_unsup_format!("unimplemented intrinsic: `{intrinsic_name}`") } let intrinsic_fallback_is_spec = ecx diff --git a/src/tools/miri/tests/pass/intrinsics/backend-fallback.rs b/src/tools/miri/tests/pass/intrinsics/backend-fallback.rs new file mode 100644 index 0000000000000..b3519833018c4 --- /dev/null +++ b/src/tools/miri/tests/pass/intrinsics/backend-fallback.rs @@ -0,0 +1,18 @@ +#![feature(intrinsics)] + +// Having a fallback body that does not match the +// intrinsic is not a good idea, but we do that here for testing. +// +// It's especially a bad idea to mark such a function as +// #[miri::intrinsic_fallback_is_spec]. +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +#[miri::intrinsic_fallback_is_spec] +fn not_quite_fshl(a: i64, b: i64, sh: i64) -> i64 { + eprintln!("{a} {b} {sh}"); + 0 +} + +fn main() { + let res = not_quite_fshl(1, 2, 3); + assert_eq!(res, 0); +} diff --git a/src/tools/miri/tests/pass/intrinsics/backend-fallback.stderr b/src/tools/miri/tests/pass/intrinsics/backend-fallback.stderr new file mode 100644 index 0000000000000..b85905ec0b994 --- /dev/null +++ b/src/tools/miri/tests/pass/intrinsics/backend-fallback.stderr @@ -0,0 +1 @@ +1 2 3 diff --git a/tests/ui/consts/auxiliary/unstable_intrinsic.rs b/tests/ui/consts/auxiliary/unstable_intrinsic.rs index c1c7571e0c90c..a270d6873d805 100644 --- a/tests/ui/consts/auxiliary/unstable_intrinsic.rs +++ b/tests/ui/consts/auxiliary/unstable_intrinsic.rs @@ -1,11 +1,20 @@ #![feature(staged_api, rustc_attrs, intrinsics)] -#![stable(since="1.0.0", feature = "stable")] +#![stable(since = "1.0.0", feature = "stable")] #[unstable(feature = "unstable", issue = "42")] #[rustc_intrinsic] pub const unsafe fn size_of_val(x: *const T) -> usize; +#[unstable(feature = "unstable", issue = "42")] +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +pub const unsafe fn llvm_fshl(a: i64, b: i64, sh: i64) -> i64; + #[unstable(feature = "unstable", issue = "42")] #[rustc_const_unstable(feature = "unstable", issue = "42")] #[rustc_intrinsic] pub const unsafe fn align_of_val(x: *const T) -> usize; + +#[unstable(feature = "unstable", issue = "42")] +#[rustc_const_unstable(feature = "unstable", issue = "42")] +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +pub const unsafe fn llvm_fshl2(a: i64, b: i64, sh: i64) -> i64; diff --git a/tests/ui/consts/const-unstable-intrinsic.rs b/tests/ui/consts/const-unstable-intrinsic.rs index edb6d365da441..1fcc0b2479c9a 100644 --- a/tests/ui/consts/const-unstable-intrinsic.rs +++ b/tests/ui/consts/const-unstable-intrinsic.rs @@ -26,17 +26,39 @@ const fn const_main() { align_of_val(&x); //~^ERROR: cannot use `#[feature(local)]` } + unsafe { + unstable_intrinsic::llvm_fshl(0, 0, 0); + //~^ERROR: unstable library feature `unstable` + //~|ERROR: not yet stable as a const intrinsic + unstable_intrinsic::llvm_fshl2(0, 0, 0); + //~^ERROR: unstable library feature `unstable` + //~|ERROR: not yet stable as a const intrinsic + + llvm_fshl(0, 0, 0); + //~^ERROR: cannot use `#[feature(local)]` + llvm_fshl2(0, 0, 0); + //~^ERROR: cannot use `#[feature(local)]` + } } #[unstable(feature = "local", issue = "42")] #[rustc_intrinsic] pub const unsafe fn size_of_val(x: *const T) -> usize; +#[unstable(feature = "local", issue = "42")] +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +pub const unsafe fn llvm_fshl(a: i64, b: i64, sh: i64) -> i64; + #[unstable(feature = "local", issue = "42")] #[rustc_const_unstable(feature = "local", issue = "42")] #[rustc_intrinsic] pub const unsafe fn align_of_val(x: *const T) -> usize; +#[unstable(feature = "local", issue = "42")] +#[rustc_const_unstable(feature = "local", issue = "42")] +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +pub const unsafe fn llvm_fshl2(a: i64, b: i64, sh: i64) -> i64; + #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")] pub const unsafe fn copy(src: *const T, dst: *mut T, count: usize) { @@ -56,6 +78,12 @@ mod fallback { //~^ ERROR cannot use `#[feature(local)]` } + #[rustc_intrinsic(llvm = "llvm.fshl.i64")] + const unsafe fn llvm_fshl(a: i64, b: i64, sh: i64) -> i64 { + super::llvm_fshl(a, b, sh) + //~^ ERROR cannot use `#[feature(local)]` + } + // Even unstable intrinsics must be const-checked if we add // `rustc_intrinsic_const_stable_indirect`. #[rustc_intrinsic] @@ -65,6 +93,14 @@ mod fallback { super::align_of_val(x) //~^ ERROR cannot use `#[feature(local)]` } + + #[rustc_intrinsic(llvm = "llvm.fshl.i64")] + #[rustc_const_unstable(feature = "core_intrinsics", issue = "none")] + #[rustc_intrinsic_const_stable_indirect] + pub const unsafe fn llvm_fshl2(a: i64, b: i64, sh: i64) -> i64 { + super::llvm_fshl2(a, b, sh) + //~^ ERROR cannot use `#[feature(local)]` + } } // `rustc_const_stable_indirect` does not actually make this intrinsic callable diff --git a/tests/ui/consts/const-unstable-intrinsic.stderr b/tests/ui/consts/const-unstable-intrinsic.stderr index 4ef39d61cf801..5fbe3d89e9c13 100644 --- a/tests/ui/consts/const-unstable-intrinsic.stderr +++ b/tests/ui/consts/const-unstable-intrinsic.stderr @@ -18,6 +18,26 @@ LL | unstable_intrinsic::align_of_val(&x); = help: add `#![feature(unstable)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date +error[E0658]: use of unstable library feature `unstable` + --> $DIR/const-unstable-intrinsic.rs:30:9 + | +LL | unstable_intrinsic::llvm_fshl(0, 0, 0); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #42 for more information + = help: add `#![feature(unstable)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: use of unstable library feature `unstable` + --> $DIR/const-unstable-intrinsic.rs:33:9 + | +LL | unstable_intrinsic::llvm_fshl2(0, 0, 0); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #42 for more information + = help: add `#![feature(unstable)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + error: `size_of_val` is not yet stable as a const intrinsic --> $DIR/const-unstable-intrinsic.rs:17:9 | @@ -64,8 +84,54 @@ LL + #[rustc_const_unstable(feature = "...", issue = "...")] LL | const fn const_main() { | +error: `llvm.fshl.i64` is not yet stable as a const intrinsic + --> $DIR/const-unstable-intrinsic.rs:30:9 + | +LL | unstable_intrinsic::llvm_fshl(0, 0, 0); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: add `#![feature(unstable)]` to the crate attributes to enable + | +LL + #![feature(unstable)] + | + +error: `llvm.fshl.i64` is not yet stable as a const intrinsic + --> $DIR/const-unstable-intrinsic.rs:33:9 + | +LL | unstable_intrinsic::llvm_fshl2(0, 0, 0); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: add `#![feature(unstable)]` to the crate attributes to enable + | +LL + #![feature(unstable)] + | + +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` + --> $DIR/const-unstable-intrinsic.rs:37:9 + | +LL | llvm_fshl(0, 0, 0); + | ^^^^^^^^^^^^^^^^^^ + | +help: if the function is not (yet) meant to be exposed to stable const contexts, add `#[rustc_const_unstable]` + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn const_main() { + | + +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` + --> $DIR/const-unstable-intrinsic.rs:39:9 + | +LL | llvm_fshl2(0, 0, 0); + | ^^^^^^^^^^^^^^^^^^^ + | +help: if the function is not (yet) meant to be exposed to stable const contexts, add `#[rustc_const_unstable]` + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn const_main() { + | + error: intrinsic `copy::copy` cannot be (indirectly) exposed to stable - --> $DIR/const-unstable-intrinsic.rs:47:14 + --> $DIR/const-unstable-intrinsic.rs:69:14 | LL | unsafe { copy(src, dst, count) } | ^^^^^^^^^^^^^^^^^^^^^ @@ -73,7 +139,7 @@ LL | unsafe { copy(src, dst, count) } = help: mark the caller as `#[rustc_const_unstable]`, or mark the intrinsic `#[rustc_intrinsic_const_stable_indirect]` (but this requires team approval) error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` - --> $DIR/const-unstable-intrinsic.rs:55:9 + --> $DIR/const-unstable-intrinsic.rs:77:9 | LL | super::size_of_val(src); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -85,19 +151,37 @@ LL | const unsafe fn copy(src: *const T, _dst: *mut T, _count: usize) { | error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` - --> $DIR/const-unstable-intrinsic.rs:65:9 + --> $DIR/const-unstable-intrinsic.rs:83:9 + | +LL | super::llvm_fshl(a, b, sh) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: if the function is not (yet) meant to be exposed to stable const contexts, add `#[rustc_const_unstable]` + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const unsafe fn llvm_fshl(a: i64, b: i64, sh: i64) -> i64 { + | + +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` + --> $DIR/const-unstable-intrinsic.rs:93:9 | LL | super::align_of_val(x) | ^^^^^^^^^^^^^^^^^^^^^^ +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` + --> $DIR/const-unstable-intrinsic.rs:101:9 + | +LL | super::llvm_fshl2(a, b, sh) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + error: intrinsic `non_const_fallback::size_of_val` cannot be (indirectly) exposed to stable - --> $DIR/const-unstable-intrinsic.rs:84:18 + --> $DIR/const-unstable-intrinsic.rs:120:18 | LL | unsafe { size_of_val(x) } | ^^^^^^^^^^^^^^ | = help: mark the caller as `#[rustc_const_unstable]`, or mark the intrinsic `#[rustc_intrinsic_const_stable_indirect]` (but this requires team approval) -error: aborting due to 10 previous errors +error: aborting due to 18 previous errors For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/intrinsics/rustc-llvm-intrinsic.rs b/tests/ui/intrinsics/rustc-llvm-intrinsic.rs new file mode 100644 index 0000000000000..261416019f3e0 --- /dev/null +++ b/tests/ui/intrinsics/rustc-llvm-intrinsic.rs @@ -0,0 +1,54 @@ +//@ run-pass +//@ revisions: backend_with_support backend_without_support force_fallback +//@ [backend_with_support]needs-backends: llvm +//@ [backend_without_support]ignore-backends: llvm +//@ [force_fallback]compile-flags: -Zforce-intrinsic-fallback + +#![feature(intrinsics)] + +// Having a fallback body that does not match the +// intrinsic is not a good idea, but we do that here for testing. +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +const fn sometimes_fshl(a: i64, b: i64, sh: i64) -> i64 { + a + b + sh +} + +#[cfg(backend_with_support)] +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +fn fshl_no_fallback(a: i64, b: i64, sh: i64) -> i64; + +// Test a built-in intrinsic name to make sure no +// implementation gets confused. +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +const fn size_of_val(a: i64, b: i64, sh: i64) -> i64 { + (((((a as i128) << 64) | (b as i128)) << sh) >> 64) as i64 +} + +#[cfg(backend_with_support)] +const IS_INTRINSIC: bool = true; + +#[cfg(any(backend_without_support, force_fallback))] +const IS_INTRINSIC: bool = false; + +fn main() { + let res = sometimes_fshl(1, 2, 3); + if IS_INTRINSIC { + assert_eq!(res, 8); + } else { + assert_eq!(res, 6); + } + + // Const eval should always use the fallback body, regardless + // of -Zforce-intrinsic-fallback. + let const_res = const { sometimes_fshl(1, 2, 3) }; + assert_eq!(const_res, 6); + + #[cfg(backend_with_support)] + { + let res = fshl_no_fallback(1, 2, 3); + assert_eq!(res, 8); + } + + assert_eq!(const { size_of_val(1, 2, 3) }, 8); + assert_eq!(size_of_val(1, 2, 3), 8); +} From ef0369b760c7d26870a6dd0735f87320d2b8e62a Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Tue, 17 Nov 2026 10:31:25 +0100 Subject: [PATCH 30/39] Move doc attribute and doc comment target checking to attribute parsing --- .../rustc_attr_parsing/src/attributes/doc.rs | 46 +----- .../src/attributes/doc_comment.rs | 97 ++++++++++++ .../rustc_attr_parsing/src/attributes/mod.rs | 1 + .../src/attributes/prelude.rs | 4 +- .../rustc_attr_parsing/src/diagnostics.rs | 27 +++- compiler/rustc_attr_parsing/src/interface.rs | 18 +++ .../rustc_attr_parsing/src/target_checking.rs | 69 +-------- compiler/rustc_expand/src/diagnostics.rs | 10 -- compiler/rustc_expand/src/expand.rs | 50 ++----- compiler/rustc_lint/src/builtin.rs | 103 +------------ compiler/rustc_lint/src/diagnostics.rs | 18 --- compiler/rustc_lint/src/lib.rs | 1 - compiler/rustc_lint_defs/src/builtin.rs | 5 +- .../check-doc-alias-attr-location.rs | 6 +- .../check-doc-alias-attr-location.stderr | 31 ++-- .../lints/unused-doc-comments.stderr | 16 +- tests/ui/attributes/attr-on-mac-call.rs | 23 +++ tests/ui/attributes/attr-on-mac-call.stderr | 76 +++++----- .../unused-doc-comments-edge-cases.stderr | 32 ++-- .../unused/unused-doc-comments-for-macros.rs | 4 +- .../unused-doc-comments-for-macros.stderr | 41 ++---- tests/ui/lint/unused/useless-comment.rs | 13 +- tests/ui/lint/unused/useless-comment.stderr | 138 ++++++++---------- .../check-doc-alias-attr-location.stderr | 8 +- 24 files changed, 352 insertions(+), 485 deletions(-) create mode 100644 compiler/rustc_attr_parsing/src/attributes/doc_comment.rs diff --git a/compiler/rustc_attr_parsing/src/attributes/doc.rs b/compiler/rustc_attr_parsing/src/attributes/doc.rs index aebde3867ebd2..c8090ffcd1e9f 100644 --- a/compiler/rustc_attr_parsing/src/attributes/doc.rs +++ b/compiler/rustc_attr_parsing/src/attributes/doc.rs @@ -10,12 +10,13 @@ use rustc_feature::AttributeStability; use rustc_lint_defs::builtin::{INVALID_DOC_ATTRIBUTES, UNUSED_ATTRIBUTES}; use rustc_span::{Span, Symbol, edition, kw, sym}; -use super::prelude::{ALL_TARGETS, AllowedTargets}; +use super::prelude::AllowedTargets; use super::{AcceptMapping, AttributeParser, template}; +use crate::attributes::doc_comment::DOC_TARGETS; use crate::context::{AcceptContext, FinalizeContext}; use crate::diagnostics::{ DocAliasBadChar, DocAliasDuplicated, DocAliasEmpty, DocAliasMalformed, DocAliasStartEnd, - DocAttrNotCrateLevel, DocAttrNotParameters, DocAttrNotTraitLevel, DocAttributeNotAttribute, + DocAttrNotCrateLevel, DocAttrNotTraitLevel, DocAttributeNotAttribute, DocAutoCfgExpectsHideOrShow, DocAutoCfgHideShowExpectsList, DocAutoCfgHideShowNoIdentBeforeValues, DocAutoCfgHideShowUnexpectedItem, DocAutoCfgHideShowUnexpectedItemAfterValues, DocAutoCfgHideShowValuesMix, @@ -864,9 +865,6 @@ impl DocParser { } fn accept_single_doc_attr(&mut self, cx: &mut AcceptContext<'_, '_>, args: &ArgParser) { - if cx.shared.target == Target::Param { - cx.emit_err(DocAttrNotParameters { span: cx.attr_span }); - } match args { ArgParser::List(items) if !items.is_empty() => { for i in items.mixed() { @@ -934,43 +932,7 @@ impl AttributeParser for DocParser { this.accept_single_doc_attr(cx, args); }, )]; - // FIXME: Currently emitted from 2 different places, generating duplicated warnings. - const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(ALL_TARGETS); - // const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowListWarnRest(&[ - // Allow(Target::ExternCrate), - // Allow(Target::Use), - // Allow(Target::Static), - // Allow(Target::Const), - // Allow(Target::Fn), - // Allow(Target::Mod), - // Allow(Target::ForeignMod), - // Allow(Target::TyAlias), - // Allow(Target::Enum), - // Allow(Target::Variant), - // Allow(Target::Struct), - // Allow(Target::Field), - // Allow(Target::Union), - // Allow(Target::Trait), - // Allow(Target::TraitAlias), - // Allow(Target::Impl { of_trait: true }), - // Allow(Target::Impl { of_trait: false }), - // Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: false })), - // Allow(Target::AssocConst(AssocCtxt::Trait)), - // Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: true })), - // Allow(Target::Method(MethodKind::Inherent)), - // Allow(Target::Method(MethodKind::Trait { body: true })), - // Allow(Target::Method(MethodKind::Trait { body: false })), - // Allow(Target::Method(MethodKind::TraitImpl)), - // Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: false })), - // Allow(Target::AssocTy(AssocCtxt::Trait)), - // Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: true })), - // Allow(Target::ForeignFn), - // Allow(Target::ForeignStatic), - // Allow(Target::ForeignTy), - // Allow(Target::MacroDef), - // Allow(Target::Crate), - // Error(Target::WherePredicate), - // ]); + const ALLOWED_TARGETS: AllowedTargets<'_> = DOC_TARGETS; fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option { if self.nb_doc_attrs != 0 { diff --git a/compiler/rustc_attr_parsing/src/attributes/doc_comment.rs b/compiler/rustc_attr_parsing/src/attributes/doc_comment.rs new file mode 100644 index 0000000000000..932be836f0661 --- /dev/null +++ b/compiler/rustc_attr_parsing/src/attributes/doc_comment.rs @@ -0,0 +1,97 @@ +use std::mem; + +use rustc_ast::AttrKind; +use rustc_ast::token::CommentKind; +use rustc_ast::visit::AssocCtxt; +use rustc_attr_ir::target::{AstTarget, MethodKind, Target}; +use rustc_errors::{Diagnostic, MultiSpan}; +use rustc_lint_defs::LintId; +use rustc_lint_defs::builtin::UNUSED_DOC_COMMENTS; +use rustc_span::Span; + +use crate::attributes::prelude::{Allow, Error}; +use crate::diagnostics::{BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub}; +use crate::target_checking::Policy::AllowSilent; +use crate::target_checking::{AllowedResult, AllowedTargets}; +use crate::{AttributeParser, EmitAttribute, ShouldEmit}; + +pub(crate) fn target_check_doc_comment( + parser: &AttributeParser<'_>, + attr: &rustc_ast::Attribute, + target: &AstTarget<'_>, + target_span: Span, + emit_lint: &mut impl FnMut(LintId, MultiSpan, EmitAttribute), + has_target_checked_doc_comment: &mut bool, +) { + if matches!(parser.should_emit, ShouldEmit::Nothing) { + return; + } + if mem::replace(has_target_checked_doc_comment, true) { + return; + } + let target = Target::from_ast_target(target); + let res = DOC_TARGETS.is_allowed(target); + if res == AllowedResult::Allowed { + return; + } + + let sub = match attr.kind { + AttrKind::DocComment(CommentKind::Line, _) | AttrKind::Normal(..) => { + BuiltinUnusedDocCommentSub::PlainHelp + } + AttrKind::DocComment(CommentKind::Block, _) => BuiltinUnusedDocCommentSub::BlockHelp, + AttrKind::Synthetic(..) | AttrKind::Generated(..) => unreachable!(), + }; + + let context = + if attr.span.ctxt() == target_span.ctxt() { target_span.shrink_to_lo() } else { attr.span }; + + let attr_span = attr.span; + emit_lint( + LintId::of(UNUSED_DOC_COMMENTS), + attr_span.into(), + EmitAttribute(Box::new(move |dcx, level, _| { + BuiltinUnusedDocComment { sub, target: target.plural_name(), label: attr_span, context } + .into_diag(dcx, level) + })), + ); +} + +/// This set of targets is used both for the `doc` attribute and doc comments. +pub(crate) const DOC_TARGETS: AllowedTargets<'static> = { + AllowedTargets::AllowListWarnRest(&[ + Allow(Target::Use), + Allow(Target::Static), + Allow(Target::Const), + Allow(Target::Fn), + Allow(Target::Mod), + Allow(Target::Enum), + Allow(Target::Variant), + Allow(Target::Struct), + Allow(Target::Field), + Allow(Target::Union), + Allow(Target::Trait), + Allow(Target::TraitAlias), + Allow(Target::TyAlias), + Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: false })), + Allow(Target::AssocConst(AssocCtxt::Trait)), + Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: true })), + Allow(Target::Method(MethodKind::Inherent)), + Allow(Target::Method(MethodKind::Trait { body: false })), + Allow(Target::Method(MethodKind::Trait { body: true })), + Allow(Target::Method(MethodKind::TraitImpl)), + Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: false })), + Allow(Target::AssocTy(AssocCtxt::Trait)), + Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: true })), + Allow(Target::ForeignFn), + Allow(Target::ForeignStatic), + Allow(Target::ForeignTy), + Allow(Target::MacroDef), + Allow(Target::Crate), + Allow(Target::ExternCrate), + Allow(Target::Impl { of_trait: false }), + Allow(Target::Impl { of_trait: true }), + AllowSilent(Target::WherePredicate), // Error, checked elsewhere + Error(Target::Param), + ]) +}; diff --git a/compiler/rustc_attr_parsing/src/attributes/mod.rs b/compiler/rustc_attr_parsing/src/attributes/mod.rs index 1a9c23150a894..7475c86ba14d0 100644 --- a/compiler/rustc_attr_parsing/src/attributes/mod.rs +++ b/compiler/rustc_attr_parsing/src/attributes/mod.rs @@ -48,6 +48,7 @@ pub(crate) mod debugger; pub(crate) mod deprecation; pub(crate) mod diagnostic; pub(crate) mod doc; +pub(crate) mod doc_comment; pub(crate) mod dummy; pub(crate) mod inline; pub(crate) mod instruction_set; diff --git a/compiler/rustc_attr_parsing/src/attributes/prelude.rs b/compiler/rustc_attr_parsing/src/attributes/prelude.rs index 76ce02833d797..d406cfb6c2b0b 100644 --- a/compiler/rustc_attr_parsing/src/attributes/prelude.rs +++ b/compiler/rustc_attr_parsing/src/attributes/prelude.rs @@ -18,11 +18,11 @@ pub(super) use crate::attributes::{ pub(super) use crate::context::{AcceptContext, FinalizeCheckContext, FinalizeContext}; #[doc(hidden)] pub(super) use crate::parser::*; +#[doc(hidden)] +pub(super) use crate::target_checking::AllowedTargets; // target checking #[doc(hidden)] pub(super) use crate::target_checking::Policy::{Allow, Error, Warn}; #[doc(hidden)] -pub(super) use crate::target_checking::{ALL_TARGETS, AllowedTargets}; -#[doc(hidden)] pub(super) use crate::unstable; pub(super) use crate::{AttributeTemplate, template}; diff --git a/compiler/rustc_attr_parsing/src/diagnostics.rs b/compiler/rustc_attr_parsing/src/diagnostics.rs index d419bcd429a3b..868f4b347a27f 100644 --- a/compiler/rustc_attr_parsing/src/diagnostics.rs +++ b/compiler/rustc_attr_parsing/src/diagnostics.rs @@ -1060,13 +1060,6 @@ pub(crate) struct DocAttrNotCrateLevel { pub attr_name: Symbol, } -#[derive(Diagnostic)] -#[diag("`#[doc(...)]` isn't allowed on parameters")] -pub(crate) struct DocAttrNotParameters { - #[primary_span] - pub span: Span, -} - #[derive(Diagnostic)] #[diag("nonexistent keyword `{$keyword}` used in `#[doc(keyword = \"...\")]`")] #[help("only existing keywords are allowed in core/std")] @@ -2271,3 +2264,23 @@ pub(crate) struct UnknownLintHelper { pub span: Span, pub unknown: Symbol, } + +#[derive(Diagnostic)] +#[diag("unused doc comment")] +pub(crate) struct BuiltinUnusedDocComment { + #[subdiagnostic] + pub sub: BuiltinUnusedDocCommentSub, + pub target: &'static str, + #[label("rustdoc does not generate documentation for {$target}")] + pub label: Span, + #[context] + pub context: Span, +} + +#[derive(Subdiagnostic)] +pub(crate) enum BuiltinUnusedDocCommentSub { + #[help("use `//` for a plain comment")] + PlainHelp, + #[help("use `/* */` for a plain comment")] + BlockHelp, +} diff --git a/compiler/rustc_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index 9bd489a5aea8f..92cf6813bd22e 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -15,6 +15,7 @@ use rustc_session::Session; use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym}; use crate::attributes::AttributeSafety; +use crate::attributes::doc_comment::target_check_doc_comment; use crate::context::{ ATTRIBUTE_PARSERS, AcceptContext, FinalizeCheckContext, FinalizeCheckFn, FinalizeContext, FinalizeFn, FinalizeOutput, SharedContext, @@ -326,6 +327,7 @@ impl<'sess> AttributeParser<'sess> { let mut attr_paths: Vec> = Vec::new(); let mut synthetic_attr_state = SyntheticAttrState::default(); let mut generated_attr_state = GeneratedAttrState::default(); + let mut has_target_checked_doc_comment = false; let mut finalizers: Vec = Vec::with_capacity(attrs.len()); @@ -340,6 +342,14 @@ impl<'sess> AttributeParser<'sess> { let attr_span = lower_span(attr.span); match &attr.kind { ast::AttrKind::DocComment(comment_kind, symbol) => { + target_check_doc_comment( + &self, + attr, + &ast_target, + target_span, + &mut emit_lint, + &mut has_target_checked_doc_comment, + ); attributes.push(Attribute::Parsed(AttributeKind::DocComment { style: attr.style, kind: DocFragmentKind::Sugared(*comment_kind), @@ -406,6 +416,14 @@ impl<'sess> AttributeParser<'sess> { // emit an error with `AcceptContext`. && let Some(comment) = nv.value_as_str() { + target_check_doc_comment( + &self, + attr, + &ast_target, + target_span, + &mut emit_lint, + &mut false, // always linted + ); attributes.push(Attribute::Parsed(AttributeKind::DocComment { style: attr.style, kind: DocFragmentKind::Raw(nv.value_span), diff --git a/compiler/rustc_attr_parsing/src/target_checking.rs b/compiler/rustc_attr_parsing/src/target_checking.rs index 0dfd7aa0b8acf..887b269881cee 100644 --- a/compiler/rustc_attr_parsing/src/target_checking.rs +++ b/compiler/rustc_attr_parsing/src/target_checking.rs @@ -1,12 +1,13 @@ use std::borrow::Cow; use rustc_ast::{AttrStyle, Safety}; -use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target}; +use rustc_attr_ir::target::{MethodKind, Target}; use rustc_attr_ir::{AttrItem, Attribute, AttributeKind}; use rustc_errors::{DiagArgValue, MultiSpan, StashKey}; use rustc_feature::Features; use rustc_lint_defs::builtin::{ - INVALID_DOC_ATTRIBUTES, MISPLACED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES, USELESS_DEPRECATED, + INVALID_DOC_ATTRIBUTES, MISPLACED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES, + UNUSED_DOC_COMMENTS, USELESS_DEPRECATED, }; use rustc_span::{BytePos, FileName, RemapPathScopeComponents, Span, Symbol, sym}; @@ -28,6 +29,7 @@ pub(crate) enum AllowedTargets<'a> { ManuallyChecked, } +#[derive(Eq, PartialEq, Copy, Clone)] pub(crate) enum AllowedResult { Allowed, Warn, @@ -181,6 +183,8 @@ impl<'sess> AttributeParser<'sess> { .contains(&cx.target) { USELESS_DEPRECATED + } else if cx.attr_path.segments[0] == sym::doc && attribute_args == "" { + UNUSED_DOC_COMMENTS //FIXME this is strange... } else if is_diagnostic_attr { MISPLACED_DIAGNOSTIC_ATTRIBUTES } else { @@ -506,64 +510,3 @@ impl<'f, 'sess> AcceptContext<'f, 'sess> { } } } - -/// This is the list of all targets to which a attribute can be applied -/// This is used for: -/// - `rustc_dummy`, which can be applied to all targets -/// - Attributes that are not parted to the new target system yet can use this list as a placeholder -pub(crate) const ALL_TARGETS: &[Policy] = { - use Policy::Allow; - &[ - Allow(Target::ExternCrate), - Allow(Target::Use), - Allow(Target::Static), - Allow(Target::Const), - Allow(Target::Fn), - Allow(Target::Closure), - Allow(Target::Mod), - Allow(Target::ForeignMod), - Allow(Target::GlobalAsm), - Allow(Target::TyAlias), - Allow(Target::Enum), - Allow(Target::Variant), - Allow(Target::Struct), - Allow(Target::Field), - Allow(Target::Union), - Allow(Target::Trait), - Allow(Target::TraitAlias), - Allow(Target::Impl { of_trait: false }), - Allow(Target::Impl { of_trait: true }), - Allow(Target::Expression), - Allow(Target::Statement), - Allow(Target::Arm), - Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: false })), - Allow(Target::AssocConst(AssocCtxt::Trait)), - Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: true })), - Allow(Target::Method(MethodKind::Inherent)), - Allow(Target::Method(MethodKind::Trait { body: false })), - Allow(Target::Method(MethodKind::Trait { body: true })), - Allow(Target::Method(MethodKind::TraitImpl)), - Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: false })), - Allow(Target::AssocTy(AssocCtxt::Trait)), - Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: true })), - Allow(Target::ForeignFn), - Allow(Target::ForeignStatic), - Allow(Target::ForeignTy), - Allow(Target::MacroDef), - Allow(Target::Param), - Allow(Target::PatField), - Allow(Target::ExprField), - Allow(Target::WherePredicate), - Allow(Target::MacroCall), - Allow(Target::Crate), - Allow(Target::Delegation { mac: false }), - Allow(Target::Delegation { mac: true }), - Allow(Target::ConstParam), - Allow(Target::LifetimeParam), - Allow(Target::TypeParam), - Allow(Target::Loop), - Allow(Target::ForLoop), - Allow(Target::While), - Allow(Target::Break), - ] -}; diff --git a/compiler/rustc_expand/src/diagnostics.rs b/compiler/rustc_expand/src/diagnostics.rs index 481b2d5346300..82a28aa5e3785 100644 --- a/compiler/rustc_expand/src/diagnostics.rs +++ b/compiler/rustc_expand/src/diagnostics.rs @@ -568,16 +568,6 @@ pub(crate) struct MacroArgsBadDelimSugg { pub close: Span, } -#[derive(Diagnostic)] -#[diag("unused doc comment")] -#[help( - "to document an item produced by a macro, the macro must produce the documentation as part of its expansion" -)] -pub(crate) struct MacroCallUnusedDocComment { - #[label("rustdoc does not generate documentation for macro invocations")] - pub span: Span, -} - #[derive(Diagnostic)] #[diag( "the meaning of the `pat` fragment specifier is changing in Rust 2021, which may affect this macro" diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 935532fddcc9e..d3dea34aff80e 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -1,7 +1,7 @@ use std::path::PathBuf; use std::rc::Rc; use std::sync::Arc; -use std::{iter, mem, slice}; +use std::{iter, mem}; use rustc_ast::mut_visit::*; use rustc_ast::tokenstream::TokenStream; @@ -23,7 +23,6 @@ use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_errors::PResult; use rustc_feature::Features; use rustc_hir::def::MacroKinds; -use rustc_lint_defs::builtin::UNUSED_DOC_COMMENTS; use rustc_parse::parser::{ AllowConstBlockItems, AttemptLocalParseRecovery, CommaRecoveryMode, ForceCollect, Parser, RecoverColon, RecoverComma, Recovery, token_descr, @@ -2229,42 +2228,17 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { // Run attributes through the attribute parser // since they will not be detected after macro expansion. fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) { - let mut attrs = attrs.iter().peekable(); - let mut span: Option = None; - while let Some(attr) = attrs.next() { - AttributeParser::parse_limited_all( - self.cx.sess, - slice::from_ref(attr), - None, - AstTarget::MacroCall, - call.span(), - self.cx.current_expansion.lint_node_id, - Some(self.cx.ecfg.features), - ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, - Some(self.cx.resolver.registered_attr_tools()), - ); - - let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span }; - span = Some(current_span); - - if attrs.peek().is_some_and(|next_attr| next_attr.doc_str().is_some()) { - continue; - } - - if match &attr.kind { - AttrKind::Normal(normal) => normal.item.name() == Some(sym::doc), - AttrKind::DocComment(..) => true, - _ => false, - } { - self.cx.sess.psess.buffer_lint( - UNUSED_DOC_COMMENTS, - current_span, - self.cx.current_expansion.lint_node_id, - crate::diagnostics::MacroCallUnusedDocComment { span: attr.span }, - ); - continue; - } - } + AttributeParser::parse_limited_all( + self.cx.sess, + attrs, + None, + AstTarget::MacroCall, + call.span(), + self.cx.current_expansion.lint_node_id, + Some(self.cx.ecfg.features), + ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, + Some(self.cx.resolver.registered_attr_tools()), + ); } fn expand_cfg_true( diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index a376252ad1038..e5ef13c2b1ada 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -56,8 +56,7 @@ use crate::diagnostics::{ BuiltinNonShorthandFieldPatterns, BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, BuiltinTypeAliasBounds, BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures, - BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub, BuiltinWhileTrue, - EqInternalMethodImplemented, InvalidAsmLabel, + BuiltinWhileTrue, EqInternalMethodImplemented, InvalidAsmLabel, }; use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; @@ -738,106 +737,6 @@ impl EarlyLintPass for AnonymousParameters { } } -fn warn_if_doc(cx: &EarlyContext<'_>, node_span: Span, node_kind: &str, attrs: &[ast::Attribute]) { - use rustc_ast::token::CommentKind; - - let mut attrs = attrs.iter().peekable(); - - // Accumulate a single span for sugared doc comments. - let mut sugared_span: Option = None; - - while let Some(attr) = attrs.next() { - let (is_doc_comment, is_doc_attribute) = match &attr.kind { - AttrKind::DocComment(..) => (true, false), - AttrKind::Normal(normal) if normal.item.path == sym::doc => (true, true), - _ => (false, false), - }; - if is_doc_comment { - sugared_span = - Some(sugared_span.map_or(attr.span, |span| span.with_hi(attr.span.hi()))); - } - - if !is_doc_attribute && attrs.peek().is_some_and(|next_attr| next_attr.is_doc_comment()) { - continue; - } - - let span = sugared_span.take().unwrap_or(attr.span); - - if is_doc_comment || is_doc_attribute { - let sub = match attr.kind { - AttrKind::DocComment(CommentKind::Line, _) | AttrKind::Normal(..) => { - BuiltinUnusedDocCommentSub::PlainHelp - } - AttrKind::DocComment(CommentKind::Block, _) => { - BuiltinUnusedDocCommentSub::BlockHelp - } - AttrKind::Synthetic(..) | AttrKind::Generated(..) => unreachable!(), - }; - cx.emit_span_lint( - UNUSED_DOC_COMMENTS, - span, - BuiltinUnusedDocComment { kind: node_kind, label: node_span, sub }, - ); - } - } -} - -impl EarlyLintPass for UnusedDocComment { - fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) { - let kind = match stmt.kind { - ast::StmtKind::Let(..) => "statements", - // Disabled pending discussion in #78306 - ast::StmtKind::Item(..) => return, - // expressions will be reported by `check_expr`. - ast::StmtKind::Empty - | ast::StmtKind::Semi(_) - | ast::StmtKind::Expr(_) - | ast::StmtKind::MacCall(_) => return, - }; - - warn_if_doc(cx, stmt.span, kind, stmt.kind.attrs()); - } - - fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) { - if let Some(body) = &arm.body { - let arm_span = arm.pat.span.with_hi(body.span.hi()); - warn_if_doc(cx, arm_span, "match arms", &arm.attrs); - } - } - - fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) { - if let ast::PatKind::Struct(_, _, fields, _) = &pat.kind { - for field in fields { - warn_if_doc(cx, field.span, "pattern fields", &field.attrs); - } - } - } - - fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) { - warn_if_doc(cx, expr.span, "expressions", &expr.attrs); - - if let ExprKind::Struct(s) = &expr.kind { - for field in &s.fields { - warn_if_doc(cx, field.span, "expression fields", &field.attrs); - } - } - } - - fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) { - warn_if_doc(cx, param.ident.span, "generic parameters", ¶m.attrs); - } - - fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) { - warn_if_doc(cx, block.span, "blocks", block.attrs()); - } - - fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) { - if let ast::ItemKind::ForeignMod(_) = item.kind { - warn_if_doc(cx, item.span, "extern blocks", &item.attrs); - } - } -} - declare_lint! { /// The `no_mangle_const_items` lint detects any `const` items with the /// [`no_mangle` attribute]. diff --git a/compiler/rustc_lint/src/diagnostics.rs b/compiler/rustc_lint/src/diagnostics.rs index 2b1a8132e65e8..6bb0944a85760 100644 --- a/compiler/rustc_lint/src/diagnostics.rs +++ b/compiler/rustc_lint/src/diagnostics.rs @@ -312,24 +312,6 @@ pub(crate) struct BuiltinAnonymousParams<'a> { pub ty_snip: &'a str, } -#[derive(Diagnostic)] -#[diag("unused doc comment")] -pub(crate) struct BuiltinUnusedDocComment<'a> { - pub kind: &'a str, - #[label("rustdoc does not generate documentation for {$kind}")] - pub label: Span, - #[subdiagnostic] - pub sub: BuiltinUnusedDocCommentSub, -} - -#[derive(Subdiagnostic)] -pub(crate) enum BuiltinUnusedDocCommentSub { - #[help("use `//` for a plain comment")] - PlainHelp, - #[help("use `/* */` for a plain comment")] - BlockHelp, -} - #[derive(Diagnostic)] #[diag("const items should never be `#[no_mangle]`")] pub(crate) struct BuiltinConstNoMangle { diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 97c500ba74cee..2c3365028844a 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -194,7 +194,6 @@ early_lint_methods!( SpecialModuleName: SpecialModuleName, UnsafeCode: UnsafeCode, UnusedBraces: UnusedBraces, - UnusedDocComment: UnusedDocComment, UnusedImportBraces: UnusedImportBraces, UnusedParens: UnusedParens::default(), WhileTrue: WhileTrue, diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index d6e4b3b0bac7b..f1bf802dad9d0 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -7,7 +7,7 @@ //! When removing a lint, make sure to also add a call to `register_removed` in //! compiler/rustc_lint/src/lib.rs. -use crate::{declare_lint, declare_lint_pass, fcw}; +use crate::{declare_lint, fcw}; pub mod hardwired { use super::*; @@ -148,6 +148,7 @@ pub mod hardwired { UNUSED_ASSOCIATED_TYPE_BOUNDS, UNUSED_ATTRIBUTES, UNUSED_CRATE_DEPENDENCIES, + UNUSED_DOC_COMMENTS, UNUSED_EXTERN_CRATES, UNUSED_FEATURES, UNUSED_IMPORTS, @@ -3482,8 +3483,6 @@ declare_lint! { }; } -declare_lint_pass!(UnusedDocComment => [UNUSED_DOC_COMMENTS]); - declare_lint! { /// The `missing_abi` lint detects cases where the ABI is omitted from /// `extern` declarations. diff --git a/tests/rustdoc-ui/check-doc-alias-attr-location.rs b/tests/rustdoc-ui/check-doc-alias-attr-location.rs index 2b272b7066793..ac7d519a65c99 100644 --- a/tests/rustdoc-ui/check-doc-alias-attr-location.rs +++ b/tests/rustdoc-ui/check-doc-alias-attr-location.rs @@ -5,8 +5,10 @@ pub trait Foo { } // FIXME(#96009): Don't emit `unused_doc_comments` here, we already emit an error anyway. -//~v WARN -#[doc(alias = "foo")] //~ ERROR +#[doc(alias = "foo")] +//~^ ERROR `#[doc(alias = "...")]` isn't allowed on +//~| WARN cannot be used on +//~| WARN previously accepted extern "C" {} #[doc(alias = "bar")] //~ ERROR diff --git a/tests/rustdoc-ui/check-doc-alias-attr-location.stderr b/tests/rustdoc-ui/check-doc-alias-attr-location.stderr index ace40d4fe7c91..9f4d7a09d46ec 100644 --- a/tests/rustdoc-ui/check-doc-alias-attr-location.stderr +++ b/tests/rustdoc-ui/check-doc-alias-attr-location.stderr @@ -1,37 +1,38 @@ -warning: unused doc comment - --> $DIR/check-doc-alias-attr-location.rs:9:1 - | -LL | #[doc(alias = "foo")] - | ^^^^^^^^^^^^^^^^^^^^^ -LL | extern "C" {} - | ------------- rustdoc does not generate documentation for extern blocks - | - = help: use `//` for a plain comment - = note: `#[warn(unused_doc_comments)]` (part of `#[warn(unused)]`) on by default - error: `#[doc(alias = "...")]` isn't allowed on foreign module - --> $DIR/check-doc-alias-attr-location.rs:9:15 + --> $DIR/check-doc-alias-attr-location.rs:8:15 | LL | #[doc(alias = "foo")] | ^^^^^ error: `#[doc(alias = "...")]` isn't allowed on implementation block - --> $DIR/check-doc-alias-attr-location.rs:12:15 + --> $DIR/check-doc-alias-attr-location.rs:14:15 | LL | #[doc(alias = "bar")] | ^^^^^ error: `#[doc(alias = "...")]` isn't allowed on implementation block - --> $DIR/check-doc-alias-attr-location.rs:18:15 + --> $DIR/check-doc-alias-attr-location.rs:20:15 | LL | #[doc(alias = "foobar")] | ^^^^^^^^ error: `#[doc(alias = "...")]` isn't allowed on type alias in implementation block - --> $DIR/check-doc-alias-attr-location.rs:20:19 + --> $DIR/check-doc-alias-attr-location.rs:22:19 | LL | #[doc(alias = "assoc")] | ^^^^^^^ +warning: the `doc` attribute cannot be used on foreign modules + --> $DIR/check-doc-alias-attr-location.rs:8:3 + | +LL | #[doc(alias = "foo")] + | ^^^ +... +LL | extern "C" {} + | + = help: the `doc` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, extern crates, foreign statics, functions, impl blocks, macro defs, modules, statics, struct fields, trait aliases, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: `#[warn(unused_doc_comments)]` (part of `#[warn(unused)]`) on by default + error: aborting due to 4 previous errors; 1 warning emitted diff --git a/tests/rustdoc-ui/lints/unused-doc-comments.stderr b/tests/rustdoc-ui/lints/unused-doc-comments.stderr index 65656ee78f717..dc74154e24005 100644 --- a/tests/rustdoc-ui/lints/unused-doc-comments.stderr +++ b/tests/rustdoc-ui/lints/unused-doc-comments.stderr @@ -2,24 +2,24 @@ warning: unused doc comment --> $DIR/unused-doc-comments.rs:10:1 | LL | /** */ m!(); - | ^^^^^^ rustdoc does not generate documentation for macro invocations + | ^^^^^^ rustdoc does not generate documentation for macro calls | - = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion + = help: use `/* */` for a plain comment = note: `#[warn(unused_doc_comments)]` (part of `#[warn(unused)]`) on by default warning: unused doc comment - --> $DIR/unused-doc-comments.rs:4:10 + --> $DIR/unused-doc-comments.rs:5:5 | -LL | pub fn f() { - | ^^^^^^- rustdoc does not generate documentation for generic parameters +LL | /** */ let (); + | ^^^^^^ rustdoc does not generate documentation for statements | = help: use `/* */` for a plain comment warning: unused doc comment - --> $DIR/unused-doc-comments.rs:5:5 + --> $DIR/unused-doc-comments.rs:4:10 | -LL | /** */ let (); - | ^^^^^^ ------- rustdoc does not generate documentation for statements +LL | pub fn f() { + | ^^^^^^ rustdoc does not generate documentation for type parameters | = help: use `/* */` for a plain comment diff --git a/tests/ui/attributes/attr-on-mac-call.rs b/tests/ui/attributes/attr-on-mac-call.rs index 28fbd0ca48600..da57853f4bddd 100644 --- a/tests/ui/attributes/attr-on-mac-call.rs +++ b/tests/ui/attributes/attr-on-mac-call.rs @@ -8,72 +8,95 @@ fn main() { #[export_name = "x"] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[unsafe(naked)] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[track_caller] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[used] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[target_feature(enable = "x")] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[deprecated] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[inline] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[link_name = "x"] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[link_section = "__TEXT,__text"] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[link_ordinal(42)] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[non_exhaustive] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[proc_macro] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[cold] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[no_mangle] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[deprecated] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[automatically_derived] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[macro_use] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[must_use] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[no_implicit_prelude] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[path = ""] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[ignore] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[should_panic] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[link_name = "x"] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[sanitize(address = "off")] //~^ ERROR attribute cannot be used on macro calls unreachable!(); diff --git a/tests/ui/attributes/attr-on-mac-call.stderr b/tests/ui/attributes/attr-on-mac-call.stderr index 0d6fe64db735f..d51f3ef574688 100644 --- a/tests/ui/attributes/attr-on-mac-call.stderr +++ b/tests/ui/attributes/attr-on-mac-call.stderr @@ -1,5 +1,5 @@ error: the `sanitize` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:77:7 + --> $DIR/attr-on-mac-call.rs:100:7 | LL | #[sanitize(address = "off")] | ^^^^^^^^ @@ -10,7 +10,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion error[E0658]: SIMD types are experimental and possibly buggy - --> $DIR/attr-on-mac-call.rs:106:12 + --> $DIR/attr-on-mac-call.rs:129:12 | LL | #[repr(simd)] | ^^^^ @@ -20,7 +20,7 @@ LL | #[repr(simd)] = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error: the `repr(simd)` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:106:7 + --> $DIR/attr-on-mac-call.rs:129:7 | LL | #[repr(simd)] | ^^^^^^^^^^ @@ -31,31 +31,31 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion error: crate-level attribute should be an inner attribute: add an exclamation mark: `#![register_tool]` - --> $DIR/attr-on-mac-call.rs:110:5 + --> $DIR/attr-on-mac-call.rs:133:5 | LL | #[register_tool(xyz)] | ^^^^^^^^^^^^^^^^^^^^^ | note: this attribute does not have an `!`, which means it is applied to this macro call - --> $DIR/attr-on-mac-call.rs:112:5 + --> $DIR/attr-on-mac-call.rs:135:5 | LL | unreachable!(); | ^^^^^^^^^^^^^^ error: attribute value must be a literal - --> $DIR/attr-on-mac-call.rs:113:20 + --> $DIR/attr-on-mac-call.rs:136:20 | LL | #[deprecated = concat!("woah", "dude")] | ^^^^^^^^^^^^^^^^^^^^^^^ error: attribute value must be a literal - --> $DIR/attr-on-mac-call.rs:115:13 + --> $DIR/attr-on-mac-call.rs:138:13 | LL | #[doc = concat!("woah", "dude")] | ^^^^^^^^^^^^^^^^^^^^^^^ error: attribute value must be a literal - --> $DIR/attr-on-mac-call.rs:118:13 + --> $DIR/attr-on-mac-call.rs:141:13 | LL | #[doc = { | _____________^ @@ -67,7 +67,7 @@ LL | | }] | |_____^ error: attribute value must be a literal - --> $DIR/attr-on-mac-call.rs:126:13 + --> $DIR/attr-on-mac-call.rs:149:13 | LL | #[doc = { | _____________^ @@ -93,7 +93,7 @@ LL | #![warn(unused_attributes)] | ^^^^^^^^^^^^^^^^^ warning: the `naked` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:11:14 + --> $DIR/attr-on-mac-call.rs:12:14 | LL | #[unsafe(naked)] | ^^^^^ @@ -105,7 +105,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `track_caller` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:14:7 + --> $DIR/attr-on-mac-call.rs:16:7 | LL | #[track_caller] | ^^^^^^^^^^^^ @@ -117,7 +117,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `used` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:17:7 + --> $DIR/attr-on-mac-call.rs:20:7 | LL | #[used] | ^^^^ @@ -129,7 +129,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `target_feature` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:20:7 + --> $DIR/attr-on-mac-call.rs:24:7 | LL | #[target_feature(enable = "x")] | ^^^^^^^^^^^^^^ @@ -141,7 +141,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `deprecated` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:23:7 + --> $DIR/attr-on-mac-call.rs:28:7 | LL | #[deprecated] | ^^^^^^^^^^ @@ -153,7 +153,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `inline` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:26:7 + --> $DIR/attr-on-mac-call.rs:32:7 | LL | #[inline] | ^^^^^^ @@ -165,7 +165,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `link_name` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:29:7 + --> $DIR/attr-on-mac-call.rs:36:7 | LL | #[link_name = "x"] | ^^^^^^^^^ @@ -177,7 +177,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `link_section` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:32:7 + --> $DIR/attr-on-mac-call.rs:40:7 | LL | #[link_section = "__TEXT,__text"] | ^^^^^^^^^^^^ @@ -189,7 +189,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `link_ordinal` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:35:7 + --> $DIR/attr-on-mac-call.rs:44:7 | LL | #[link_ordinal(42)] | ^^^^^^^^^^^^ @@ -201,7 +201,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `non_exhaustive` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:38:7 + --> $DIR/attr-on-mac-call.rs:48:7 | LL | #[non_exhaustive] | ^^^^^^^^^^^^^^ @@ -213,7 +213,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `proc_macro` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:41:7 + --> $DIR/attr-on-mac-call.rs:52:7 | LL | #[proc_macro] | ^^^^^^^^^^ @@ -225,7 +225,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `cold` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:44:7 + --> $DIR/attr-on-mac-call.rs:56:7 | LL | #[cold] | ^^^^ @@ -237,7 +237,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `no_mangle` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:47:7 + --> $DIR/attr-on-mac-call.rs:60:7 | LL | #[no_mangle] | ^^^^^^^^^ @@ -249,7 +249,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `deprecated` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:50:7 + --> $DIR/attr-on-mac-call.rs:64:7 | LL | #[deprecated] | ^^^^^^^^^^ @@ -261,7 +261,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `automatically_derived` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:53:7 + --> $DIR/attr-on-mac-call.rs:68:7 | LL | #[automatically_derived] | ^^^^^^^^^^^^^^^^^^^^^ @@ -273,7 +273,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `macro_use` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:56:7 + --> $DIR/attr-on-mac-call.rs:72:7 | LL | #[macro_use] | ^^^^^^^^^ @@ -285,7 +285,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `must_use` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:59:7 + --> $DIR/attr-on-mac-call.rs:76:7 | LL | #[must_use] | ^^^^^^^^ @@ -297,7 +297,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `no_implicit_prelude` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:62:7 + --> $DIR/attr-on-mac-call.rs:80:7 | LL | #[no_implicit_prelude] | ^^^^^^^^^^^^^^^^^^^ @@ -309,7 +309,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `path` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:65:7 + --> $DIR/attr-on-mac-call.rs:84:7 | LL | #[path = ""] | ^^^^ @@ -321,7 +321,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `ignore` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:68:7 + --> $DIR/attr-on-mac-call.rs:88:7 | LL | #[ignore] | ^^^^^^ @@ -333,7 +333,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `should_panic` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:71:7 + --> $DIR/attr-on-mac-call.rs:92:7 | LL | #[should_panic] | ^^^^^^^^^^^^ @@ -345,7 +345,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `link_name` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:74:7 + --> $DIR/attr-on-mac-call.rs:96:7 | LL | #[link_name = "x"] | ^^^^^^^^^ @@ -357,7 +357,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `repr()` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:81:7 + --> $DIR/attr-on-mac-call.rs:104:7 | LL | #[repr()] | ^^^^^^ @@ -369,7 +369,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: unused attribute - --> $DIR/attr-on-mac-call.rs:81:5 + --> $DIR/attr-on-mac-call.rs:104:5 | LL | #[repr()] | ^^^^^^^^^ help: remove this attribute @@ -377,7 +377,7 @@ LL | #[repr()] = note: using `repr` with an empty list has no effect warning: the `repr(u8)` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:86:7 + --> $DIR/attr-on-mac-call.rs:109:7 | LL | #[repr(u8)] | ^^^^^^^^ @@ -389,7 +389,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `repr(align(...))` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:90:7 + --> $DIR/attr-on-mac-call.rs:113:7 | LL | #[repr(align(8))] | ^^^^^^^^^^^^^^ @@ -401,7 +401,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `repr(packed)` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:94:7 + --> $DIR/attr-on-mac-call.rs:117:7 | LL | #[repr(packed)] | ^^^^^^^^^^^^ @@ -413,7 +413,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `repr(C)` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:98:7 + --> $DIR/attr-on-mac-call.rs:121:7 | LL | #[repr(C)] | ^^^^^^^ @@ -425,7 +425,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `repr(Rust)` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:102:7 + --> $DIR/attr-on-mac-call.rs:125:7 | LL | #[repr(Rust)] | ^^^^^^^^^^ diff --git a/tests/ui/lint/unused/unused-doc-comments-edge-cases.stderr b/tests/ui/lint/unused/unused-doc-comments-edge-cases.stderr index 0f0288c6def60..c390238d61bd9 100644 --- a/tests/ui/lint/unused/unused-doc-comments-edge-cases.stderr +++ b/tests/ui/lint/unused/unused-doc-comments-edge-cases.stderr @@ -19,10 +19,9 @@ error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:6:9 | LL | /// useless doc comment - | ^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for match arms LL | LL | _ => false, - | ---------- rustdoc does not generate documentation for match arms | = help: use `//` for a plain comment note: the lint level is defined here @@ -35,10 +34,9 @@ error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:23:5 | LL | /// useless doc comment - | ^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions ... LL | num == 3 - | --- rustdoc does not generate documentation for expressions | = help: use `//` for a plain comment @@ -46,10 +44,9 @@ error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:33:9 | LL | /// useless doc comment - | ^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for struct fields LL | LL | foo: 3 - | ------ rustdoc does not generate documentation for expression fields | = help: use `//` for a plain comment @@ -57,10 +54,9 @@ error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:45:9 | LL | /// useless doc comment - | ^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for pattern fields LL | LL | foo - | --- rustdoc does not generate documentation for pattern fields | = help: use `//` for a plain comment @@ -68,33 +64,27 @@ error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:55:27 | LL | fn doc_comment_on_generic<#[doc = "x"] T>(val: T) {} - | ^^^^^^^^^^^^ - rustdoc does not generate documentation for generic parameters + | ^^^^^^^^^^^^ rustdoc does not generate documentation for type parameters | = help: use `//` for a plain comment error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:59:5 | -LL | /// unused doc comment - | ^^^^^^^^^^^^^^^^^^^^^^ +LL | /// unused doc comment + | ^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions LL | -LL | / { -LL | | let x = 12; -LL | | } - | |_____- rustdoc does not generate documentation for expressions +LL | { | = help: use `//` for a plain comment error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:66:1 | -LL | /// unused doc comment - | ^^^^^^^^^^^^^^^^^^^^^^ +LL | /// unused doc comment + | ^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for foreign modules LL | -LL | / extern "C" { -LL | | fn foo(); -LL | | } - | |_- rustdoc does not generate documentation for extern blocks +LL | extern "C" { | = help: use `//` for a plain comment diff --git a/tests/ui/lint/unused/unused-doc-comments-for-macros.rs b/tests/ui/lint/unused/unused-doc-comments-for-macros.rs index 8a3dd45c02115..ebe313baada87 100644 --- a/tests/ui/lint/unused/unused-doc-comments-for-macros.rs +++ b/tests/ui/lint/unused/unused-doc-comments-for-macros.rs @@ -15,14 +15,12 @@ fn main() { /// line3 foo!(); - // Even invalid doc attributes should emit the warning. #[doc = { let a = 1; let b = 1; let sum = a + b; assert_eq!(sum, 2); }] - //~^^^^^^ ERROR: unused doc comment - //~| ERROR attribute value must be a literal + //~^^^^^^ ERROR attribute value must be a literal foo!(); } diff --git a/tests/ui/lint/unused/unused-doc-comments-for-macros.stderr b/tests/ui/lint/unused/unused-doc-comments-for-macros.stderr index 9bb89974f9e23..88972c8196eab 100644 --- a/tests/ui/lint/unused/unused-doc-comments-for-macros.stderr +++ b/tests/ui/lint/unused/unused-doc-comments-for-macros.stderr @@ -1,5 +1,5 @@ error: attribute value must be a literal - --> $DIR/unused-doc-comments-for-macros.rs:19:13 + --> $DIR/unused-doc-comments-for-macros.rs:18:13 | LL | #[doc = { | _____________^ @@ -13,14 +13,12 @@ LL | | }] error: unused doc comment --> $DIR/unused-doc-comments-for-macros.rs:7:5 | -LL | / /// line1 -LL | | /// line2 -LL | | /// line3 - | |_____--------^ - | | - | rustdoc does not generate documentation for macro invocations +LL | /// line1 + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro calls +... +LL | foo!(); | - = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion + = help: use `//` for a plain comment note: the lint level is defined here --> $DIR/unused-doc-comments-for-macros.rs:1:9 | @@ -30,27 +28,12 @@ LL | #![deny(unused_doc_comments)] error: unused doc comment --> $DIR/unused-doc-comments-for-macros.rs:13:5 | -LL | / /// line1 -LL | | /// line2 -LL | | /// line3 - | |_____--------^ - | | - | rustdoc does not generate documentation for macro invocations +LL | /// line1 + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro calls +... +LL | foo!(); | - = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion + = help: use `//` for a plain comment -error: unused doc comment - --> $DIR/unused-doc-comments-for-macros.rs:19:5 - | -LL | / #[doc = { -LL | | let a = 1; -LL | | let b = 1; -LL | | let sum = a + b; -LL | | assert_eq!(sum, 2); -LL | | }] - | |______^ rustdoc does not generate documentation for macro invocations - | - = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion - -error: aborting due to 4 previous errors +error: aborting due to 3 previous errors diff --git a/tests/ui/lint/unused/useless-comment.rs b/tests/ui/lint/unused/useless-comment.rs index 24ff917520814..d04d0a4c116da 100644 --- a/tests/ui/lint/unused/useless-comment.rs +++ b/tests/ui/lint/unused/useless-comment.rs @@ -11,13 +11,16 @@ macro_rules! mac { mac!(); /// a //~ ERROR unused doc comment -#[doc(test(attr(allow(dead_code))))] //~ ERROR unused doc comment +#[doc(test(attr(allow(dead_code))))] +//~^ ERROR `doc` attribute cannot be used on +//~| WARN previously accepted unsafe extern "C" { } fn foo() { /// a //~ ERROR unused doc comment #[doc(test(attr(allow(dead_code))))] - //~^ ERROR unused doc comment + //~^ ERROR `doc` attribute cannot be used on + //~| WARN previously accepted let x = 12; /// multi-line //~ ERROR unused doc comment @@ -27,7 +30,8 @@ fn foo() { /// c //~ ERROR unused doc comment 1 => {}, #[doc(test(attr(allow(dead_code))))] - //~^ ERROR unused doc comment + //~^ ERROR `doc` attribute cannot be used on + //~| WARN previously accepted _ => {} } @@ -42,7 +46,8 @@ fn foo() { mac!(); #[doc(test(attr(allow(dead_code))))] - //~^ ERROR unused doc comment + //~^ ERROR `doc` attribute cannot be used on + //~| WARN previously accepted let x = /** comment */ 47; //~ ERROR unused doc comment /// dox //~ ERROR unused doc comment diff --git a/tests/ui/lint/unused/useless-comment.stderr b/tests/ui/lint/unused/useless-comment.stderr index 22e63caf607a3..a7cafc916430c 100644 --- a/tests/ui/lint/unused/useless-comment.stderr +++ b/tests/ui/lint/unused/useless-comment.stderr @@ -2,9 +2,10 @@ error: unused doc comment --> $DIR/useless-comment.rs:10:1 | LL | /// foo - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro invocations + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro calls +LL | mac!(); | - = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion + = help: use `//` for a plain comment note: the lint level is defined here --> $DIR/useless-comment.rs:3:9 | @@ -12,154 +13,139 @@ LL | #![deny(unused_doc_comments)] | ^^^^^^^^^^^^^^^^^^^ error: unused doc comment - --> $DIR/useless-comment.rs:13:1 + --> $DIR/useless-comment.rs:45:5 | -LL | /// a - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -LL | #[doc(test(attr(allow(dead_code))))] -LL | unsafe extern "C" { } - | --------------------- rustdoc does not generate documentation for extern blocks +LL | /// bar + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro calls +LL | mac!(); | = help: use `//` for a plain comment error: unused doc comment - --> $DIR/useless-comment.rs:14:1 + --> $DIR/useless-comment.rs:13:1 | -LL | #[doc(test(attr(allow(dead_code))))] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | /// a + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for foreign modules +... LL | unsafe extern "C" { } - | --------------------- rustdoc does not generate documentation for extern blocks | = help: use `//` for a plain comment -error: unused doc comment - --> $DIR/useless-comment.rs:41:5 +error: the `doc` attribute cannot be used on foreign modules + --> $DIR/useless-comment.rs:14:3 | -LL | /// bar - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro invocations +LL | #[doc(test(attr(allow(dead_code))))] + | ^^^ +... +LL | unsafe extern "C" { } | - = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion + = help: the `doc` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, extern crates, foreign statics, functions, impl blocks, macro defs, modules, statics, struct fields, trait aliases, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! error: unused doc comment - --> $DIR/useless-comment.rs:18:5 + --> $DIR/useless-comment.rs:20:5 | LL | /// a - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for statements ... LL | let x = 12; - | ----------- rustdoc does not generate documentation for statements | = help: use `//` for a plain comment -error: unused doc comment - --> $DIR/useless-comment.rs:19:5 +error: the `doc` attribute cannot be used on statements + --> $DIR/useless-comment.rs:21:7 | LL | #[doc(test(attr(allow(dead_code))))] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -LL | + | ^^^ +... LL | let x = 12; - | ----------- rustdoc does not generate documentation for statements | - = help: use `//` for a plain comment + = help: the `doc` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, extern crates, foreign statics, functions, impl blocks, macro defs, modules, statics, struct fields, trait aliases, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! error: unused doc comment - --> $DIR/useless-comment.rs:23:5 - | -LL | / /// multi-line -LL | | /// doc comment -LL | | /// that is unused - | |______________________^ -LL | / match x { -LL | | /// c -LL | | 1 => {}, -LL | | #[doc(test(attr(allow(dead_code))))] -LL | | -LL | | _ => {} -LL | | } - | |_____- rustdoc does not generate documentation for expressions + --> $DIR/useless-comment.rs:26:5 + | +LL | /// multi-line + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions +... +LL | match x { | = help: use `//` for a plain comment error: unused doc comment - --> $DIR/useless-comment.rs:27:9 + --> $DIR/useless-comment.rs:30:9 | LL | /// c - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for match arms LL | 1 => {}, - | ------- rustdoc does not generate documentation for match arms | = help: use `//` for a plain comment -error: unused doc comment - --> $DIR/useless-comment.rs:29:9 +error: the `doc` attribute cannot be used on match arms + --> $DIR/useless-comment.rs:32:11 | LL | #[doc(test(attr(allow(dead_code))))] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -LL | + | ^^^ +... LL | _ => {} - | ------- rustdoc does not generate documentation for match arms | - = help: use `//` for a plain comment + = help: the `doc` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, extern crates, foreign statics, functions, impl blocks, macro defs, modules, statics, struct fields, trait aliases, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! error: unused doc comment - --> $DIR/useless-comment.rs:34:5 + --> $DIR/useless-comment.rs:38:5 | LL | /// foo - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions LL | unsafe {} - | --------- rustdoc does not generate documentation for expressions | = help: use `//` for a plain comment error: unused doc comment - --> $DIR/useless-comment.rs:37:5 + --> $DIR/useless-comment.rs:41:5 | LL | #[doc = "foo"] - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions LL | #[doc = "bar"] LL | 3; - | - rustdoc does not generate documentation for expressions | = help: use `//` for a plain comment error: unused doc comment - --> $DIR/useless-comment.rs:38:5 + --> $DIR/useless-comment.rs:42:5 | LL | #[doc = "bar"] - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions LL | 3; - | - rustdoc does not generate documentation for expressions | = help: use `//` for a plain comment error: unused doc comment - --> $DIR/useless-comment.rs:44:5 + --> $DIR/useless-comment.rs:51:13 | -LL | #[doc(test(attr(allow(dead_code))))] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -LL | LL | let x = /** comment */ 47; - | -------------------------- rustdoc does not generate documentation for statements + | ^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions | - = help: use `//` for a plain comment + = help: use `/* */` for a plain comment -error: unused doc comment - --> $DIR/useless-comment.rs:46:13 +error: the `doc` attribute cannot be used on statements + --> $DIR/useless-comment.rs:48:7 | +LL | #[doc(test(attr(allow(dead_code))))] + | ^^^ +... LL | let x = /** comment */ 47; - | ^^^^^^^^^^^^^^ -- rustdoc does not generate documentation for expressions | - = help: use `/* */` for a plain comment + = help: the `doc` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, extern crates, foreign statics, functions, impl blocks, macro defs, modules, statics, struct fields, trait aliases, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! error: unused doc comment - --> $DIR/useless-comment.rs:48:5 - | -LL | /// dox - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -LL | / { -LL | | -LL | | } - | |_____- rustdoc does not generate documentation for expressions + --> $DIR/useless-comment.rs:53:5 + | +LL | /// dox + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions +LL | { | = help: use `//` for a plain comment diff --git a/tests/ui/rustdoc/check-doc-alias-attr-location.stderr b/tests/ui/rustdoc/check-doc-alias-attr-location.stderr index 815bec9f184a9..c7303fe4f01a6 100644 --- a/tests/ui/rustdoc/check-doc-alias-attr-location.stderr +++ b/tests/ui/rustdoc/check-doc-alias-attr-location.stderr @@ -1,8 +1,10 @@ -error: `#[doc(...)]` isn't allowed on parameters - --> $DIR/check-doc-alias-attr-location.rs:22:12 +error: the `doc` attribute cannot be used on function params + --> $DIR/check-doc-alias-attr-location.rs:22:14 | LL | fn foo(#[doc(alias = "qux")] _x: u32) -> Self::X { - | ^^^^^^^^^^^^^^^^^^^^^ + | ^^^ + | + = help: the `doc` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, extern crates, foreign statics, functions, impl blocks, macro defs, modules, statics, struct fields, trait aliases, traits, type aliases, and use statements error: `#[doc(alias = "...")]` isn't allowed on foreign module --> $DIR/check-doc-alias-attr-location.rs:9:15 From 40bd35d6ae3a447dd4e191d1e7de4ce2eab1bb0b Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:12:57 +0100 Subject: [PATCH 31/39] Actually test ABI for C ZSTs Previously we accidentally tested Rust ZSTs instead --- tests/ui/abi/c-zst.aarch64-darwin.stderr | 18 ++--- tests/ui/abi/c-zst.powerpc-linux.stderr | 31 +++++--- tests/ui/abi/c-zst.rs | 16 +++- tests/ui/abi/c-zst.s390x-linux.stderr | 31 +++++--- tests/ui/abi/c-zst.sparc-linux.stderr | 18 ++--- tests/ui/abi/c-zst.sparc-none.stderr | 18 ++--- tests/ui/abi/c-zst.sparc64-linux.stderr | 31 +++++--- tests/ui/abi/c-zst.x86_64-linux.stderr | 18 ++--- .../ui/abi/c-zst.x86_64-pc-windows-gnu.stderr | 44 ++++++++--- tests/ui/abi/rust-zst.aarch64-darwin.stderr | 67 ++++++++++++++++ tests/ui/abi/rust-zst.powerpc-linux.stderr | 67 ++++++++++++++++ tests/ui/abi/rust-zst.rs | 64 +++++++++++++++ tests/ui/abi/rust-zst.s390x-linux.stderr | 67 ++++++++++++++++ tests/ui/abi/rust-zst.sparc-linux.stderr | 78 +++++++++++++++++++ tests/ui/abi/rust-zst.sparc-none.stderr | 78 +++++++++++++++++++ tests/ui/abi/rust-zst.sparc64-linux.stderr | 67 ++++++++++++++++ tests/ui/abi/rust-zst.x86_64-linux.stderr | 67 ++++++++++++++++ .../abi/rust-zst.x86_64-pc-windows-gnu.stderr | 67 ++++++++++++++++ 18 files changed, 767 insertions(+), 80 deletions(-) create mode 100644 tests/ui/abi/rust-zst.aarch64-darwin.stderr create mode 100644 tests/ui/abi/rust-zst.powerpc-linux.stderr create mode 100644 tests/ui/abi/rust-zst.rs create mode 100644 tests/ui/abi/rust-zst.s390x-linux.stderr create mode 100644 tests/ui/abi/rust-zst.sparc-linux.stderr create mode 100644 tests/ui/abi/rust-zst.sparc-none.stderr create mode 100644 tests/ui/abi/rust-zst.sparc64-linux.stderr create mode 100644 tests/ui/abi/rust-zst.x86_64-linux.stderr create mode 100644 tests/ui/abi/rust-zst.x86_64-pc-windows-gnu.stderr diff --git a/tests/ui/abi/c-zst.aarch64-darwin.stderr b/tests/ui/abi/c-zst.aarch64-darwin.stderr index 0d5234a7904ff..ea764cb2cc71e 100644 --- a/tests/ui/abi/c-zst.aarch64-darwin.stderr +++ b/tests/ui/abi/c-zst.aarch64-darwin.stderr @@ -2,7 +2,7 @@ error: fn_abi_of(pass_zst) = FnAbi { args: [ ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -20,8 +20,8 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, mode: Ignore, @@ -29,7 +29,7 @@ error: fn_abi_of(pass_zst) = FnAbi { ], ret: ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -47,8 +47,8 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, mode: Ignore, @@ -58,10 +58,10 @@ error: fn_abi_of(pass_zst) = FnAbi { conv: C, can_unwind: false, } - --> $DIR/c-zst.rs:67:1 + --> $DIR/c-zst.rs:74:1 | -LL | extern "C" fn pass_zst(_: ()) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | extern "C" fn pass_zst(_: Czst) -> Czst { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/abi/c-zst.powerpc-linux.stderr b/tests/ui/abi/c-zst.powerpc-linux.stderr index 0d5234a7904ff..8598792e93815 100644 --- a/tests/ui/abi/c-zst.powerpc-linux.stderr +++ b/tests/ui/abi/c-zst.powerpc-linux.stderr @@ -2,7 +2,7 @@ error: fn_abi_of(pass_zst) = FnAbi { args: [ ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -20,16 +20,27 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, - mode: Ignore, + mode: Indirect { + attrs: ArgAttributes { + regular: CapturesAddress | NoAlias | NonNull | NoUndef | NoFree, + arg_ext: None, + pointee_size: Size(0 bytes), + pointee_align: Some( + Align(1 bytes), + ), + }, + address_space: None, + mode: Pointer, + }, }, ], ret: ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -47,8 +58,8 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, mode: Ignore, @@ -58,10 +69,10 @@ error: fn_abi_of(pass_zst) = FnAbi { conv: C, can_unwind: false, } - --> $DIR/c-zst.rs:67:1 + --> $DIR/c-zst.rs:74:1 | -LL | extern "C" fn pass_zst(_: ()) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | extern "C" fn pass_zst(_: Czst) -> Czst { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/abi/c-zst.rs b/tests/ui/abi/c-zst.rs index c4f6f23f600b4..5a3ba8c672f03 100644 --- a/tests/ui/abi/c-zst.rs +++ b/tests/ui/abi/c-zst.rs @@ -1,5 +1,6 @@ //@ add-minicore //@ normalize-stderr: "(align|unadjusted_abi_align): Align\([1-8] bytes\)" -> "$1: $$SOME_ALIGN" +//@ normalize-stderr: "(randomization_seed): \d+" -> "$1: $$SEED" /*! C doesn't have zero-sized types... except it does. @@ -10,8 +11,11 @@ e.g. despite being "zero-sized", sometimes C compilers decide ZSTs consume regis That means these two function signatures may not be compatible: ``` -extern "C" fn((), i32, i32); -extern "C" fn(i32, (), i32); +#[repr(C)] +struct Czst; + +extern "C" fn(Czst, i32, i32); +extern "C" fn(i32, Czst, i32); ``` */ @@ -63,5 +67,11 @@ extern "C" fn(i32, (), i32); extern crate minicore; use minicore::*; +#[repr(C)] +struct Czst; + #[rustc_abi(debug)] -extern "C" fn pass_zst(_: ()) {} //~ ERROR: fn_abi +extern "C" fn pass_zst(_: Czst) -> Czst { + //~^ ERROR: fn_abi + Czst +} diff --git a/tests/ui/abi/c-zst.s390x-linux.stderr b/tests/ui/abi/c-zst.s390x-linux.stderr index 0d5234a7904ff..8598792e93815 100644 --- a/tests/ui/abi/c-zst.s390x-linux.stderr +++ b/tests/ui/abi/c-zst.s390x-linux.stderr @@ -2,7 +2,7 @@ error: fn_abi_of(pass_zst) = FnAbi { args: [ ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -20,16 +20,27 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, - mode: Ignore, + mode: Indirect { + attrs: ArgAttributes { + regular: CapturesAddress | NoAlias | NonNull | NoUndef | NoFree, + arg_ext: None, + pointee_size: Size(0 bytes), + pointee_align: Some( + Align(1 bytes), + ), + }, + address_space: None, + mode: Pointer, + }, }, ], ret: ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -47,8 +58,8 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, mode: Ignore, @@ -58,10 +69,10 @@ error: fn_abi_of(pass_zst) = FnAbi { conv: C, can_unwind: false, } - --> $DIR/c-zst.rs:67:1 + --> $DIR/c-zst.rs:74:1 | -LL | extern "C" fn pass_zst(_: ()) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | extern "C" fn pass_zst(_: Czst) -> Czst { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/abi/c-zst.sparc-linux.stderr b/tests/ui/abi/c-zst.sparc-linux.stderr index b77a31cceaec2..8598792e93815 100644 --- a/tests/ui/abi/c-zst.sparc-linux.stderr +++ b/tests/ui/abi/c-zst.sparc-linux.stderr @@ -2,7 +2,7 @@ error: fn_abi_of(pass_zst) = FnAbi { args: [ ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -20,8 +20,8 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, mode: Indirect { @@ -40,7 +40,7 @@ error: fn_abi_of(pass_zst) = FnAbi { ], ret: ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -58,8 +58,8 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, mode: Ignore, @@ -69,10 +69,10 @@ error: fn_abi_of(pass_zst) = FnAbi { conv: C, can_unwind: false, } - --> $DIR/c-zst.rs:67:1 + --> $DIR/c-zst.rs:74:1 | -LL | extern "C" fn pass_zst(_: ()) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | extern "C" fn pass_zst(_: Czst) -> Czst { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/abi/c-zst.sparc-none.stderr b/tests/ui/abi/c-zst.sparc-none.stderr index b77a31cceaec2..8598792e93815 100644 --- a/tests/ui/abi/c-zst.sparc-none.stderr +++ b/tests/ui/abi/c-zst.sparc-none.stderr @@ -2,7 +2,7 @@ error: fn_abi_of(pass_zst) = FnAbi { args: [ ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -20,8 +20,8 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, mode: Indirect { @@ -40,7 +40,7 @@ error: fn_abi_of(pass_zst) = FnAbi { ], ret: ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -58,8 +58,8 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, mode: Ignore, @@ -69,10 +69,10 @@ error: fn_abi_of(pass_zst) = FnAbi { conv: C, can_unwind: false, } - --> $DIR/c-zst.rs:67:1 + --> $DIR/c-zst.rs:74:1 | -LL | extern "C" fn pass_zst(_: ()) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | extern "C" fn pass_zst(_: Czst) -> Czst { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/abi/c-zst.sparc64-linux.stderr b/tests/ui/abi/c-zst.sparc64-linux.stderr index 0d5234a7904ff..8598792e93815 100644 --- a/tests/ui/abi/c-zst.sparc64-linux.stderr +++ b/tests/ui/abi/c-zst.sparc64-linux.stderr @@ -2,7 +2,7 @@ error: fn_abi_of(pass_zst) = FnAbi { args: [ ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -20,16 +20,27 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, - mode: Ignore, + mode: Indirect { + attrs: ArgAttributes { + regular: CapturesAddress | NoAlias | NonNull | NoUndef | NoFree, + arg_ext: None, + pointee_size: Size(0 bytes), + pointee_align: Some( + Align(1 bytes), + ), + }, + address_space: None, + mode: Pointer, + }, }, ], ret: ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -47,8 +58,8 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, mode: Ignore, @@ -58,10 +69,10 @@ error: fn_abi_of(pass_zst) = FnAbi { conv: C, can_unwind: false, } - --> $DIR/c-zst.rs:67:1 + --> $DIR/c-zst.rs:74:1 | -LL | extern "C" fn pass_zst(_: ()) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | extern "C" fn pass_zst(_: Czst) -> Czst { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/abi/c-zst.x86_64-linux.stderr b/tests/ui/abi/c-zst.x86_64-linux.stderr index 0d5234a7904ff..ea764cb2cc71e 100644 --- a/tests/ui/abi/c-zst.x86_64-linux.stderr +++ b/tests/ui/abi/c-zst.x86_64-linux.stderr @@ -2,7 +2,7 @@ error: fn_abi_of(pass_zst) = FnAbi { args: [ ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -20,8 +20,8 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, mode: Ignore, @@ -29,7 +29,7 @@ error: fn_abi_of(pass_zst) = FnAbi { ], ret: ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -47,8 +47,8 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, mode: Ignore, @@ -58,10 +58,10 @@ error: fn_abi_of(pass_zst) = FnAbi { conv: C, can_unwind: false, } - --> $DIR/c-zst.rs:67:1 + --> $DIR/c-zst.rs:74:1 | -LL | extern "C" fn pass_zst(_: ()) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | extern "C" fn pass_zst(_: Czst) -> Czst { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/abi/c-zst.x86_64-pc-windows-gnu.stderr b/tests/ui/abi/c-zst.x86_64-pc-windows-gnu.stderr index 0d5234a7904ff..efc74aab224a9 100644 --- a/tests/ui/abi/c-zst.x86_64-pc-windows-gnu.stderr +++ b/tests/ui/abi/c-zst.x86_64-pc-windows-gnu.stderr @@ -2,7 +2,7 @@ error: fn_abi_of(pass_zst) = FnAbi { args: [ ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -20,16 +20,27 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, }, }, - mode: Ignore, + mode: Indirect { + attrs: ArgAttributes { + regular: CapturesAddress | NoAlias | NonNull | NoUndef | NoFree, + arg_ext: None, + pointee_size: Size(0 bytes), + pointee_align: Some( + Align(1 bytes), + ), + }, + address_space: None, + mode: Pointer, + }, }, ], ret: ArgAbi { layout: TyAndLayout { - ty: (), + ty: Czst, layout: Layout { size: Size(0 bytes), align: $SOME_ALIGN, @@ -47,21 +58,32 @@ error: fn_abi_of(pass_zst) = FnAbi { }, max_repr_align: None, unadjusted_abi_align: $SOME_ALIGN, - repr_c: false, - randomization_seed: 0, + repr_c: true, + randomization_seed: $SEED, + }, + }, + mode: Indirect { + attrs: ArgAttributes { + regular: CapturesAddress | NoAlias | NonNull | NoUndef | NoFree, + arg_ext: None, + pointee_size: Size(0 bytes), + pointee_align: Some( + Align(1 bytes), + ), }, + address_space: None, + mode: Pointer, }, - mode: Ignore, }, c_variadic: false, fixed_count: 1, conv: C, can_unwind: false, } - --> $DIR/c-zst.rs:67:1 + --> $DIR/c-zst.rs:74:1 | -LL | extern "C" fn pass_zst(_: ()) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | extern "C" fn pass_zst(_: Czst) -> Czst { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/abi/rust-zst.aarch64-darwin.stderr b/tests/ui/abi/rust-zst.aarch64-darwin.stderr new file mode 100644 index 0000000000000..f4a3338ca287d --- /dev/null +++ b/tests/ui/abi/rust-zst.aarch64-darwin.stderr @@ -0,0 +1,67 @@ +error: fn_abi_of(pass_rust_zst) = FnAbi { + args: [ + ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + ], + ret: ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + c_variadic: false, + fixed_count: 1, + conv: C, + can_unwind: false, + } + --> $DIR/rust-zst.rs:64:1 + | +LL | extern "C" fn pass_rust_zst(_: ()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/abi/rust-zst.powerpc-linux.stderr b/tests/ui/abi/rust-zst.powerpc-linux.stderr new file mode 100644 index 0000000000000..f4a3338ca287d --- /dev/null +++ b/tests/ui/abi/rust-zst.powerpc-linux.stderr @@ -0,0 +1,67 @@ +error: fn_abi_of(pass_rust_zst) = FnAbi { + args: [ + ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + ], + ret: ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + c_variadic: false, + fixed_count: 1, + conv: C, + can_unwind: false, + } + --> $DIR/rust-zst.rs:64:1 + | +LL | extern "C" fn pass_rust_zst(_: ()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/abi/rust-zst.rs b/tests/ui/abi/rust-zst.rs new file mode 100644 index 0000000000000..dd652c7d23e2f --- /dev/null +++ b/tests/ui/abi/rust-zst.rs @@ -0,0 +1,64 @@ +//@ add-minicore +//@ normalize-stderr: "(align|unadjusted_abi_align): Align\([1-8] bytes\)" -> "$1: $$SOME_ALIGN" +/*! +Rust ZSTs are always ignored in the calling convention even when the C ABI +passes zero-sized structs by-ref. + +That means these two function signatures are always compatible: + +``` +extern "C" fn((), i32, i32); +extern "C" fn(i32, (), i32); +``` +*/ + +// +// C ZST IS ZERO-SIZED +// + +//@ revisions: aarch64-darwin +//@[aarch64-darwin] compile-flags: --target aarch64-apple-darwin +//@[aarch64-darwin] needs-llvm-components: aarch64 + +//@ revisions: x86_64-linux +//@[x86_64-linux] compile-flags: --target x86_64-unknown-linux-gnu +//@[x86_64-linux] needs-llvm-components: x86 + +// +// C ZST IS PASS-BY-POINTER +// + +// according to the SRV4 ABI, an aggregate is always passed in registers, +// and it so happens the GCC extension for ZSTs considers them as structs. +//@ revisions: powerpc-linux +//@[powerpc-linux] compile-flags: --target powerpc-unknown-linux-gnu +//@[powerpc-linux] needs-llvm-components: powerpc + +//@ revisions: s390x-linux +//@[s390x-linux] compile-flags: --target s390x-unknown-linux-gnu +//@[s390x-linux] needs-llvm-components: systemz + +//@ revisions: sparc-none sparc-linux sparc64-linux +//@[sparc-none] compile-flags: --target sparc-unknown-none-elf +//@[sparc-none] needs-llvm-components: sparc +//@[sparc-linux] compile-flags: --target sparc-unknown-linux-gnu +//@[sparc-linux] needs-llvm-components: sparc +//@[sparc64-linux] compile-flags: --target sparc64-unknown-linux-gnu +//@[sparc64-linux] needs-llvm-components: sparc + +// The Win64 ABI uses slightly different handling for power-of-2 sizes in the ABI, +// so GCC decided that ZSTs are pass-by-pointer, as `0.is_power_of_two() == false` +//@ revisions: x86_64-pc-windows-gnu +//@[x86_64-pc-windows-gnu] compile-flags: --target x86_64-pc-windows-gnu +//@[x86_64-pc-windows-gnu] needs-llvm-components: x86 +//@ ignore-backends: gcc + +#![feature(no_core, rustc_attrs)] +#![no_core] +#![crate_type = "lib"] + +extern crate minicore; +use minicore::*; + +#[rustc_abi(debug)] +extern "C" fn pass_rust_zst(_: ()) {} //~ ERROR: fn_abi diff --git a/tests/ui/abi/rust-zst.s390x-linux.stderr b/tests/ui/abi/rust-zst.s390x-linux.stderr new file mode 100644 index 0000000000000..f4a3338ca287d --- /dev/null +++ b/tests/ui/abi/rust-zst.s390x-linux.stderr @@ -0,0 +1,67 @@ +error: fn_abi_of(pass_rust_zst) = FnAbi { + args: [ + ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + ], + ret: ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + c_variadic: false, + fixed_count: 1, + conv: C, + can_unwind: false, + } + --> $DIR/rust-zst.rs:64:1 + | +LL | extern "C" fn pass_rust_zst(_: ()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/abi/rust-zst.sparc-linux.stderr b/tests/ui/abi/rust-zst.sparc-linux.stderr new file mode 100644 index 0000000000000..e7b48442c5538 --- /dev/null +++ b/tests/ui/abi/rust-zst.sparc-linux.stderr @@ -0,0 +1,78 @@ +error: fn_abi_of(pass_rust_zst) = FnAbi { + args: [ + ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Indirect { + attrs: ArgAttributes { + regular: CapturesAddress | NoAlias | NonNull | NoUndef | NoFree, + arg_ext: None, + pointee_size: Size(0 bytes), + pointee_align: Some( + Align(1 bytes), + ), + }, + address_space: None, + mode: Pointer, + }, + }, + ], + ret: ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + c_variadic: false, + fixed_count: 1, + conv: C, + can_unwind: false, + } + --> $DIR/rust-zst.rs:64:1 + | +LL | extern "C" fn pass_rust_zst(_: ()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/abi/rust-zst.sparc-none.stderr b/tests/ui/abi/rust-zst.sparc-none.stderr new file mode 100644 index 0000000000000..e7b48442c5538 --- /dev/null +++ b/tests/ui/abi/rust-zst.sparc-none.stderr @@ -0,0 +1,78 @@ +error: fn_abi_of(pass_rust_zst) = FnAbi { + args: [ + ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Indirect { + attrs: ArgAttributes { + regular: CapturesAddress | NoAlias | NonNull | NoUndef | NoFree, + arg_ext: None, + pointee_size: Size(0 bytes), + pointee_align: Some( + Align(1 bytes), + ), + }, + address_space: None, + mode: Pointer, + }, + }, + ], + ret: ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + c_variadic: false, + fixed_count: 1, + conv: C, + can_unwind: false, + } + --> $DIR/rust-zst.rs:64:1 + | +LL | extern "C" fn pass_rust_zst(_: ()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/abi/rust-zst.sparc64-linux.stderr b/tests/ui/abi/rust-zst.sparc64-linux.stderr new file mode 100644 index 0000000000000..f4a3338ca287d --- /dev/null +++ b/tests/ui/abi/rust-zst.sparc64-linux.stderr @@ -0,0 +1,67 @@ +error: fn_abi_of(pass_rust_zst) = FnAbi { + args: [ + ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + ], + ret: ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + c_variadic: false, + fixed_count: 1, + conv: C, + can_unwind: false, + } + --> $DIR/rust-zst.rs:64:1 + | +LL | extern "C" fn pass_rust_zst(_: ()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/abi/rust-zst.x86_64-linux.stderr b/tests/ui/abi/rust-zst.x86_64-linux.stderr new file mode 100644 index 0000000000000..f4a3338ca287d --- /dev/null +++ b/tests/ui/abi/rust-zst.x86_64-linux.stderr @@ -0,0 +1,67 @@ +error: fn_abi_of(pass_rust_zst) = FnAbi { + args: [ + ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + ], + ret: ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + c_variadic: false, + fixed_count: 1, + conv: C, + can_unwind: false, + } + --> $DIR/rust-zst.rs:64:1 + | +LL | extern "C" fn pass_rust_zst(_: ()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/abi/rust-zst.x86_64-pc-windows-gnu.stderr b/tests/ui/abi/rust-zst.x86_64-pc-windows-gnu.stderr new file mode 100644 index 0000000000000..f4a3338ca287d --- /dev/null +++ b/tests/ui/abi/rust-zst.x86_64-pc-windows-gnu.stderr @@ -0,0 +1,67 @@ +error: fn_abi_of(pass_rust_zst) = FnAbi { + args: [ + ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + ], + ret: ArgAbi { + layout: TyAndLayout { + ty: (), + layout: Layout { + size: Size(0 bytes), + align: $SOME_ALIGN, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + in_memory_order: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: $SOME_ALIGN, + repr_c: false, + randomization_seed: 0, + }, + }, + mode: Ignore, + }, + c_variadic: false, + fixed_count: 1, + conv: C, + can_unwind: false, + } + --> $DIR/rust-zst.rs:64:1 + | +LL | extern "C" fn pass_rust_zst(_: ()) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + From 75722d9ec52008deb92e3c46a3562297d44dd8d6 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:15:02 +0100 Subject: [PATCH 32/39] Fix Rust ZST ABI for SPARC --- compiler/rustc_target/src/callconv/sparc.rs | 2 +- tests/ui/abi/rust-zst.sparc-linux.stderr | 13 +------------ tests/ui/abi/rust-zst.sparc-none.stderr | 13 +------------ 3 files changed, 3 insertions(+), 25 deletions(-) diff --git a/compiler/rustc_target/src/callconv/sparc.rs b/compiler/rustc_target/src/callconv/sparc.rs index d367efaf746f0..daefd5e10d92b 100644 --- a/compiler/rustc_target/src/callconv/sparc.rs +++ b/compiler/rustc_target/src/callconv/sparc.rs @@ -78,7 +78,7 @@ where for arg in fn_abi.args.iter_mut() { if arg.is_ignore() { - if arg.layout.is_zst() { + if arg.layout.is_zst() && arg.layout.is_repr_c() { arg.make_indirect_from_ignore(); } continue; diff --git a/tests/ui/abi/rust-zst.sparc-linux.stderr b/tests/ui/abi/rust-zst.sparc-linux.stderr index e7b48442c5538..f4a3338ca287d 100644 --- a/tests/ui/abi/rust-zst.sparc-linux.stderr +++ b/tests/ui/abi/rust-zst.sparc-linux.stderr @@ -24,18 +24,7 @@ error: fn_abi_of(pass_rust_zst) = FnAbi { randomization_seed: 0, }, }, - mode: Indirect { - attrs: ArgAttributes { - regular: CapturesAddress | NoAlias | NonNull | NoUndef | NoFree, - arg_ext: None, - pointee_size: Size(0 bytes), - pointee_align: Some( - Align(1 bytes), - ), - }, - address_space: None, - mode: Pointer, - }, + mode: Ignore, }, ], ret: ArgAbi { diff --git a/tests/ui/abi/rust-zst.sparc-none.stderr b/tests/ui/abi/rust-zst.sparc-none.stderr index e7b48442c5538..f4a3338ca287d 100644 --- a/tests/ui/abi/rust-zst.sparc-none.stderr +++ b/tests/ui/abi/rust-zst.sparc-none.stderr @@ -24,18 +24,7 @@ error: fn_abi_of(pass_rust_zst) = FnAbi { randomization_seed: 0, }, }, - mode: Indirect { - attrs: ArgAttributes { - regular: CapturesAddress | NoAlias | NonNull | NoUndef | NoFree, - arg_ext: None, - pointee_size: Size(0 bytes), - pointee_align: Some( - Align(1 bytes), - ), - }, - address_space: None, - mode: Pointer, - }, + mode: Ignore, }, ], ret: ArgAbi { From 5543825acaa69161fe881b5bc02c5ebd45797b46 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Mon, 26 Oct 2026 16:47:10 -0500 Subject: [PATCH 33/39] std: Enable `is_mips*_feature_detected` for MIPS release 6 We have four MIPS-like arches, not just the two. --- library/std_detect/src/detect/arch/mips.rs | 2 +- library/std_detect/src/detect/arch/mips64.rs | 2 +- library/std_detect/src/detect/arch/mod.rs | 4 ++-- tests/ui/std/is_arch_feature_detected.AARCH64.stderr | 2 +- tests/ui/std/is_arch_feature_detected.X86.stderr | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/library/std_detect/src/detect/arch/mips.rs b/library/std_detect/src/detect/arch/mips.rs index 9e1960eb96da5..e3388dbcd768e 100644 --- a/library/std_detect/src/detect/arch/mips.rs +++ b/library/std_detect/src/detect/arch/mips.rs @@ -2,7 +2,7 @@ features! { @TARGET: mips; - @CFG: target_arch = "mips"; + @CFG: any(target_arch = "mips", target_arch = "mips32r6"); @MACRO_NAME: is_mips_feature_detected; @MACRO_ATTRS: /// Check for the presence of a CPU feature at runtime. diff --git a/library/std_detect/src/detect/arch/mips64.rs b/library/std_detect/src/detect/arch/mips64.rs index 2bb44ba6e2b39..55477b98c26f8 100644 --- a/library/std_detect/src/detect/arch/mips64.rs +++ b/library/std_detect/src/detect/arch/mips64.rs @@ -2,7 +2,7 @@ features! { @TARGET: mips64; - @CFG: target_arch = "mips64"; + @CFG: any(target_arch = "mips64", target_arch = "mips64r6"); @MACRO_NAME: is_mips64_feature_detected; @MACRO_ATTRS: /// Check for the presence of a CPU feature at runtime. diff --git a/library/std_detect/src/detect/arch/mod.rs b/library/std_detect/src/detect/arch/mod.rs index 2c0b464e32beb..30cb74bf0d2d2 100644 --- a/library/std_detect/src/detect/arch/mod.rs +++ b/library/std_detect/src/detect/arch/mod.rs @@ -41,11 +41,11 @@ cfg_select! { pub use powerpc::__is_feature_detected; pub(crate) use powerpc::Feature; } - target_arch = "mips" => { + any(target_arch = "mips", target_arch = "mips32r6") => { pub use mips::__is_feature_detected; pub(crate) use mips::Feature; } - target_arch = "mips64" => { + any(target_arch = "mips64", target_arch = "mips64r6") => { pub use mips64::__is_feature_detected; pub(crate) use mips64::Feature; } diff --git a/tests/ui/std/is_arch_feature_detected.AARCH64.stderr b/tests/ui/std/is_arch_feature_detected.AARCH64.stderr index d5452993d2573..3b5f035e70629 100644 --- a/tests/ui/std/is_arch_feature_detected.AARCH64.stderr +++ b/tests/ui/std/is_arch_feature_detected.AARCH64.stderr @@ -54,7 +54,7 @@ LL | let _ = arch::is_mips_feature_detected!("msa"); error: This macro cannot be used on the current target. You can prevent it from being used in other architectures by guarding it behind - a `cfg(target_arch = "mips")`. + a `cfg(any(target_arch = "mips", target_arch = "mips32r6"))`. --> $DIR/is_arch_feature_detected.rs:41:13 | LL | let _ = arch::is_mips_feature_detected!("msa"); diff --git a/tests/ui/std/is_arch_feature_detected.X86.stderr b/tests/ui/std/is_arch_feature_detected.X86.stderr index 50105408bf422..a2f1216db4a1a 100644 --- a/tests/ui/std/is_arch_feature_detected.X86.stderr +++ b/tests/ui/std/is_arch_feature_detected.X86.stderr @@ -44,7 +44,7 @@ LL | let _ = arch::is_mips_feature_detected!("msa"); error: This macro cannot be used on the current target. You can prevent it from being used in other architectures by guarding it behind - a `cfg(target_arch = "mips")`. + a `cfg(any(target_arch = "mips", target_arch = "mips32r6"))`. --> $DIR/is_arch_feature_detected.rs:41:13 | LL | let _ = arch::is_mips_feature_detected!("msa"); From 78c5cdd4a2b08dcd19110697ab4567cd07484fdd Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Mon, 26 Oct 2026 16:47:10 -0500 Subject: [PATCH 34/39] std: Combine `is_mips64_feature_detected` into `is_mips_feature_detected` All other architecture families currently use a single macro for both 32- and 64-bit versions. Do the same for MIPS. --- library/std/src/lib.rs | 4 ++-- library/std_detect/src/detect/arch/mips.rs | 7 ++++++- library/std_detect/src/detect/arch/mips64.rs | 15 --------------- library/std_detect/src/detect/arch/mod.rs | 13 ++++++------- library/std_detect/src/lib.rs | 1 - library/stdarch/crates/simd-test-macro/src/lib.rs | 10 ++++++---- .../std/is_arch_feature_detected.AARCH64.stderr | 3 ++- tests/ui/std/is_arch_feature_detected.X86.stderr | 3 ++- 8 files changed, 24 insertions(+), 32 deletions(-) delete mode 100644 library/std_detect/src/detect/arch/mips64.rs diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index a3df4dcd559e3..192f1931fb69d 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -712,6 +712,8 @@ pub mod arch { pub use std_detect::is_arm_feature_detected; #[stable(feature = "stdarch_loongarch_feature", since = "1.89.0")] pub use std_detect::is_loongarch_feature_detected; + #[unstable(feature = "stdarch_mips_feature_detection", issue = "111188")] + pub use std_detect::is_mips_feature_detected; #[unstable(feature = "stdarch_powerpc_feature_detection", issue = "111191")] pub use std_detect::is_powerpc_feature_detected; #[stable(feature = "riscv_ratified", since = "1.78.0")] @@ -720,8 +722,6 @@ pub mod arch { pub use std_detect::is_s390x_feature_detected; #[stable(feature = "simd_x86", since = "1.27.0")] pub use std_detect::is_x86_feature_detected; - #[unstable(feature = "stdarch_mips_feature_detection", issue = "111188")] - pub use std_detect::{is_mips_feature_detected, is_mips64_feature_detected}; } // This was stabilized in the crate root so we have to keep it there. diff --git a/library/std_detect/src/detect/arch/mips.rs b/library/std_detect/src/detect/arch/mips.rs index e3388dbcd768e..17435c9d8f50f 100644 --- a/library/std_detect/src/detect/arch/mips.rs +++ b/library/std_detect/src/detect/arch/mips.rs @@ -2,7 +2,12 @@ features! { @TARGET: mips; - @CFG: any(target_arch = "mips", target_arch = "mips32r6"); + @CFG: any( + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6" + ); @MACRO_NAME: is_mips_feature_detected; @MACRO_ATTRS: /// Check for the presence of a CPU feature at runtime. diff --git a/library/std_detect/src/detect/arch/mips64.rs b/library/std_detect/src/detect/arch/mips64.rs deleted file mode 100644 index 55477b98c26f8..0000000000000 --- a/library/std_detect/src/detect/arch/mips64.rs +++ /dev/null @@ -1,15 +0,0 @@ -//! Run-time feature detection on MIPS64. - -features! { - @TARGET: mips64; - @CFG: any(target_arch = "mips64", target_arch = "mips64r6"); - @MACRO_NAME: is_mips64_feature_detected; - @MACRO_ATTRS: - /// Check for the presence of a CPU feature at runtime. - /// - /// When the feature is known to be enabled at compile time (e.g. via `-Ctarget-feature`) - /// the macro expands to `true`. - #[unstable(feature = "stdarch_mips_feature_detection", issue = "111188")] - @FEATURE: #[unstable(feature = "stdarch_mips_feature_detection", issue = "111188")] msa: "msa"; - /// MIPS SIMD Architecture (MSA) -} diff --git a/library/std_detect/src/detect/arch/mod.rs b/library/std_detect/src/detect/arch/mod.rs index 30cb74bf0d2d2..7e21f2986e6a4 100644 --- a/library/std_detect/src/detect/arch/mod.rs +++ b/library/std_detect/src/detect/arch/mod.rs @@ -14,8 +14,6 @@ mod powerpc; #[macro_use] mod mips; #[macro_use] -mod mips64; -#[macro_use] mod loongarch; #[macro_use] mod s390x; @@ -41,14 +39,15 @@ cfg_select! { pub use powerpc::__is_feature_detected; pub(crate) use powerpc::Feature; } - any(target_arch = "mips", target_arch = "mips32r6") => { + any( + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6" + ) => { pub use mips::__is_feature_detected; pub(crate) use mips::Feature; } - any(target_arch = "mips64", target_arch = "mips64r6") => { - pub use mips64::__is_feature_detected; - pub(crate) use mips64::Feature; - } any(target_arch = "loongarch32", target_arch = "loongarch64") => { pub use loongarch::__is_feature_detected; pub(crate) use loongarch::Feature; diff --git a/library/std_detect/src/lib.rs b/library/std_detect/src/lib.rs index d5805875ad9d6..fd76ed55bc056 100644 --- a/library/std_detect/src/lib.rs +++ b/library/std_detect/src/lib.rs @@ -8,7 +8,6 @@ //! * `aarch64`: [`is_aarch64_feature_detected`] //! * `riscv`: [`is_riscv_feature_detected`] //! * `mips`: [`is_mips_feature_detected`] -//! * `mips64`: [`is_mips64_feature_detected`] //! * `powerpc`: [`is_powerpc_feature_detected`] //! * `loongarch`: [`is_loongarch_feature_detected`] //! * `s390x`: [`is_s390x_feature_detected`] diff --git a/library/stdarch/crates/simd-test-macro/src/lib.rs b/library/stdarch/crates/simd-test-macro/src/lib.rs index ee11fb5c0664b..286b36d3dd249 100644 --- a/library/stdarch/crates/simd-test-macro/src/lib.rs +++ b/library/stdarch/crates/simd-test-macro/src/lib.rs @@ -140,12 +140,14 @@ pub fn simd_test( target_arch = "s390x" => { use std::arch::is_s390x_feature_detected as test_macro; } - any(target_arch = "mips", target_arch = "mips32r6") => { + any( + target_arch = "mips", + target_arch = "mips32r6" + target_arch = "mips64", + target_arch = "mips64r6", + ) => { use std::arch::is_mips_feature_detected as test_macro; } - any(target_arch = "mips64", target_arch = "mips64r6") => { - use std::arch::is_mips64_feature_detected as test_macro; - } _ => compile_error!("unknown target; need to update simd-test-macro"), } diff --git a/tests/ui/std/is_arch_feature_detected.AARCH64.stderr b/tests/ui/std/is_arch_feature_detected.AARCH64.stderr index 3b5f035e70629..8dc6ff24c0b62 100644 --- a/tests/ui/std/is_arch_feature_detected.AARCH64.stderr +++ b/tests/ui/std/is_arch_feature_detected.AARCH64.stderr @@ -54,7 +54,8 @@ LL | let _ = arch::is_mips_feature_detected!("msa"); error: This macro cannot be used on the current target. You can prevent it from being used in other architectures by guarding it behind - a `cfg(any(target_arch = "mips", target_arch = "mips32r6"))`. + a `cfg(any(target_arch = "mips", target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6"))`. --> $DIR/is_arch_feature_detected.rs:41:13 | LL | let _ = arch::is_mips_feature_detected!("msa"); diff --git a/tests/ui/std/is_arch_feature_detected.X86.stderr b/tests/ui/std/is_arch_feature_detected.X86.stderr index a2f1216db4a1a..319b15874d4c2 100644 --- a/tests/ui/std/is_arch_feature_detected.X86.stderr +++ b/tests/ui/std/is_arch_feature_detected.X86.stderr @@ -44,7 +44,8 @@ LL | let _ = arch::is_mips_feature_detected!("msa"); error: This macro cannot be used on the current target. You can prevent it from being used in other architectures by guarding it behind - a `cfg(any(target_arch = "mips", target_arch = "mips32r6"))`. + a `cfg(any(target_arch = "mips", target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6"))`. --> $DIR/is_arch_feature_detected.rs:41:13 | LL | let _ = arch::is_mips_feature_detected!("msa"); From 92defb8ec1ffac3f1b31c28a96579c3ce1f8def4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandra=20Gonz=C3=A1lez?= Date: Wed, 4 Nov 2026 14:33:07 +0000 Subject: [PATCH 35/39] Move metadata emitting from Linker into finish_and_emit_metadata. --- compiler/rustc_driver_impl/src/lib.rs | 4 ++-- compiler/rustc_interface/src/passes.rs | 18 ++++++++++-------- compiler/rustc_interface/src/queries.rs | 3 ++- tests/ui-fulldeps/run-compiler-twice.rs | 3 ++- 4 files changed, 16 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 958e42cda583a..503812ffba289 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -335,9 +335,9 @@ pub fn compiler_entrypoint(at_args: &[String], callbacks: &mut (dyn Callbacks + } } - passes::finish_and_emit_metadata(tcx); + let metadata = passes::finish_and_emit_metadata(tcx); - let linker = Linker::codegen_and_build_linker(tcx, codegen_backend); + let linker = Linker::codegen_and_build_linker(tcx, codegen_backend, metadata); if let Some(metrics_dir) = &sess.opts.unstable_opts.metrics_dir { dump_feature_usage_metrics(tcx, metrics_dir); diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 5cd62288503bd..24c383fdf1210 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -895,13 +895,20 @@ pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) { } } -pub fn finish_and_emit_metadata<'tcx>(tcx: TyCtxt<'tcx>) { +pub fn finish_and_emit_metadata<'tcx>(tcx: TyCtxt<'tcx>) -> EncodedMetadata { // Hook for tests. if let Some((def_id, _)) = tcx.entry_fn(()) && find_attr!(tcx, def_id, RustcDelayedBugFromInsideQuery) { tcx.ensure_ok().trigger_delayed_bug(def_id); } + + let metadata = match rustc_metadata::fs::encode_and_write_metadata(tcx) { + Ok(metadata) => metadata, + Err(guar) => guar.raise_fatal(), + }; + + metadata } pub static DEFAULT_QUERY_PROVIDERS: LazyLock = LazyLock::new(|| { @@ -1303,7 +1310,7 @@ fn analysis(tcx: TyCtxt<'_>, (): ()) { pub(crate) fn start_codegen<'tcx>( codegen_backend: &dyn CodegenBackend, tcx: TyCtxt<'tcx>, -) -> (Box, CrateInfo, EncodedMetadata) { +) -> (Box, CrateInfo) { tcx.sess.timings.start_section(tcx.sess.dcx(), TimingSection::Codegen); // Don't run this test assertions when not doing codegen. Compiletest tries to build // build-fail tests in check mode first and expects it to not give an error in that case. @@ -1320,11 +1327,6 @@ pub(crate) fn start_codegen<'tcx>( info!("Pre-codegen\n{:?}", tcx.debug_stats()); - let metadata = match rustc_metadata::fs::encode_and_write_metadata(tcx) { - Ok(metadata) => metadata, - Err(guar) => guar.raise_fatal(), - }; - let is_host_metadata = tcx .sess .opts @@ -1361,7 +1363,7 @@ pub(crate) fn start_codegen<'tcx>( let crate_info = CrateInfo::new(tcx, codegen_backend.target_cpu(tcx.sess)); - (codegen, crate_info, metadata) + (codegen, crate_info) } /// Compute and validate the crate name. diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index 94cc1484586c8..05b4810160ce3 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -29,8 +29,9 @@ impl Linker { pub fn codegen_and_build_linker( tcx: TyCtxt<'_>, codegen_backend: &dyn CodegenBackend, + metadata: EncodedMetadata, ) -> Linker { - let (ongoing_codegen, crate_info, metadata) = passes::start_codegen(codegen_backend, tcx); + let (ongoing_codegen, crate_info) = passes::start_codegen(codegen_backend, tcx); Linker { dep_graph: tcx.dep_graph.clone(), diff --git a/tests/ui-fulldeps/run-compiler-twice.rs b/tests/ui-fulldeps/run-compiler-twice.rs index ae0f41a205bf4..85e370769517d 100644 --- a/tests/ui-fulldeps/run-compiler-twice.rs +++ b/tests/ui-fulldeps/run-compiler-twice.rs @@ -79,7 +79,8 @@ fn compile(code: String, output: PathBuf, sysroot: Sysroot, linker: Option<&Path let (linker, incr_comp_session) = rustc_interface::create_and_enter_global_ctxt(&compiler, krate, |tcx| { let _ = tcx.analysis(()); - Linker::codegen_and_build_linker(tcx, &*compiler.codegen_backend) + let metadata = rustc_interface::passes::finish_and_emit_metadata(tcx); + Linker::codegen_and_build_linker(tcx, &*compiler.codegen_backend, metadata) }); linker.link(&compiler.sess, incr_comp_session, &*compiler.codegen_backend); }); From c7577d3452810c553e2377d9c9b9eb2a9ce9148d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandra=20Gonz=C3=A1lez?= Date: Wed, 4 Nov 2026 14:33:31 +0000 Subject: [PATCH 36/39] Move delayed-error checking into `compiler_entrypoint` --- compiler/rustc_driver_impl/src/lib.rs | 7 +++++++ compiler/rustc_interface/src/passes.rs | 7 ------- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 503812ffba289..a2b6949a614b4 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -337,6 +337,13 @@ pub fn compiler_entrypoint(at_args: &[String], callbacks: &mut (dyn Callbacks + let metadata = passes::finish_and_emit_metadata(tcx); + // Don't do code generation if there were any errors. Likewise if + // there were any delayed bugs, because codegen will likely cause + // more ICEs, obscuring the original problem. + if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() { + guar.raise_fatal(); + } + let linker = Linker::codegen_and_build_linker(tcx, codegen_backend, metadata); if let Some(metrics_dir) = &sess.opts.unstable_opts.metrics_dir { diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 24c383fdf1210..a65ad928a1b9d 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -1318,13 +1318,6 @@ pub(crate) fn start_codegen<'tcx>( rustc_symbol_mangling::test::dump_symbol_names_and_def_paths(tcx); } - // Don't do code generation if there were any errors. Likewise if - // there were any delayed bugs, because codegen will likely cause - // more ICEs, obscuring the original problem. - if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() { - guar.raise_fatal(); - } - info!("Pre-codegen\n{:?}", tcx.debug_stats()); let is_host_metadata = tcx From 278b0478e09eacc49ea0bb0a33148a5d13374dc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandra=20Gonz=C3=A1lez?= Date: Wed, 4 Nov 2026 15:02:21 +0000 Subject: [PATCH 37/39] Raise abort-on-error --- compiler/rustc_interface/src/queries.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index 05b4810160ce3..b0d87a9684f8b 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -68,6 +68,11 @@ impl Linker { } }); + // Backends could raise an error, do not continue if that's the case. + if let Some(guar) = sess.dcx().has_errors_or_delayed_bugs() { + guar.raise_fatal(); + } + sess.timings.end_section(sess.dcx(), TimingSection::Codegen); if sess.opts.incremental.is_some() @@ -82,10 +87,6 @@ impl Linker { work_products.insert(id, product); } - if let Some(guar) = sess.dcx().has_errors_or_delayed_bugs() { - guar.raise_fatal(); - } - let _timer = sess.timer("link"); sess.time("serialize_work_products", || { From f1dd4c5d887a90be77d0b16ae11142a88fe4ae20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandra=20Gonz=C3=A1lez?= Date: Thu, 5 Nov 2026 19:23:05 +0000 Subject: [PATCH 38/39] Remove `OutputType::Metadata` handling by `link_binary` --- compiler/rustc_codegen_ssa/src/back/link.rs | 17 ++++++----------- compiler/rustc_interface/src/queries.rs | 7 +------ 2 files changed, 7 insertions(+), 17 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 622ac2a905d70..0fee34a7797c5 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -310,23 +310,18 @@ pub fn link_binary( codegen_backend: &'static str, ) { let _timer = sess.timer("link_binary"); - let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata); let mut tempfiles_for_stdout_output: Vec = Vec::new(); let mut rmeta_link_cache = RmetaLinkCache::default(); - if outputs.outputs.should_link() { - sess.time("check_externally_implementable_item_linkage", || { - check_externally_implementable_item_linkage(sess, &crate_info); - }); - sess.dcx().abort_if_errors(); - } + sess.time("check_externally_implementable_item_linkage", || { + check_externally_implementable_item_linkage(sess, &crate_info); + }); + + sess.dcx().abort_if_errors(); for &crate_type in &crate_info.crate_types { // Ignore executable crates if we have -Z no-codegen, as they will error. - if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen()) - && !output_metadata - && crate_type == CrateType::Executable - { + if sess.opts.unstable_opts.no_codegen && crate_type == CrateType::Executable { continue; } diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index b0d87a9684f8b..89e22b1c0c3b6 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -117,12 +117,7 @@ impl Linker { return; } - if !sess - .opts - .output_types - .keys() - .any(|&i| i == OutputType::Exe || i == OutputType::Metadata) - { + if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe) { return; } From a750f1d42b03408f34f18111ec1713b6c744b76c Mon Sep 17 00:00:00 2001 From: Jakub Chlanda Date: Mon, 16 Nov 2026 14:18:59 +0000 Subject: [PATCH 39/39] [PAC] Disable rust-tail-cc for pauthtest --- tests/ui/abi/rust-tail-cc.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/ui/abi/rust-tail-cc.rs b/tests/ui/abi/rust-tail-cc.rs index aba5d0d695647..350d88d259bc9 100644 --- a/tests/ui/abi/rust-tail-cc.rs +++ b/tests/ui/abi/rust-tail-cc.rs @@ -6,6 +6,10 @@ //@ needs-unwind //@ ignore-backends: gcc +// FIXME(jchlanda): remove the ignore below when https://github.com/llvm/llvm-project/pull/221009 is +// present in-tree +//@ ignore-pauthtest: temporarily ignored until a future LLVM upgrade. + #![feature(rust_tail_cc)] struct CrateOf<'a> {