From 44b2e6c07d96112a4c2229638f5e73a3f078136f Mon Sep 17 00:00:00 2001 From: Caleb Zulawski Date: Sat, 23 Sep 2023 22:51:43 -0400 Subject: [PATCH 01/15] Stabilize target_feature_11 --- .../rustc_codegen_ssa/src/codegen_attrs.rs | 27 +++------ compiler/rustc_feature/src/accepted.rs | 2 + compiler/rustc_feature/src/unstable.rs | 2 - library/core/src/lib.rs | 1 - .../closure-inherit-target-feature.rs | 1 - .../codegen/target-feature-inline-closure.rs | 1 - tests/mir-opt/inline/inline_compatibility.rs | 1 - tests/ui/asm/x86_64/issue-89875.rs | 2 - .../fn-exception-target-features.rs | 9 ++- .../fn-exception-target-features.stderr | 4 +- .../start_lang_item_with_target_feature.rs | 2 +- .../panic-handler-with-target-feature.rs | 1 - .../panic-handler-with-target-feature.stderr | 2 +- .../rfc-2396-target_feature-11/check-pass.rs | 2 - .../closures-inherit-target_feature.rs | 2 - .../feature-gate-target_feature_11.rs | 6 -- .../feature-gate-target_feature_11.stderr | 15 ----- .../rfcs/rfc-2396-target_feature-11/fn-ptr.rs | 2 - .../rfc-2396-target_feature-11/fn-ptr.stderr | 4 +- .../rfc-2396-target_feature-11/fn-traits.rs | 2 - .../fn-traits.stderr | 28 ++++----- .../issue-108645-target-feature-on-main.rs | 2 - ...issue-108645-target-feature-on-main.stderr | 2 +- .../issue-108655-inline-always-closure.rs | 2 - .../rfc-2396-target_feature-11/issue-99876.rs | 2 - .../return-fn-ptr.rs | 2 - .../rfc-2396-target_feature-11/safe-calls.rs | 2 - .../safe-calls.stderr | 24 ++++---- .../rfc-2396-target_feature-11/trait-impl.rs | 2 - .../trait-impl.stderr | 8 +-- tests/ui/simd-abi-checks.rs | 2 +- tests/ui/target-feature/implied-features.rs | 1 - tests/ui/target-feature/invalid-attribute.rs | 17 ++---- .../target-feature/invalid-attribute.stderr | 60 +++++++------------ 34 files changed, 77 insertions(+), 165 deletions(-) delete mode 100644 tests/ui/rfcs/rfc-2396-target_feature-11/feature-gate-target_feature_11.rs delete mode 100644 tests/ui/rfcs/rfc-2396-target_feature-11/feature-gate-target_feature_11.stderr diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index a0bc2d4ea48f1..b9e859b5d1a63 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -260,10 +260,9 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { if safe_target_features { if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc { // The `#[target_feature]` attribute is allowed on - // WebAssembly targets on all functions, including safe - // ones. Other targets require that `#[target_feature]` is - // only applied to unsafe functions (pending the - // `target_feature_11` feature) because on most targets + // WebAssembly targets on all functions. Prior to stabilizing + // the `target_feature_11` feature, `#[target_feature]` was + // only permitted on unsafe functions because on most targets // execution of instructions that are not supported is // considered undefined behavior. For WebAssembly which is a // 100% safe target at execution time it's not possible to @@ -277,17 +276,10 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { // if a target is documenting some wasm-specific code then // it's not spuriously denied. // - // This exception needs to be kept in sync with allowing - // `#[target_feature]` on `main` and `start`. - } else if !tcx.features().target_feature_11() { - feature_err( - &tcx.sess, - sym::target_feature_11, - attr.span, - "`#[target_feature(..)]` can only be applied to `unsafe` functions", - ) - .with_span_label(tcx.def_span(did), "not an `unsafe` function") - .emit(); + // Now that `#[target_feature]` is permitted on safe functions, + // this exception must still exist for allowing the attribute on + // `main`, `start`, and other functions that are not usually + // allowed. } else { check_target_feature_trait_unsafe(tcx, did, attr.span); } @@ -616,10 +608,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { // its parent function, which effectively inherits the features anyway. Boxing this closure // would result in this closure being compiled without the inherited target features, but this // is probably a poor usage of `#[inline(always)]` and easily avoided by not using the attribute. - if tcx.features().target_feature_11() - && tcx.is_closure_like(did.to_def_id()) - && !codegen_fn_attrs.inline.always() - { + if tcx.is_closure_like(did.to_def_id()) && codegen_fn_attrs.inline != InlineAttr::Always { let owner_id = tcx.parent(did.to_def_id()); if tcx.def_kind(owner_id).has_codegen_attrs() { codegen_fn_attrs diff --git a/compiler/rustc_feature/src/accepted.rs b/compiler/rustc_feature/src/accepted.rs index 217a7aeb2d7f7..400844d51539a 100644 --- a/compiler/rustc_feature/src/accepted.rs +++ b/compiler/rustc_feature/src/accepted.rs @@ -389,6 +389,8 @@ declare_features! ( (accepted, struct_variant, "1.0.0", None), /// Allows `#[target_feature(...)]`. (accepted, target_feature, "1.27.0", None), + /// Allows the use of `#[target_feature]` on safe functions. + (accepted, target_feature_11, "CURRENT_RUSTC_VERSION", Some(69098)), /// Allows `fn main()` with return types which implements `Termination` (RFC 1937). (accepted, termination_trait, "1.26.0", Some(43301)), /// Allows `#[test]` functions where the return type implements `Termination` (RFC 1937). diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 1a216ebf117c6..dccc168547965 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -618,8 +618,6 @@ declare_features! ( (unstable, strict_provenance_lints, "1.61.0", Some(130351)), /// Allows string patterns to dereference values to match them. (unstable, string_deref_patterns, "1.67.0", Some(87121)), - /// Allows the use of `#[target_feature]` on safe functions. - (unstable, target_feature_11, "1.45.0", Some(69098)), /// Allows using `#[thread_local]` on `static` items. (unstable, thread_local, "1.0.0", Some(29594)), /// Allows defining `trait X = A + B;` alias items. diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index c18e0405f7293..4216e7e5814e8 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -190,7 +190,6 @@ #![feature(staged_api)] #![feature(stmt_expr_attributes)] #![feature(strict_provenance_lints)] -#![feature(target_feature_11)] #![feature(trait_alias)] #![feature(transparent_unions)] #![feature(try_blocks)] diff --git a/tests/assembly/closure-inherit-target-feature.rs b/tests/assembly/closure-inherit-target-feature.rs index 4692653d91fc6..b629d8769edf2 100644 --- a/tests/assembly/closure-inherit-target-feature.rs +++ b/tests/assembly/closure-inherit-target-feature.rs @@ -4,7 +4,6 @@ // make sure the feature is not enabled at compile-time //@ compile-flags: -C opt-level=3 -C target-feature=-sse4.1 -C llvm-args=-x86-asm-syntax=intel -#![feature(target_feature_11)] #![crate_type = "rlib"] use std::arch::x86_64::{__m128, _mm_blend_ps}; diff --git a/tests/codegen/target-feature-inline-closure.rs b/tests/codegen/target-feature-inline-closure.rs index d973bd93e3166..73bdbc0e1a841 100644 --- a/tests/codegen/target-feature-inline-closure.rs +++ b/tests/codegen/target-feature-inline-closure.rs @@ -3,7 +3,6 @@ //@ compile-flags: -Copt-level=3 -Ctarget-cpu=x86-64 #![crate_type = "lib"] -#![feature(target_feature_11)] #[cfg(target_arch = "x86_64")] use std::arch::x86_64::*; diff --git a/tests/mir-opt/inline/inline_compatibility.rs b/tests/mir-opt/inline/inline_compatibility.rs index 13f28aaacd6a7..1bb102ccda58a 100644 --- a/tests/mir-opt/inline/inline_compatibility.rs +++ b/tests/mir-opt/inline/inline_compatibility.rs @@ -4,7 +4,6 @@ #![crate_type = "lib"] #![feature(no_sanitize)] -#![feature(target_feature_11)] #![feature(c_variadic)] #[inline] diff --git a/tests/ui/asm/x86_64/issue-89875.rs b/tests/ui/asm/x86_64/issue-89875.rs index af940f05fead7..0252859cff0a2 100644 --- a/tests/ui/asm/x86_64/issue-89875.rs +++ b/tests/ui/asm/x86_64/issue-89875.rs @@ -2,8 +2,6 @@ //@ needs-asm-support //@ only-x86_64 -#![feature(target_feature_11)] - use std::arch::asm; #[target_feature(enable = "avx")] diff --git a/tests/ui/async-await/async-closures/fn-exception-target-features.rs b/tests/ui/async-await/async-closures/fn-exception-target-features.rs index 82fc776fd2c72..66cc413977032 100644 --- a/tests/ui/async-await/async-closures/fn-exception-target-features.rs +++ b/tests/ui/async-await/async-closures/fn-exception-target-features.rs @@ -1,14 +1,13 @@ //@ edition: 2021 //@ only-x86_64 -#![feature(target_feature_11)] -// `target_feature_11` just to test safe functions w/ target features. - -use std::pin::Pin; use std::future::Future; +use std::pin::Pin; #[target_feature(enable = "sse2")] -fn target_feature() -> Pin + 'static>> { todo!() } +fn target_feature() -> Pin + 'static>> { + todo!() +} fn test(f: impl AsyncFn()) {} diff --git a/tests/ui/async-await/async-closures/fn-exception-target-features.stderr b/tests/ui/async-await/async-closures/fn-exception-target-features.stderr index 37977b45250ff..f0846bfdb1250 100644 --- a/tests/ui/async-await/async-closures/fn-exception-target-features.stderr +++ b/tests/ui/async-await/async-closures/fn-exception-target-features.stderr @@ -1,5 +1,5 @@ error[E0277]: the trait bound `#[target_features] fn() -> Pin + 'static)>> {target_feature}: AsyncFn()` is not satisfied - --> $DIR/fn-exception-target-features.rs:16:10 + --> $DIR/fn-exception-target-features.rs:15:10 | LL | test(target_feature); | ---- ^^^^^^^^^^^^^^ unsatisfied trait bound @@ -8,7 +8,7 @@ LL | test(target_feature); | = help: the trait `AsyncFn()` is not implemented for fn item `#[target_features] fn() -> Pin + 'static)>> {target_feature}` note: required by a bound in `test` - --> $DIR/fn-exception-target-features.rs:13:17 + --> $DIR/fn-exception-target-features.rs:12:17 | LL | fn test(f: impl AsyncFn()) {} | ^^^^^^^^^ required by this bound in `test` diff --git a/tests/ui/lang-items/start_lang_item_with_target_feature.rs b/tests/ui/lang-items/start_lang_item_with_target_feature.rs index eb712ba409259..18cd4c9704056 100644 --- a/tests/ui/lang-items/start_lang_item_with_target_feature.rs +++ b/tests/ui/lang-items/start_lang_item_with_target_feature.rs @@ -1,7 +1,7 @@ //@ only-x86_64 //@ check-fail -#![feature(lang_items, no_core, target_feature_11)] +#![feature(lang_items, no_core)] #![no_core] #[lang = "copy"] diff --git a/tests/ui/panic-handler/panic-handler-with-target-feature.rs b/tests/ui/panic-handler/panic-handler-with-target-feature.rs index 8d5ea0703afa5..aec00c637bedb 100644 --- a/tests/ui/panic-handler/panic-handler-with-target-feature.rs +++ b/tests/ui/panic-handler/panic-handler-with-target-feature.rs @@ -1,7 +1,6 @@ //@ compile-flags:-C panic=abort //@ only-x86_64 -#![feature(target_feature_11)] #![no_std] #![no_main] diff --git a/tests/ui/panic-handler/panic-handler-with-target-feature.stderr b/tests/ui/panic-handler/panic-handler-with-target-feature.stderr index cb17da3a4efbe..ddf0ae77a0a1a 100644 --- a/tests/ui/panic-handler/panic-handler-with-target-feature.stderr +++ b/tests/ui/panic-handler/panic-handler-with-target-feature.stderr @@ -1,5 +1,5 @@ error: `#[panic_handler]` function is not allowed to have `#[target_feature]` - --> $DIR/panic-handler-with-target-feature.rs:11:1 + --> $DIR/panic-handler-with-target-feature.rs:10:1 | LL | #[target_feature(enable = "avx2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/check-pass.rs b/tests/ui/rfcs/rfc-2396-target_feature-11/check-pass.rs index 674cf930c0a6a..9279e7a955ed8 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/check-pass.rs +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/check-pass.rs @@ -9,8 +9,6 @@ //@ check-pass //@ only-x86_64 -#![feature(target_feature_11)] - #[target_feature(enable = "sse2")] const fn sse2() {} diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/closures-inherit-target_feature.rs b/tests/ui/rfcs/rfc-2396-target_feature-11/closures-inherit-target_feature.rs index 122ef542e7d63..aecea6314d412 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/closures-inherit-target_feature.rs +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/closures-inherit-target_feature.rs @@ -3,8 +3,6 @@ //@ check-pass //@ only-x86_64 -#![feature(target_feature_11)] - #[target_feature(enable = "avx")] fn also_use_avx() { println!("Hello from AVX") diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/feature-gate-target_feature_11.rs b/tests/ui/rfcs/rfc-2396-target_feature-11/feature-gate-target_feature_11.rs deleted file mode 100644 index 2add6b2e18653..0000000000000 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/feature-gate-target_feature_11.rs +++ /dev/null @@ -1,6 +0,0 @@ -//@ only-x86_64 - -#[target_feature(enable = "sse2")] //~ ERROR can only be applied to `unsafe` functions -fn foo() {} - -fn main() {} diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/feature-gate-target_feature_11.stderr b/tests/ui/rfcs/rfc-2396-target_feature-11/feature-gate-target_feature_11.stderr deleted file mode 100644 index 4f1994d56fd42..0000000000000 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/feature-gate-target_feature_11.stderr +++ /dev/null @@ -1,15 +0,0 @@ -error[E0658]: `#[target_feature(..)]` can only be applied to `unsafe` functions - --> $DIR/feature-gate-target_feature_11.rs:3:1 - | -LL | #[target_feature(enable = "sse2")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -LL | fn foo() {} - | -------- not an `unsafe` function - | - = note: see issue #69098 for more information - = help: add `#![feature(target_feature_11)]` 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: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.rs b/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.rs index d7c17299d061c..43a5a2f16aac1 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.rs +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.rs @@ -1,7 +1,5 @@ //@ only-x86_64 -#![feature(target_feature_11)] - #[target_feature(enable = "avx")] fn foo_avx() {} diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.stderr b/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.stderr index 1228404120a4c..5bfbc236bc4e3 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.stderr +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/fn-ptr.rs:14:21 + --> $DIR/fn-ptr.rs:12:21 | LL | #[target_feature(enable = "avx")] | --------------------------------- `#[target_feature]` added here @@ -14,7 +14,7 @@ LL | let foo: fn() = foo_avx; = note: functions with `#[target_feature]` can only be coerced to `unsafe` function pointers error[E0308]: mismatched types - --> $DIR/fn-ptr.rs:23:21 + --> $DIR/fn-ptr.rs:21:21 | LL | #[target_feature(enable = "sse2")] | ---------------------------------- `#[target_feature]` added here diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/fn-traits.rs b/tests/ui/rfcs/rfc-2396-target_feature-11/fn-traits.rs index c880ef0fe8a0e..82053a12b133f 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/fn-traits.rs +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/fn-traits.rs @@ -1,7 +1,5 @@ //@ only-x86_64 -#![feature(target_feature_11)] - #[target_feature(enable = "avx")] fn foo() {} diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/fn-traits.stderr b/tests/ui/rfcs/rfc-2396-target_feature-11/fn-traits.stderr index efc061eca5f59..1c6e3905abb11 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/fn-traits.stderr +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/fn-traits.stderr @@ -1,5 +1,5 @@ error[E0277]: expected a `Fn()` closure, found `#[target_features] fn() {foo}` - --> $DIR/fn-traits.rs:31:10 + --> $DIR/fn-traits.rs:29:10 | LL | call(foo); | ---- ^^^ expected an `Fn()` closure, found `#[target_features] fn() {foo}` @@ -11,13 +11,13 @@ LL | call(foo); = note: `#[target_feature]` functions do not implement the `Fn` traits = note: try casting the function to a `fn` pointer or wrapping it in a closure note: required by a bound in `call` - --> $DIR/fn-traits.rs:14:17 + --> $DIR/fn-traits.rs:12:17 | LL | fn call(f: impl Fn()) { | ^^^^ required by this bound in `call` error[E0277]: expected a `FnMut()` closure, found `#[target_features] fn() {foo}` - --> $DIR/fn-traits.rs:32:14 + --> $DIR/fn-traits.rs:30:14 | LL | call_mut(foo); | -------- ^^^ expected an `FnMut()` closure, found `#[target_features] fn() {foo}` @@ -29,13 +29,13 @@ LL | call_mut(foo); = note: `#[target_feature]` functions do not implement the `Fn` traits = note: try casting the function to a `fn` pointer or wrapping it in a closure note: required by a bound in `call_mut` - --> $DIR/fn-traits.rs:18:25 + --> $DIR/fn-traits.rs:16:25 | LL | fn call_mut(mut f: impl FnMut()) { | ^^^^^^^ required by this bound in `call_mut` error[E0277]: expected a `FnOnce()` closure, found `#[target_features] fn() {foo}` - --> $DIR/fn-traits.rs:33:15 + --> $DIR/fn-traits.rs:31:15 | LL | call_once(foo); | --------- ^^^ expected an `FnOnce()` closure, found `#[target_features] fn() {foo}` @@ -47,13 +47,13 @@ LL | call_once(foo); = note: `#[target_feature]` functions do not implement the `Fn` traits = note: try casting the function to a `fn` pointer or wrapping it in a closure note: required by a bound in `call_once` - --> $DIR/fn-traits.rs:22:22 + --> $DIR/fn-traits.rs:20:22 | LL | fn call_once(f: impl FnOnce()) { | ^^^^^^^^ required by this bound in `call_once` error[E0277]: expected a `FnOnce(i32)` closure, found `#[target_features] fn(i32) {bar}` - --> $DIR/fn-traits.rs:34:19 + --> $DIR/fn-traits.rs:32:19 | LL | call_once_i32(bar); | ------------- ^^^ expected an `FnOnce(i32)` closure, found `#[target_features] fn(i32) {bar}` @@ -64,13 +64,13 @@ LL | call_once_i32(bar); = note: `#[target_feature]` functions do not implement the `Fn` traits = note: try casting the function to a `fn` pointer or wrapping it in a closure note: required by a bound in `call_once_i32` - --> $DIR/fn-traits.rs:26:26 + --> $DIR/fn-traits.rs:24:26 | LL | fn call_once_i32(f: impl FnOnce(i32)) { | ^^^^^^^^^^^ required by this bound in `call_once_i32` error[E0277]: expected a `Fn()` closure, found `unsafe fn() {foo_unsafe}` - --> $DIR/fn-traits.rs:36:10 + --> $DIR/fn-traits.rs:34:10 | LL | call(foo_unsafe); | ---- ^^^^^^^^^^ call the function in a closure: `|| unsafe { /* code */ }` @@ -83,13 +83,13 @@ LL | call(foo_unsafe); = note: `#[target_feature]` functions do not implement the `Fn` traits = note: try casting the function to a `fn` pointer or wrapping it in a closure note: required by a bound in `call` - --> $DIR/fn-traits.rs:14:17 + --> $DIR/fn-traits.rs:12:17 | LL | fn call(f: impl Fn()) { | ^^^^ required by this bound in `call` error[E0277]: expected a `FnMut()` closure, found `unsafe fn() {foo_unsafe}` - --> $DIR/fn-traits.rs:38:14 + --> $DIR/fn-traits.rs:36:14 | LL | call_mut(foo_unsafe); | -------- ^^^^^^^^^^ call the function in a closure: `|| unsafe { /* code */ }` @@ -102,13 +102,13 @@ LL | call_mut(foo_unsafe); = note: `#[target_feature]` functions do not implement the `Fn` traits = note: try casting the function to a `fn` pointer or wrapping it in a closure note: required by a bound in `call_mut` - --> $DIR/fn-traits.rs:18:25 + --> $DIR/fn-traits.rs:16:25 | LL | fn call_mut(mut f: impl FnMut()) { | ^^^^^^^ required by this bound in `call_mut` error[E0277]: expected a `FnOnce()` closure, found `unsafe fn() {foo_unsafe}` - --> $DIR/fn-traits.rs:40:15 + --> $DIR/fn-traits.rs:38:15 | LL | call_once(foo_unsafe); | --------- ^^^^^^^^^^ call the function in a closure: `|| unsafe { /* code */ }` @@ -121,7 +121,7 @@ LL | call_once(foo_unsafe); = note: `#[target_feature]` functions do not implement the `Fn` traits = note: try casting the function to a `fn` pointer or wrapping it in a closure note: required by a bound in `call_once` - --> $DIR/fn-traits.rs:22:22 + --> $DIR/fn-traits.rs:20:22 | LL | fn call_once(f: impl FnOnce()) { | ^^^^^^^^ required by this bound in `call_once` diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/issue-108645-target-feature-on-main.rs b/tests/ui/rfcs/rfc-2396-target_feature-11/issue-108645-target-feature-on-main.rs index a1c118478677b..6df89ee97ddf8 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/issue-108645-target-feature-on-main.rs +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/issue-108645-target-feature-on-main.rs @@ -1,7 +1,5 @@ //@ only-x86_64 -#![feature(target_feature_11)] - #[target_feature(enable = "avx2")] fn main() {} //~^ ERROR `main` function is not allowed to have `#[target_feature]` diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/issue-108645-target-feature-on-main.stderr b/tests/ui/rfcs/rfc-2396-target_feature-11/issue-108645-target-feature-on-main.stderr index 57ad1cc8d0802..15f99512f1747 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/issue-108645-target-feature-on-main.stderr +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/issue-108645-target-feature-on-main.stderr @@ -1,5 +1,5 @@ error: `main` function is not allowed to have `#[target_feature]` - --> $DIR/issue-108645-target-feature-on-main.rs:6:1 + --> $DIR/issue-108645-target-feature-on-main.rs:4:1 | LL | fn main() {} | ^^^^^^^^^ `main` function is not allowed to have `#[target_feature]` diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/issue-108655-inline-always-closure.rs b/tests/ui/rfcs/rfc-2396-target_feature-11/issue-108655-inline-always-closure.rs index 6bd810b0956d8..bf6dba6702c9e 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/issue-108655-inline-always-closure.rs +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/issue-108655-inline-always-closure.rs @@ -3,8 +3,6 @@ //@ check-pass //@ only-x86_64 -#![feature(target_feature_11)] - #[target_feature(enable = "avx")] pub unsafe fn test() { ({ diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/issue-99876.rs b/tests/ui/rfcs/rfc-2396-target_feature-11/issue-99876.rs index 57dac2e4adb76..141d07876d4ca 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/issue-99876.rs +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/issue-99876.rs @@ -1,7 +1,5 @@ //@ check-pass -#![feature(target_feature_11)] - struct S(T) where [T; (|| {}, 1).1]: Copy; diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/return-fn-ptr.rs b/tests/ui/rfcs/rfc-2396-target_feature-11/return-fn-ptr.rs index b49493d66096d..5b306438fb083 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/return-fn-ptr.rs +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/return-fn-ptr.rs @@ -1,8 +1,6 @@ //@ only-x86_64 //@ run-pass -#![feature(target_feature_11)] - #[target_feature(enable = "sse2")] fn foo() -> bool { true diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/safe-calls.rs b/tests/ui/rfcs/rfc-2396-target_feature-11/safe-calls.rs index fec4e75290fc8..35bf6c110115e 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/safe-calls.rs +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/safe-calls.rs @@ -2,8 +2,6 @@ // Set the base cpu explicitly, in case the default has been changed. //@ compile-flags: -C target-cpu=x86-64 -#![feature(target_feature_11)] - #[target_feature(enable = "sse2")] const fn sse2() {} diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/safe-calls.stderr b/tests/ui/rfcs/rfc-2396-target_feature-11/safe-calls.stderr index 901bf640845dd..ea4626092340b 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/safe-calls.stderr +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/safe-calls.stderr @@ -1,5 +1,5 @@ error[E0133]: call to function `sse2` with `#[target_feature]` is unsafe and requires unsafe function or block - --> $DIR/safe-calls.rs:27:5 + --> $DIR/safe-calls.rs:25:5 | LL | sse2(); | ^^^^^^ call to function with `#[target_feature]` @@ -8,7 +8,7 @@ LL | sse2(); = note: the sse2 target feature being enabled in the build configuration does not remove the requirement to list it in `#[target_feature]` error[E0133]: call to function `avx_bmi2` with `#[target_feature]` is unsafe and requires unsafe function or block - --> $DIR/safe-calls.rs:29:5 + --> $DIR/safe-calls.rs:27:5 | LL | avx_bmi2(); | ^^^^^^^^^^ call to function with `#[target_feature]` @@ -16,7 +16,7 @@ LL | avx_bmi2(); = help: in order for the call to be safe, the context requires the following additional target features: avx and bmi2 error[E0133]: call to function `Quux::avx_bmi2` with `#[target_feature]` is unsafe and requires unsafe function or block - --> $DIR/safe-calls.rs:31:5 + --> $DIR/safe-calls.rs:29:5 | LL | Quux.avx_bmi2(); | ^^^^^^^^^^^^^^^ call to function with `#[target_feature]` @@ -24,7 +24,7 @@ LL | Quux.avx_bmi2(); = help: in order for the call to be safe, the context requires the following additional target features: avx and bmi2 error[E0133]: call to function `avx_bmi2` with `#[target_feature]` is unsafe and requires unsafe function or block - --> $DIR/safe-calls.rs:38:5 + --> $DIR/safe-calls.rs:36:5 | LL | avx_bmi2(); | ^^^^^^^^^^ call to function with `#[target_feature]` @@ -32,7 +32,7 @@ LL | avx_bmi2(); = help: in order for the call to be safe, the context requires the following additional target features: avx and bmi2 error[E0133]: call to function `Quux::avx_bmi2` with `#[target_feature]` is unsafe and requires unsafe function or block - --> $DIR/safe-calls.rs:40:5 + --> $DIR/safe-calls.rs:38:5 | LL | Quux.avx_bmi2(); | ^^^^^^^^^^^^^^^ call to function with `#[target_feature]` @@ -40,7 +40,7 @@ LL | Quux.avx_bmi2(); = help: in order for the call to be safe, the context requires the following additional target features: avx and bmi2 error[E0133]: call to function `avx_bmi2` with `#[target_feature]` is unsafe and requires unsafe function or block - --> $DIR/safe-calls.rs:47:5 + --> $DIR/safe-calls.rs:45:5 | LL | avx_bmi2(); | ^^^^^^^^^^ call to function with `#[target_feature]` @@ -48,7 +48,7 @@ LL | avx_bmi2(); = help: in order for the call to be safe, the context requires the following additional target feature: bmi2 error[E0133]: call to function `Quux::avx_bmi2` with `#[target_feature]` is unsafe and requires unsafe function or block - --> $DIR/safe-calls.rs:49:5 + --> $DIR/safe-calls.rs:47:5 | LL | Quux.avx_bmi2(); | ^^^^^^^^^^^^^^^ call to function with `#[target_feature]` @@ -56,7 +56,7 @@ LL | Quux.avx_bmi2(); = help: in order for the call to be safe, the context requires the following additional target feature: bmi2 error[E0133]: call to function `sse2` with `#[target_feature]` is unsafe and requires unsafe function or block - --> $DIR/safe-calls.rs:61:15 + --> $DIR/safe-calls.rs:59:15 | LL | const _: () = sse2(); | ^^^^^^ call to function with `#[target_feature]` @@ -65,7 +65,7 @@ LL | const _: () = sse2(); = note: the sse2 target feature being enabled in the build configuration does not remove the requirement to list it in `#[target_feature]` error[E0133]: call to function `sse2_and_fxsr` with `#[target_feature]` is unsafe and requires unsafe function or block - --> $DIR/safe-calls.rs:64:15 + --> $DIR/safe-calls.rs:62:15 | LL | const _: () = sse2_and_fxsr(); | ^^^^^^^^^^^^^^^ call to function with `#[target_feature]` @@ -74,7 +74,7 @@ LL | const _: () = sse2_and_fxsr(); = note: the fxsr and sse2 target features being enabled in the build configuration does not remove the requirement to list them in `#[target_feature]` error[E0133]: call to function `sse2` with `#[target_feature]` is unsafe and requires unsafe block - --> $DIR/safe-calls.rs:69:5 + --> $DIR/safe-calls.rs:67:5 | LL | sse2(); | ^^^^^^ call to function with `#[target_feature]` @@ -83,12 +83,12 @@ LL | sse2(); = help: in order for the call to be safe, the context requires the following additional target feature: sse2 = note: the sse2 target feature being enabled in the build configuration does not remove the requirement to list it in `#[target_feature]` note: an unsafe function restricts its caller, but its body is safe by default - --> $DIR/safe-calls.rs:68:1 + --> $DIR/safe-calls.rs:66:1 | LL | unsafe fn needs_unsafe_block() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: the lint level is defined here - --> $DIR/safe-calls.rs:67:8 + --> $DIR/safe-calls.rs:65:8 | LL | #[deny(unsafe_op_in_unsafe_fn)] | ^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/trait-impl.rs b/tests/ui/rfcs/rfc-2396-target_feature-11/trait-impl.rs index a2ac6ff45fccf..bb1dd3b503039 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/trait-impl.rs +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/trait-impl.rs @@ -1,7 +1,5 @@ //@ only-x86_64 -#![feature(target_feature_11)] - trait Foo { fn foo(&self); unsafe fn unsf_foo(&self); diff --git a/tests/ui/rfcs/rfc-2396-target_feature-11/trait-impl.stderr b/tests/ui/rfcs/rfc-2396-target_feature-11/trait-impl.stderr index 1ab1fad64ccf9..f2ef2b2f3b86b 100644 --- a/tests/ui/rfcs/rfc-2396-target_feature-11/trait-impl.stderr +++ b/tests/ui/rfcs/rfc-2396-target_feature-11/trait-impl.stderr @@ -1,5 +1,5 @@ error: `#[target_feature(..)]` cannot be applied to safe trait method - --> $DIR/trait-impl.rs:13:5 + --> $DIR/trait-impl.rs:11:5 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot be applied to safe trait method @@ -8,13 +8,13 @@ LL | fn foo(&self) {} | ------------- not an `unsafe` function error[E0053]: method `foo` has an incompatible type for trait - --> $DIR/trait-impl.rs:15:5 + --> $DIR/trait-impl.rs:13:5 | LL | fn foo(&self) {} | ^^^^^^^^^^^^^ expected safe fn, found unsafe fn | note: type in trait - --> $DIR/trait-impl.rs:6:5 + --> $DIR/trait-impl.rs:4:5 | LL | fn foo(&self); | ^^^^^^^^^^^^^^ @@ -22,7 +22,7 @@ LL | fn foo(&self); found signature `#[target_features] fn(&Bar)` error: `#[target_feature(..)]` cannot be applied to safe trait method - --> $DIR/trait-impl.rs:23:5 + --> $DIR/trait-impl.rs:21:5 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot be applied to safe trait method diff --git a/tests/ui/simd-abi-checks.rs b/tests/ui/simd-abi-checks.rs index c97767b27941e..3a344a1f5f8fb 100644 --- a/tests/ui/simd-abi-checks.rs +++ b/tests/ui/simd-abi-checks.rs @@ -4,7 +4,7 @@ #![feature(avx512_target_feature)] #![feature(portable_simd)] -#![feature(target_feature_11, simd_ffi)] +#![feature(simd_ffi)] #![allow(improper_ctypes_definitions)] use std::arch::x86_64::*; diff --git a/tests/ui/target-feature/implied-features.rs b/tests/ui/target-feature/implied-features.rs index 4fdd843e6c289..d0b5dd3c3fb99 100644 --- a/tests/ui/target-feature/implied-features.rs +++ b/tests/ui/target-feature/implied-features.rs @@ -1,6 +1,5 @@ //@ only-x86_64 //@ build-pass -#![feature(target_feature_11)] #![allow(dead_code)] #[target_feature(enable = "ssse3")] diff --git a/tests/ui/target-feature/invalid-attribute.rs b/tests/ui/target-feature/invalid-attribute.rs index c0f5b6b2fb292..9ef7a686d253d 100644 --- a/tests/ui/target-feature/invalid-attribute.rs +++ b/tests/ui/target-feature/invalid-attribute.rs @@ -28,13 +28,6 @@ extern "Rust" {} //~^ ERROR malformed `target_feature` attribute unsafe fn foo() {} -#[target_feature(enable = "sse2")] -//~^ ERROR `#[target_feature(..)]` can only be applied to `unsafe` functions -//~| NOTE see issue #69098 -//~| NOTE: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -fn bar() {} -//~^ NOTE not an `unsafe` function - #[target_feature(enable = "sse2")] //~^ ERROR attribute should be applied to a function mod another {} @@ -58,7 +51,7 @@ enum Bar {} #[target_feature(enable = "sse2")] //~^ ERROR attribute should be applied to a function union Qux { -//~^ NOTE not a function + //~^ NOTE not a function f1: u16, f2: u16, } @@ -102,9 +95,8 @@ trait Quux { impl Quux for Foo { #[target_feature(enable = "sse2")] - //~^ ERROR `#[target_feature(..)]` can only be applied to `unsafe` functions - //~| NOTE see issue #69098 - //~| NOTE: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + //~^ ERROR `#[target_feature(..)]` cannot be applied to safe trait method + //~| NOTE cannot be applied to safe trait method fn foo() {} //~^ NOTE not an `unsafe` function //~| ERROR: incompatible type for trait @@ -117,9 +109,8 @@ fn main() { //~^ ERROR attribute should be applied to a function unsafe { foo(); - bar(); } - //~^^^^ NOTE not a function + //~^^^ NOTE not a function #[target_feature(enable = "sse2")] //~^ ERROR attribute should be applied to a function diff --git a/tests/ui/target-feature/invalid-attribute.stderr b/tests/ui/target-feature/invalid-attribute.stderr index 10fcf65bb9a83..dc8a53041640e 100644 --- a/tests/ui/target-feature/invalid-attribute.stderr +++ b/tests/ui/target-feature/invalid-attribute.stderr @@ -32,7 +32,7 @@ LL | extern "Rust" {} | ---------------- not a function definition error: attribute should be applied to a function definition - --> $DIR/invalid-attribute.rs:38:1 + --> $DIR/invalid-attribute.rs:31:1 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -41,7 +41,7 @@ LL | mod another {} | -------------- not a function definition error: attribute should be applied to a function definition - --> $DIR/invalid-attribute.rs:43:1 + --> $DIR/invalid-attribute.rs:36:1 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -50,7 +50,7 @@ LL | const FOO: usize = 7; | --------------------- not a function definition error: attribute should be applied to a function definition - --> $DIR/invalid-attribute.rs:48:1 + --> $DIR/invalid-attribute.rs:41:1 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -59,7 +59,7 @@ LL | struct Foo; | ----------- not a function definition error: attribute should be applied to a function definition - --> $DIR/invalid-attribute.rs:53:1 + --> $DIR/invalid-attribute.rs:46:1 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -68,7 +68,7 @@ LL | enum Bar {} | ----------- not a function definition error: attribute should be applied to a function definition - --> $DIR/invalid-attribute.rs:58:1 + --> $DIR/invalid-attribute.rs:51:1 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -81,7 +81,7 @@ LL | | } | |_- not a function definition error: attribute should be applied to a function definition - --> $DIR/invalid-attribute.rs:66:1 + --> $DIR/invalid-attribute.rs:59:1 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -90,7 +90,7 @@ LL | type Uwu = (); | -------------- not a function definition error: attribute should be applied to a function definition - --> $DIR/invalid-attribute.rs:71:1 + --> $DIR/invalid-attribute.rs:64:1 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -99,7 +99,7 @@ LL | trait Baz {} | ------------ not a function definition error: attribute should be applied to a function definition - --> $DIR/invalid-attribute.rs:81:1 + --> $DIR/invalid-attribute.rs:74:1 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -108,7 +108,7 @@ LL | static A: () = (); | ------------------ not a function definition error: attribute should be applied to a function definition - --> $DIR/invalid-attribute.rs:86:1 + --> $DIR/invalid-attribute.rs:79:1 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -117,7 +117,7 @@ LL | impl Quux for u8 {} | ------------------- not a function definition error: attribute should be applied to a function definition - --> $DIR/invalid-attribute.rs:93:1 + --> $DIR/invalid-attribute.rs:86:1 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -126,19 +126,18 @@ LL | impl Foo {} | ----------- not a function definition error: attribute should be applied to a function definition - --> $DIR/invalid-attribute.rs:116:5 + --> $DIR/invalid-attribute.rs:108:5 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | LL | / unsafe { LL | | foo(); -LL | | bar(); LL | | } | |_____- not a function definition error: attribute should be applied to a function definition - --> $DIR/invalid-attribute.rs:124:5 + --> $DIR/invalid-attribute.rs:115:5 | LL | #[target_feature(enable = "sse2")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -164,27 +163,14 @@ error: malformed `target_feature` attribute input LL | #[target_feature(disable = "baz")] | ^^^^^^^^^^^^^^^ help: must be of the form: `enable = ".."` -error[E0658]: `#[target_feature(..)]` can only be applied to `unsafe` functions - --> $DIR/invalid-attribute.rs:31:1 - | -LL | #[target_feature(enable = "sse2")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | fn bar() {} - | -------- not an `unsafe` function - | - = note: see issue #69098 for more information - = help: add `#![feature(target_feature_11)]` 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: cannot use `#[inline(always)]` with `#[target_feature]` - --> $DIR/invalid-attribute.rs:76:1 + --> $DIR/invalid-attribute.rs:69:1 | LL | #[inline(always)] | ^^^^^^^^^^^^^^^^^ error[E0046]: not all trait items implemented, missing: `foo` - --> $DIR/invalid-attribute.rs:88:1 + --> $DIR/invalid-attribute.rs:81:1 | LL | impl Quux for u8 {} | ^^^^^^^^^^^^^^^^ missing `foo` in implementation @@ -192,34 +178,30 @@ LL | impl Quux for u8 {} LL | fn foo(); | --------- `foo` from trait -error[E0658]: `#[target_feature(..)]` can only be applied to `unsafe` functions - --> $DIR/invalid-attribute.rs:104:5 +error: `#[target_feature(..)]` cannot be applied to safe trait method + --> $DIR/invalid-attribute.rs:97:5 | LL | #[target_feature(enable = "sse2")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot be applied to safe trait method ... LL | fn foo() {} | -------- not an `unsafe` function - | - = note: see issue #69098 for more information - = help: add `#![feature(target_feature_11)]` 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[E0053]: method `foo` has an incompatible type for trait - --> $DIR/invalid-attribute.rs:108:5 + --> $DIR/invalid-attribute.rs:100:5 | LL | fn foo() {} | ^^^^^^^^ expected safe fn, found unsafe fn | note: type in trait - --> $DIR/invalid-attribute.rs:99:5 + --> $DIR/invalid-attribute.rs:92:5 | LL | fn foo(); | ^^^^^^^^^ = note: expected signature `fn()` found signature `#[target_features] fn()` -error: aborting due to 24 previous errors +error: aborting due to 23 previous errors -Some errors have detailed explanations: E0046, E0053, E0658. +Some errors have detailed explanations: E0046, E0053. For more information about an error, try `rustc --explain E0046`. From 68ff0f17976721ee59229f72e6f7fe0cae44c8eb Mon Sep 17 00:00:00 2001 From: joboet Date: Fri, 7 Feb 2025 18:34:09 +0100 Subject: [PATCH 02/15] std: replace the `FromInner` implementation for addresses with private conversion functions Having these implementation available crate-wide means that platforms not using sockets for their networking code have to stub out the libc definitions required to support them. This PR moves the conversions to private helper functions that are only available where actually needed. I also fixed the signature of the function converting from a C socket address to a Rust one: taking a reference to a `sockaddr_storage` resulted in unsound usage inside `LookupHost::next`, which could create a reference to a structure smaller than `sockaddr_storage`. Thus I've replaced the argument type with a pointer and made the function `unsafe`. --- library/std/src/net/ip_addr.rs | 29 --- library/std/src/net/socket_addr.rs | 46 +---- library/std/src/os/solid/io.rs | 4 +- library/std/src/sys/net/connection/sgx.rs | 35 ---- library/std/src/sys/net/connection/socket.rs | 188 +++++++++++------- .../src/sys/net/connection/socket/hermit.rs | 10 +- .../src/sys/net/connection/socket/solid.rs | 8 +- .../std/src/sys/net/connection/socket/unix.rs | 11 +- .../src/sys/net/connection/socket/wasip2.rs | 9 +- .../src/sys/net/connection/socket/windows.rs | 23 ++- .../std/src/sys/net/connection/unsupported.rs | 35 ---- library/std/src/sys/net/connection/wasip1.rs | 35 ---- .../std/src/sys/net/connection/xous/mod.rs | 35 ---- 13 files changed, 155 insertions(+), 313 deletions(-) diff --git a/library/std/src/net/ip_addr.rs b/library/std/src/net/ip_addr.rs index 4d673a1d66db6..7262899b3bbbe 100644 --- a/library/std/src/net/ip_addr.rs +++ b/library/std/src/net/ip_addr.rs @@ -8,32 +8,3 @@ pub use core::net::IpAddr; pub use core::net::Ipv6MulticastScope; #[stable(feature = "rust1", since = "1.0.0")] pub use core::net::{Ipv4Addr, Ipv6Addr}; - -use crate::sys::net::netc as c; -use crate::sys_common::{FromInner, IntoInner}; - -impl IntoInner for Ipv4Addr { - #[inline] - fn into_inner(self) -> c::in_addr { - // `s_addr` is stored as BE on all machines and the array is in BE order. - // So the native endian conversion method is used so that it's never swapped. - c::in_addr { s_addr: u32::from_ne_bytes(self.octets()) } - } -} -impl FromInner for Ipv4Addr { - fn from_inner(addr: c::in_addr) -> Ipv4Addr { - Ipv4Addr::from(addr.s_addr.to_ne_bytes()) - } -} - -impl IntoInner for Ipv6Addr { - fn into_inner(self) -> c::in6_addr { - c::in6_addr { s6_addr: self.octets() } - } -} -impl FromInner for Ipv6Addr { - #[inline] - fn from_inner(addr: c::in6_addr) -> Ipv6Addr { - Ipv6Addr::from(addr.s6_addr) - } -} diff --git a/library/std/src/net/socket_addr.rs b/library/std/src/net/socket_addr.rs index e8355cc31d7a5..4c8905c0d4609 100644 --- a/library/std/src/net/socket_addr.rs +++ b/library/std/src/net/socket_addr.rs @@ -6,50 +6,8 @@ mod tests; pub use core::net::{SocketAddr, SocketAddrV4, SocketAddrV6}; use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -use crate::sys::net::{LookupHost, netc as c}; -use crate::sys_common::{FromInner, IntoInner}; -use crate::{io, iter, mem, option, slice, vec}; - -impl FromInner for SocketAddrV4 { - fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 { - SocketAddrV4::new(Ipv4Addr::from_inner(addr.sin_addr), u16::from_be(addr.sin_port)) - } -} - -impl FromInner for SocketAddrV6 { - fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 { - SocketAddrV6::new( - Ipv6Addr::from_inner(addr.sin6_addr), - u16::from_be(addr.sin6_port), - addr.sin6_flowinfo, - addr.sin6_scope_id, - ) - } -} - -impl IntoInner for SocketAddrV4 { - fn into_inner(self) -> c::sockaddr_in { - c::sockaddr_in { - sin_family: c::AF_INET as c::sa_family_t, - sin_port: self.port().to_be(), - sin_addr: self.ip().into_inner(), - ..unsafe { mem::zeroed() } - } - } -} - -impl IntoInner for SocketAddrV6 { - fn into_inner(self) -> c::sockaddr_in6 { - c::sockaddr_in6 { - sin6_family: c::AF_INET6 as c::sa_family_t, - sin6_port: self.port().to_be(), - sin6_addr: self.ip().into_inner(), - sin6_flowinfo: self.flowinfo(), - sin6_scope_id: self.scope_id(), - ..unsafe { mem::zeroed() } - } - } -} +use crate::sys::net::LookupHost; +use crate::{io, iter, option, slice, vec}; /// A trait for objects which can be converted or resolved to one or more /// [`SocketAddr`] values. diff --git a/library/std/src/os/solid/io.rs b/library/std/src/os/solid/io.rs index b8c3440542d00..ca58a900c4451 100644 --- a/library/std/src/os/solid/io.rs +++ b/library/std/src/os/solid/io.rs @@ -122,7 +122,7 @@ impl BorrowedFd<'_> { /// Creates a new `OwnedFd` instance that shares the same underlying file /// description as the existing `BorrowedFd` instance. pub fn try_clone_to_owned(&self) -> crate::io::Result { - let fd = sys::net::cvt(unsafe { sys::net::netc::dup(self.as_raw_fd()) })?; + let fd = sys::net::cvt(unsafe { crate::sys::abi::sockets::dup(self.as_raw_fd()) })?; Ok(unsafe { OwnedFd::from_raw_fd(fd) }) } } @@ -168,7 +168,7 @@ impl FromRawFd for OwnedFd { impl Drop for OwnedFd { #[inline] fn drop(&mut self) { - unsafe { sys::net::netc::close(self.fd.as_inner()) }; + unsafe { crate::sys::abi::sockets::close(self.fd.as_inner()) }; } } diff --git a/library/std/src/sys/net/connection/sgx.rs b/library/std/src/sys/net/connection/sgx.rs index b390a5eac5f74..242df10bc3270 100644 --- a/library/std/src/sys/net/connection/sgx.rs +++ b/library/std/src/sys/net/connection/sgx.rs @@ -499,38 +499,3 @@ impl<'a> TryFrom<(&'a str, u16)> for LookupHost { LookupHost::new(format!("{host}:{port}")) } } - -#[allow(bad_style)] -pub mod netc { - pub const AF_INET: u8 = 0; - pub const AF_INET6: u8 = 1; - pub type sa_family_t = u8; - - #[derive(Copy, Clone)] - pub struct in_addr { - pub s_addr: u32, - } - - #[derive(Copy, Clone)] - pub struct sockaddr_in { - #[allow(dead_code)] - pub sin_family: sa_family_t, - pub sin_port: u16, - pub sin_addr: in_addr, - } - - #[derive(Copy, Clone)] - pub struct in6_addr { - pub s6_addr: [u8; 16], - } - - #[derive(Copy, Clone)] - pub struct sockaddr_in6 { - #[allow(dead_code)] - pub sin6_family: sa_family_t, - pub sin6_port: u16, - pub sin6_addr: in6_addr, - pub sin6_flowinfo: u32, - pub sin6_scope_id: u32, - } -} diff --git a/library/std/src/sys/net/connection/socket.rs b/library/std/src/sys/net/connection/socket.rs index 6fe3430b53f79..b4f0a7836803e 100644 --- a/library/std/src/sys/net/connection/socket.rs +++ b/library/std/src/sys/net/connection/socket.rs @@ -3,9 +3,9 @@ mod tests; use crate::ffi::{c_int, c_void}; use crate::io::{self, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut}; -use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; +use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, SocketAddrV4, SocketAddrV6}; use crate::sys::common::small_c_string::run_with_cstr; -use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::sys_common::{AsInner, FromInner}; use crate::time::Duration; use crate::{cmp, fmt, mem, ptr}; @@ -79,6 +79,111 @@ cfg_if::cfg_if! { } } +//////////////////////////////////////////////////////////////////////////////// +// address conversions +//////////////////////////////////////////////////////////////////////////////// + +fn ip_v4_addr_to_c(addr: &Ipv4Addr) -> c::in_addr { + // `s_addr` is stored as BE on all machines and the array is in BE order. + // So the native endian conversion method is used so that it's never swapped. + c::in_addr { s_addr: u32::from_ne_bytes(addr.octets()) } +} + +fn ip_v6_addr_to_c(addr: &Ipv6Addr) -> c::in6_addr { + c::in6_addr { s6_addr: addr.octets() } +} + +fn ip_v4_addr_from_c(addr: c::in_addr) -> Ipv4Addr { + Ipv4Addr::from(addr.s_addr.to_ne_bytes()) +} + +fn ip_v6_addr_from_c(addr: c::in6_addr) -> Ipv6Addr { + Ipv6Addr::from(addr.s6_addr) +} + +fn socket_addr_v4_to_c(addr: &SocketAddrV4) -> c::sockaddr_in { + c::sockaddr_in { + sin_family: c::AF_INET as c::sa_family_t, + sin_port: addr.port().to_be(), + sin_addr: ip_v4_addr_to_c(addr.ip()), + ..unsafe { mem::zeroed() } + } +} + +fn socket_addr_v6_to_c(addr: &SocketAddrV6) -> c::sockaddr_in6 { + c::sockaddr_in6 { + sin6_family: c::AF_INET6 as c::sa_family_t, + sin6_port: addr.port().to_be(), + sin6_addr: ip_v6_addr_to_c(addr.ip()), + sin6_flowinfo: addr.flowinfo(), + sin6_scope_id: addr.scope_id(), + ..unsafe { mem::zeroed() } + } +} + +fn socket_addr_v4_from_c(addr: c::sockaddr_in) -> SocketAddrV4 { + SocketAddrV4::new(ip_v4_addr_from_c(addr.sin_addr), u16::from_be(addr.sin_port)) +} + +fn socket_addr_v6_from_c(addr: c::sockaddr_in6) -> SocketAddrV6 { + SocketAddrV6::new( + ip_v6_addr_from_c(addr.sin6_addr), + u16::from_be(addr.sin6_port), + addr.sin6_flowinfo, + addr.sin6_scope_id, + ) +} + +/// A type with the same memory layout as `c::sockaddr`. Used in converting Rust level +/// SocketAddr* types into their system representation. The benefit of this specific +/// type over using `c::sockaddr_storage` is that this type is exactly as large as it +/// needs to be and not a lot larger. And it can be initialized more cleanly from Rust. +#[repr(C)] +union SocketAddrCRepr { + v4: c::sockaddr_in, + v6: c::sockaddr_in6, +} + +impl SocketAddrCRepr { + fn as_ptr(&self) -> *const c::sockaddr { + self as *const _ as *const c::sockaddr + } +} + +fn socket_addr_to_c(addr: &SocketAddr) -> (SocketAddrCRepr, c::socklen_t) { + match addr { + SocketAddr::V4(a) => { + let sockaddr = SocketAddrCRepr { v4: socket_addr_v4_to_c(a) }; + (sockaddr, mem::size_of::() as c::socklen_t) + } + SocketAddr::V6(a) => { + let sockaddr = SocketAddrCRepr { v6: socket_addr_v6_to_c(a) }; + (sockaddr, mem::size_of::() as c::socklen_t) + } + } +} + +unsafe fn socket_addr_from_c( + storage: *const c::sockaddr_storage, + len: usize, +) -> io::Result { + match (*storage).ss_family as c_int { + c::AF_INET => { + assert!(len >= mem::size_of::()); + Ok(SocketAddr::V4(socket_addr_v4_from_c(unsafe { + *(storage as *const _ as *const c::sockaddr_in) + }))) + } + c::AF_INET6 => { + assert!(len >= mem::size_of::()); + Ok(SocketAddr::V6(socket_addr_v6_from_c(unsafe { + *(storage as *const _ as *const c::sockaddr_in6) + }))) + } + _ => Err(io::const_error!(ErrorKind::InvalidInput, "invalid argument")), + } +} + //////////////////////////////////////////////////////////////////////////////// // sockaddr and misc bindings //////////////////////////////////////////////////////////////////////////////// @@ -124,25 +229,7 @@ where let mut storage: c::sockaddr_storage = mem::zeroed(); let mut len = mem::size_of_val(&storage) as c::socklen_t; cvt(f((&raw mut storage) as *mut _, &mut len))?; - sockaddr_to_addr(&storage, len as usize) - } -} - -pub fn sockaddr_to_addr(storage: &c::sockaddr_storage, len: usize) -> io::Result { - match storage.ss_family as c_int { - c::AF_INET => { - assert!(len >= mem::size_of::()); - Ok(SocketAddr::V4(FromInner::from_inner(unsafe { - *(storage as *const _ as *const c::sockaddr_in) - }))) - } - c::AF_INET6 => { - assert!(len >= mem::size_of::()); - Ok(SocketAddr::V6(FromInner::from_inner(unsafe { - *(storage as *const _ as *const c::sockaddr_in6) - }))) - } - _ => Err(io::const_error!(ErrorKind::InvalidInput, "invalid argument")), + socket_addr_from_c(&storage, len as usize) } } @@ -179,7 +266,7 @@ impl Iterator for LookupHost { unsafe { let cur = self.cur.as_ref()?; self.cur = cur.ai_next; - match sockaddr_to_addr(mem::transmute(cur.ai_addr), cur.ai_addrlen as usize) { + match socket_addr_from_c(cur.ai_addr.cast(), cur.ai_addrlen as usize) { Ok(addr) => return Some(addr), Err(_) => continue, } @@ -432,7 +519,7 @@ impl TcpListener { setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR, 1 as c_int)?; // Bind our new socket - let (addr, len) = addr.into_inner(); + let (addr, len) = socket_addr_to_c(addr); cvt(unsafe { c::bind(sock.as_raw(), addr.as_ptr(), len as _) })?; cfg_if::cfg_if! { @@ -473,7 +560,7 @@ impl TcpListener { let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() }; let mut len = mem::size_of_val(&storage) as c::socklen_t; let sock = self.inner.accept((&raw mut storage) as *mut _, &mut len)?; - let addr = sockaddr_to_addr(&storage, len as usize)?; + let addr = unsafe { socket_addr_from_c(&storage, len as usize)? }; Ok((TcpStream { inner: sock }, addr)) } @@ -542,7 +629,7 @@ impl UdpSocket { init(); let sock = Socket::new(addr, c::SOCK_DGRAM)?; - let (addr, len) = addr.into_inner(); + let (addr, len) = socket_addr_to_c(addr); cvt(unsafe { c::bind(sock.as_raw(), addr.as_ptr(), len as _) })?; Ok(UdpSocket { inner: sock }) } @@ -574,7 +661,7 @@ impl UdpSocket { pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result { let len = cmp::min(buf.len(), ::MAX as usize) as wrlen_t; - let (dst, dstlen) = dst.into_inner(); + let (dst, dstlen) = socket_addr_to_c(dst); let ret = cvt(unsafe { c::sendto( self.inner.as_raw(), @@ -656,15 +743,15 @@ impl UdpSocket { pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { let mreq = c::ip_mreq { - imr_multiaddr: multiaddr.into_inner(), - imr_interface: interface.into_inner(), + imr_multiaddr: ip_v4_addr_to_c(multiaddr), + imr_interface: ip_v4_addr_to_c(interface), }; setsockopt(&self.inner, c::IPPROTO_IP, c::IP_ADD_MEMBERSHIP, mreq) } pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { let mreq = c::ipv6_mreq { - ipv6mr_multiaddr: multiaddr.into_inner(), + ipv6mr_multiaddr: ip_v6_addr_to_c(multiaddr), ipv6mr_interface: to_ipv6mr_interface(interface), }; setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq) @@ -672,15 +759,15 @@ impl UdpSocket { pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { let mreq = c::ip_mreq { - imr_multiaddr: multiaddr.into_inner(), - imr_interface: interface.into_inner(), + imr_multiaddr: ip_v4_addr_to_c(multiaddr), + imr_interface: ip_v4_addr_to_c(interface), }; setsockopt(&self.inner, c::IPPROTO_IP, c::IP_DROP_MEMBERSHIP, mreq) } pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { let mreq = c::ipv6_mreq { - ipv6mr_multiaddr: multiaddr.into_inner(), + ipv6mr_multiaddr: ip_v6_addr_to_c(multiaddr), ipv6mr_interface: to_ipv6mr_interface(interface), }; setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, mreq) @@ -720,7 +807,7 @@ impl UdpSocket { } pub fn connect(&self, addr: io::Result<&SocketAddr>) -> io::Result<()> { - let (addr, len) = addr?.into_inner(); + let (addr, len) = socket_addr_to_c(addr?); cvt_r(|| unsafe { c::connect(self.inner.as_raw(), addr.as_ptr(), len) }).map(drop) } } @@ -743,38 +830,3 @@ impl fmt::Debug for UdpSocket { res.field(name, &self.inner.as_raw()).finish() } } - -//////////////////////////////////////////////////////////////////////////////// -// Converting SocketAddr to libc representation -//////////////////////////////////////////////////////////////////////////////// - -/// A type with the same memory layout as `c::sockaddr`. Used in converting Rust level -/// SocketAddr* types into their system representation. The benefit of this specific -/// type over using `c::sockaddr_storage` is that this type is exactly as large as it -/// needs to be and not a lot larger. And it can be initialized more cleanly from Rust. -#[repr(C)] -pub(crate) union SocketAddrCRepr { - v4: c::sockaddr_in, - v6: c::sockaddr_in6, -} - -impl SocketAddrCRepr { - pub fn as_ptr(&self) -> *const c::sockaddr { - self as *const _ as *const c::sockaddr - } -} - -impl<'a> IntoInner<(SocketAddrCRepr, c::socklen_t)> for &'a SocketAddr { - fn into_inner(self) -> (SocketAddrCRepr, c::socklen_t) { - match *self { - SocketAddr::V4(ref a) => { - let sockaddr = SocketAddrCRepr { v4: a.into_inner() }; - (sockaddr, mem::size_of::() as c::socklen_t) - } - SocketAddr::V6(ref a) => { - let sockaddr = SocketAddrCRepr { v6: a.into_inner() }; - (sockaddr, mem::size_of::() as c::socklen_t) - } - } - } -} diff --git a/library/std/src/sys/net/connection/socket/hermit.rs b/library/std/src/sys/net/connection/socket/hermit.rs index 42179dcc9156d..e393342ced9da 100644 --- a/library/std/src/sys/net/connection/socket/hermit.rs +++ b/library/std/src/sys/net/connection/socket/hermit.rs @@ -2,13 +2,13 @@ use core::ffi::c_int; -pub(crate) use hermit_abi as netc; +pub(super) use hermit_abi as netc; +use super::{getsockopt, setsockopt, socket_addr_from_c, socket_addr_to_c}; use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut}; use crate::net::{Shutdown, SocketAddr}; use crate::os::hermit::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, RawFd}; use crate::sys::fd::FileDesc; -use crate::sys::net::{getsockopt, setsockopt, sockaddr_to_addr}; use crate::sys::time::Instant; pub use crate::sys::{cvt, cvt_r}; use crate::sys_common::{AsInner, FromInner, IntoInner}; @@ -55,7 +55,7 @@ impl Socket { } pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> { - let (addr, len) = addr.into_inner(); + let (addr, len) = socket_addr_to_c(addr); cvt_r(|| unsafe { netc::connect(self.as_raw_fd(), addr.as_ptr(), len) })?; Ok(()) } @@ -63,7 +63,7 @@ impl Socket { pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> { self.set_nonblocking(true)?; let r = unsafe { - let (addr, len) = addr.into_inner(); + let (addr, len) = socket_addr_to_c(addr); cvt(netc::connect(self.as_raw_fd(), addr.as_ptr(), len)) }; self.set_nonblocking(false)?; @@ -195,7 +195,7 @@ impl Socket { &mut addrlen, ) })?; - Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?)) + Ok((n as usize, unsafe { socket_addr_from_c(&storage, addrlen as usize)? })) } pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { diff --git a/library/std/src/sys/net/connection/socket/solid.rs b/library/std/src/sys/net/connection/socket/solid.rs index f85ecbb883ee7..906bef267b6f0 100644 --- a/library/std/src/sys/net/connection/socket/solid.rs +++ b/library/std/src/sys/net/connection/socket/solid.rs @@ -1,17 +1,17 @@ use libc::{c_int, c_void, size_t}; use self::netc::{MSG_PEEK, sockaddr, socklen_t}; +use super::{getsockopt, setsockopt, socket_addr_from_c, socket_addr_to_c}; use crate::ffi::CStr; use crate::io::{self, BorrowedBuf, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut}; use crate::net::{Shutdown, SocketAddr}; use crate::os::solid::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd}; use crate::sys::abi; -use crate::sys::net::{getsockopt, setsockopt, sockaddr_to_addr}; use crate::sys_common::{FromInner, IntoInner}; use crate::time::Duration; use crate::{cmp, mem, ptr, str}; -pub mod netc { +pub(super) mod netc { pub use crate::sys::abi::sockets::*; } @@ -131,7 +131,7 @@ impl Socket { } pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> { - let (addr, len) = addr.into_inner(); + let (addr, len) = socket_addr_to_c(addr); cvt(unsafe { netc::connect(self.as_raw_fd(), addr.as_ptr(), len) })?; Ok(()) } @@ -256,7 +256,7 @@ impl Socket { &mut addrlen, ) })?; - Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?)) + Ok((n as usize, unsafe { socket_addr_from_c(&storage, addrlen as usize)? })) } pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { diff --git a/library/std/src/sys/net/connection/socket/unix.rs b/library/std/src/sys/net/connection/socket/unix.rs index da6316055273f..34ab26bc117af 100644 --- a/library/std/src/sys/net/connection/socket/unix.rs +++ b/library/std/src/sys/net/connection/socket/unix.rs @@ -5,7 +5,7 @@ use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut}; use crate::net::{Shutdown, SocketAddr}; use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; use crate::sys::fd::FileDesc; -use crate::sys::net::{getsockopt, setsockopt, sockaddr_to_addr}; +use crate::sys::net::{getsockopt, setsockopt}; use crate::sys::pal::IsMinusOne; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::{Duration, Instant}; @@ -19,8 +19,9 @@ cfg_if::cfg_if! { } } -pub(crate) use libc as netc; +pub(super) use libc as netc; +use super::{socket_addr_from_c, socket_addr_to_c}; pub use crate::sys::{cvt, cvt_r}; #[expect(non_camel_case_types)] @@ -150,7 +151,7 @@ impl Socket { } pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> { - let (addr, len) = addr.into_inner(); + let (addr, len) = socket_addr_to_c(addr); loop { let result = unsafe { libc::connect(self.as_raw_fd(), addr.as_ptr(), len) }; if result.is_minus_one() { @@ -168,7 +169,7 @@ impl Socket { pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> { self.set_nonblocking(true)?; let r = unsafe { - let (addr, len) = addr.into_inner(); + let (addr, len) = socket_addr_to_c(addr); cvt(libc::connect(self.as_raw_fd(), addr.as_ptr(), len)) }; self.set_nonblocking(false)?; @@ -334,7 +335,7 @@ impl Socket { &mut addrlen, ) })?; - Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?)) + Ok((n as usize, unsafe { socket_addr_from_c(&storage, addrlen as usize)? })) } pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { diff --git a/library/std/src/sys/net/connection/socket/wasip2.rs b/library/std/src/sys/net/connection/socket/wasip2.rs index 9d1c05a473e4d..c5034e73dd704 100644 --- a/library/std/src/sys/net/connection/socket/wasip2.rs +++ b/library/std/src/sys/net/connection/socket/wasip2.rs @@ -1,19 +1,18 @@ #![deny(unsafe_op_in_unsafe_fn)] +pub(super) use libc as netc; use libc::{c_int, c_void, size_t}; +use super::{getsockopt, setsockopt, socket_addr_from_c, socket_addr_to_c}; use crate::ffi::CStr; use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut}; use crate::net::{Shutdown, SocketAddr}; use crate::os::wasi::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; -use crate::sys::net::{getsockopt, setsockopt, sockaddr_to_addr}; use crate::sys::unsupported; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::{Duration, Instant}; use crate::{cmp, mem, str}; -pub extern crate libc as netc; - #[allow(non_camel_case_types)] pub type wrlen_t = size_t; @@ -89,7 +88,7 @@ impl Socket { } pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> { - let (addr, len) = addr.into_inner(); + let (addr, len) = socket_addr_to_c(addr); cvt_r(|| unsafe { netc::connect(self.as_raw_fd(), addr.as_ptr(), len) })?; Ok(()) } @@ -224,7 +223,7 @@ impl Socket { &mut addrlen, ) })?; - Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?)) + Ok((n as usize, unsafe { socket_addr_from_c(&storage, addrlen as usize)? })) } pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { diff --git a/library/std/src/sys/net/connection/socket/windows.rs b/library/std/src/sys/net/connection/socket/windows.rs index 80cf37eaf0580..428f142dabe20 100644 --- a/library/std/src/sys/net/connection/socket/windows.rs +++ b/library/std/src/sys/net/connection/socket/windows.rs @@ -2,6 +2,7 @@ use core::ffi::{c_int, c_long, c_ulong, c_ushort}; +use super::{getsockopt, setsockopt, socket_addr_from_c, socket_addr_to_c}; use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut, Read}; use crate::net::{Shutdown, SocketAddr}; use crate::os::windows::io::{ @@ -16,7 +17,7 @@ use crate::{cmp, mem, ptr, sys}; #[allow(non_camel_case_types)] pub type wrlen_t = i32; -pub mod netc { +pub(super) mod netc { //! BSD socket compatibility shim //! //! Some Windows API types are not quite what's expected by our cross-platform @@ -225,7 +226,7 @@ impl Socket { } pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> { - let (addr, len) = addr.into_inner(); + let (addr, len) = socket_addr_to_c(addr); let result = unsafe { c::connect(self.as_raw(), addr.as_ptr(), len) }; cvt(result).map(drop) } @@ -401,12 +402,12 @@ impl Socket { let error = unsafe { c::WSAGetLastError() }; if error == c::WSAESHUTDOWN { - Ok((0, super::sockaddr_to_addr(&storage, addrlen as usize)?)) + Ok((0, unsafe { socket_addr_from_c(&storage, addrlen as usize)? })) } else { Err(io::Error::from_raw_os_error(error)) } } - _ => Ok((result as usize, super::sockaddr_to_addr(&storage, addrlen as usize)?)), + _ => Ok((result as usize, unsafe { socket_addr_from_c(&storage, addrlen as usize)? })), } } @@ -451,11 +452,11 @@ impl Socket { } None => 0, }; - super::setsockopt(self, c::SOL_SOCKET, kind, timeout) + setsockopt(self, c::SOL_SOCKET, kind, timeout) } pub fn timeout(&self, kind: c_int) -> io::Result> { - let raw: u32 = super::getsockopt(self, c::SOL_SOCKET, kind)?; + let raw: u32 = getsockopt(self, c::SOL_SOCKET, kind)?; if raw == 0 { Ok(None) } else { @@ -488,26 +489,26 @@ impl Socket { l_linger: linger.unwrap_or_default().as_secs() as c_ushort, }; - super::setsockopt(self, c::SOL_SOCKET, c::SO_LINGER, linger) + setsockopt(self, c::SOL_SOCKET, c::SO_LINGER, linger) } pub fn linger(&self) -> io::Result> { - let val: c::LINGER = super::getsockopt(self, c::SOL_SOCKET, c::SO_LINGER)?; + let val: c::LINGER = getsockopt(self, c::SOL_SOCKET, c::SO_LINGER)?; Ok((val.l_onoff != 0).then(|| Duration::from_secs(val.l_linger as u64))) } pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { - super::setsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY, nodelay as c::BOOL) + setsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY, nodelay as c::BOOL) } pub fn nodelay(&self) -> io::Result { - let raw: c::BOOL = super::getsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY)?; + let raw: c::BOOL = getsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY)?; Ok(raw != 0) } pub fn take_error(&self) -> io::Result> { - let raw: c_int = super::getsockopt(self, c::SOL_SOCKET, c::SO_ERROR)?; + let raw: c_int = getsockopt(self, c::SOL_SOCKET, c::SO_ERROR)?; if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) } } diff --git a/library/std/src/sys/net/connection/unsupported.rs b/library/std/src/sys/net/connection/unsupported.rs index 87e6106468fdb..da2174396266f 100644 --- a/library/std/src/sys/net/connection/unsupported.rs +++ b/library/std/src/sys/net/connection/unsupported.rs @@ -332,38 +332,3 @@ impl<'a> TryFrom<(&'a str, u16)> for LookupHost { unsupported() } } - -#[allow(nonstandard_style)] -pub mod netc { - pub const AF_INET: u8 = 0; - pub const AF_INET6: u8 = 1; - pub type sa_family_t = u8; - - #[derive(Copy, Clone)] - pub struct in_addr { - pub s_addr: u32, - } - - #[derive(Copy, Clone)] - pub struct sockaddr_in { - #[allow(dead_code)] - pub sin_family: sa_family_t, - pub sin_port: u16, - pub sin_addr: in_addr, - } - - #[derive(Copy, Clone)] - pub struct in6_addr { - pub s6_addr: [u8; 16], - } - - #[derive(Copy, Clone)] - pub struct sockaddr_in6 { - #[allow(dead_code)] - pub sin6_family: sa_family_t, - pub sin6_port: u16, - pub sin6_addr: in6_addr, - pub sin6_flowinfo: u32, - pub sin6_scope_id: u32, - } -} diff --git a/library/std/src/sys/net/connection/wasip1.rs b/library/std/src/sys/net/connection/wasip1.rs index 27e3a528af497..951dc65e5b47d 100644 --- a/library/std/src/sys/net/connection/wasip1.rs +++ b/library/std/src/sys/net/connection/wasip1.rs @@ -505,38 +505,3 @@ impl<'a> TryFrom<(&'a str, u16)> for LookupHost { unsupported() } } - -#[allow(nonstandard_style)] -pub mod netc { - pub const AF_INET: u8 = 0; - pub const AF_INET6: u8 = 1; - pub type sa_family_t = u8; - - #[derive(Copy, Clone)] - pub struct in_addr { - pub s_addr: u32, - } - - #[derive(Copy, Clone)] - pub struct sockaddr_in { - #[allow(dead_code)] - pub sin_family: sa_family_t, - pub sin_port: u16, - pub sin_addr: in_addr, - } - - #[derive(Copy, Clone)] - pub struct in6_addr { - pub s6_addr: [u8; 16], - } - - #[derive(Copy, Clone)] - pub struct sockaddr_in6 { - #[allow(dead_code)] - pub sin6_family: sa_family_t, - pub sin6_port: u16, - pub sin6_addr: in6_addr, - pub sin6_flowinfo: u32, - pub sin6_scope_id: u32, - } -} diff --git a/library/std/src/sys/net/connection/xous/mod.rs b/library/std/src/sys/net/connection/xous/mod.rs index 3e18ed24208d3..e44a375b9e3c5 100644 --- a/library/std/src/sys/net/connection/xous/mod.rs +++ b/library/std/src/sys/net/connection/xous/mod.rs @@ -46,38 +46,3 @@ pub struct GetAddress { } pub use dns::LookupHost; - -#[allow(nonstandard_style)] -pub mod netc { - pub const AF_INET: u8 = 0; - pub const AF_INET6: u8 = 1; - pub type sa_family_t = u8; - - #[derive(Copy, Clone)] - pub struct in_addr { - pub s_addr: u32, - } - - #[derive(Copy, Clone)] - pub struct sockaddr_in { - #[allow(dead_code)] - pub sin_family: sa_family_t, - pub sin_port: u16, - pub sin_addr: in_addr, - } - - #[derive(Copy, Clone)] - pub struct in6_addr { - pub s6_addr: [u8; 16], - } - - #[derive(Copy, Clone)] - pub struct sockaddr_in6 { - #[allow(dead_code)] - pub sin6_family: sa_family_t, - pub sin6_port: u16, - pub sin6_addr: in6_addr, - pub sin6_flowinfo: u32, - pub sin6_scope_id: u32, - } -} From 18b9ee734518c34d60d8624974b23ca3e07f4908 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 29 Jan 2025 12:16:51 +0100 Subject: [PATCH 03/15] add x86-sse2 (32bit) ABI that requires SSE2 target feature --- compiler/rustc_target/src/spec/base/apple/mod.rs | 10 +++++++--- compiler/rustc_target/src/spec/mod.rs | 9 +++++++++ .../src/spec/targets/i586_pc_nto_qnx700.rs | 3 ++- .../src/spec/targets/i586_unknown_linux_gnu.rs | 1 + .../src/spec/targets/i586_unknown_linux_musl.rs | 1 + .../src/spec/targets/i686_linux_android.rs | 3 ++- .../src/spec/targets/i686_pc_windows_gnu.rs | 3 ++- .../src/spec/targets/i686_pc_windows_gnullvm.rs | 3 ++- .../src/spec/targets/i686_pc_windows_msvc.rs | 3 ++- .../src/spec/targets/i686_unknown_freebsd.rs | 3 ++- .../src/spec/targets/i686_unknown_haiku.rs | 3 ++- .../src/spec/targets/i686_unknown_linux_gnu.rs | 14 +++++++++++++- .../src/spec/targets/i686_unknown_linux_musl.rs | 5 ++++- .../src/spec/targets/i686_unknown_netbsd.rs | 3 ++- .../src/spec/targets/i686_unknown_openbsd.rs | 3 ++- .../src/spec/targets/i686_uwp_windows_gnu.rs | 3 ++- .../src/spec/targets/i686_uwp_windows_msvc.rs | 3 ++- .../src/spec/targets/i686_win7_windows_gnu.rs | 3 ++- .../src/spec/targets/i686_win7_windows_msvc.rs | 3 ++- .../src/spec/targets/i686_wrs_vxworks.rs | 3 ++- compiler/rustc_target/src/target_features.rs | 8 ++++++++ .../x86/intrinsics-x86-pause-without-sse2.stderr | 5 +++++ tests/ui/sse-abi-checks.rs | 2 +- .../target-cpu-lacks-required-target-feature.rs | 12 ++++++++++++ ...target-cpu-lacks-required-target-feature.stderr | 7 +++++++ 25 files changed, 96 insertions(+), 20 deletions(-) create mode 100644 src/tools/miri/tests/pass/shims/x86/intrinsics-x86-pause-without-sse2.stderr create mode 100644 tests/ui/target-feature/target-cpu-lacks-required-target-feature.rs create mode 100644 tests/ui/target-feature/target-cpu-lacks-required-target-feature.stderr diff --git a/compiler/rustc_target/src/spec/base/apple/mod.rs b/compiler/rustc_target/src/spec/base/apple/mod.rs index 497994a5998cb..1b56143545f61 100644 --- a/compiler/rustc_target/src/spec/base/apple/mod.rs +++ b/compiler/rustc_target/src/spec/base/apple/mod.rs @@ -2,8 +2,8 @@ use std::borrow::Cow; use std::env; use crate::spec::{ - Cc, DebuginfoKind, FloatAbi, FramePointer, LinkerFlavor, Lld, SplitDebuginfo, StackProbeType, - StaticCow, TargetOptions, cvs, + Cc, DebuginfoKind, FloatAbi, FramePointer, LinkerFlavor, Lld, RustcAbi, SplitDebuginfo, + StackProbeType, StaticCow, TargetOptions, cvs, }; #[cfg(test)] @@ -103,7 +103,7 @@ pub(crate) fn base( arch: Arch, abi: TargetAbi, ) -> (TargetOptions, StaticCow, StaticCow) { - let opts = TargetOptions { + let mut opts = TargetOptions { abi: abi.target_abi().into(), llvm_floatabi: Some(FloatAbi::Hard), os: os.into(), @@ -154,6 +154,10 @@ pub(crate) fn base( ..Default::default() }; + if matches!(arch, Arch::I386 | Arch::I686) { + // All Apple x86-32 targets have SSE2. + opts.rustc_abi = Some(RustcAbi::X86Sse2); + } (opts, unversioned_llvm_target(os, arch, abi), arch.target_arch()) } diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 03b3426fcec01..e3046e8b85530 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -1116,6 +1116,8 @@ impl ToJson for FloatAbi { /// The Rustc-specific variant of the ABI used for this target. #[derive(Clone, Copy, PartialEq, Hash, Debug)] pub enum RustcAbi { + /// On x86-32 only: make use of SSE and SSE2 for ABI purposes. + X86Sse2, /// On x86-32/64 only: do not use any FPU or SIMD registers for the ABI. X86Softfloat, } @@ -1125,6 +1127,7 @@ impl FromStr for RustcAbi { fn from_str(s: &str) -> Result { Ok(match s { + "x86-sse2" => RustcAbi::X86Sse2, "x86-softfloat" => RustcAbi::X86Softfloat, _ => return Err(()), }) @@ -1134,6 +1137,7 @@ impl FromStr for RustcAbi { impl ToJson for RustcAbi { fn to_json(&self) -> Json { match *self { + RustcAbi::X86Sse2 => "x86-sse2", RustcAbi::X86Softfloat => "x86-softfloat", } .to_json() @@ -3268,6 +3272,11 @@ impl Target { // Check consistency of Rust ABI declaration. if let Some(rust_abi) = self.rustc_abi { match rust_abi { + RustcAbi::X86Sse2 => check_matches!( + &*self.arch, + "x86", + "`x86-sse2` ABI is only valid for x86-32 targets" + ), RustcAbi::X86Softfloat => check_matches!( &*self.arch, "x86" | "x86_64", diff --git a/compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs b/compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs index fa21cfbab8a3c..6a98a763b364d 100644 --- a/compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs +++ b/compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs @@ -1,5 +1,5 @@ use crate::spec::base::nto_qnx; -use crate::spec::{StackProbeType, Target, TargetOptions, base}; +use crate::spec::{RustcAbi, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut meta = nto_qnx::meta(); @@ -14,6 +14,7 @@ pub(crate) fn target() -> Target { .into(), arch: "x86".into(), options: TargetOptions { + rustc_abi: Some(RustcAbi::X86Sse2), cpu: "pentium4".into(), max_atomic_width: Some(64), pre_link_args: nto_qnx::pre_link_args( diff --git a/compiler/rustc_target/src/spec/targets/i586_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/i586_unknown_linux_gnu.rs index e481e967ebfa2..f04e3c2c2a5b0 100644 --- a/compiler/rustc_target/src/spec/targets/i586_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/i586_unknown_linux_gnu.rs @@ -2,6 +2,7 @@ use crate::spec::Target; pub(crate) fn target() -> Target { let mut base = super::i686_unknown_linux_gnu::target(); + base.rustc_abi = None; // overwrite the SSE2 ABI set by the base target base.cpu = "pentium".into(); base.llvm_target = "i586-unknown-linux-gnu".into(); base diff --git a/compiler/rustc_target/src/spec/targets/i586_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/i586_unknown_linux_musl.rs index 8ad93496f3a8c..42babb90da7cc 100644 --- a/compiler/rustc_target/src/spec/targets/i586_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/i586_unknown_linux_musl.rs @@ -2,6 +2,7 @@ use crate::spec::Target; pub(crate) fn target() -> Target { let mut base = super::i686_unknown_linux_musl::target(); + base.rustc_abi = None; // overwrite the SSE2 ABI set by the base target base.cpu = "pentium".into(); base.llvm_target = "i586-unknown-linux-musl".into(); // FIXME(compiler-team#422): musl targets should be dynamically linked by default. diff --git a/compiler/rustc_target/src/spec/targets/i686_linux_android.rs b/compiler/rustc_target/src/spec/targets/i686_linux_android.rs index dcf9b6b4460f3..4744ca859dfe0 100644 --- a/compiler/rustc_target/src/spec/targets/i686_linux_android.rs +++ b/compiler/rustc_target/src/spec/targets/i686_linux_android.rs @@ -1,4 +1,4 @@ -use crate::spec::{SanitizerSet, StackProbeType, Target, TargetOptions, base}; +use crate::spec::{RustcAbi, SanitizerSet, StackProbeType, Target, TargetOptions, base}; // See https://developer.android.com/ndk/guides/abis.html#x86 // for target ABI requirements. @@ -8,6 +8,7 @@ pub(crate) fn target() -> Target { base.max_atomic_width = Some(64); + base.rustc_abi = Some(RustcAbi::X86Sse2); // https://developer.android.com/ndk/guides/abis.html#x86 base.cpu = "pentiumpro".into(); base.features = "+mmx,+sse,+sse2,+sse3,+ssse3".into(); diff --git a/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnu.rs b/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnu.rs index 208fe50912ca9..06dbf1e3a1657 100644 --- a/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnu.rs @@ -1,7 +1,8 @@ -use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, Target, base}; +use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, RustcAbi, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_gnu::opts(); + base.rustc_abi = Some(RustcAbi::X86Sse2); base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.frame_pointer = FramePointer::Always; // Required for backtraces diff --git a/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnullvm.rs b/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnullvm.rs index 5df8dce1aa352..05d848e039315 100644 --- a/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnullvm.rs +++ b/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnullvm.rs @@ -1,7 +1,8 @@ -use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, Target, base}; +use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, RustcAbi, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_gnullvm::opts(); + base.rustc_abi = Some(RustcAbi::X86Sse2); base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.frame_pointer = FramePointer::Always; // Required for backtraces diff --git a/compiler/rustc_target/src/spec/targets/i686_pc_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/i686_pc_windows_msvc.rs index 180750bc7a8b2..e0e471130874c 100644 --- a/compiler/rustc_target/src/spec/targets/i686_pc_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/i686_pc_windows_msvc.rs @@ -1,7 +1,8 @@ -use crate::spec::{LinkerFlavor, Lld, SanitizerSet, Target, base}; +use crate::spec::{LinkerFlavor, Lld, RustcAbi, SanitizerSet, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_msvc::opts(); + base.rustc_abi = Some(RustcAbi::X86Sse2); base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.supported_sanitizers = SanitizerSet::ADDRESS; diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_freebsd.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_freebsd.rs index 85ab87cc07f77..71c26041a50a4 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_freebsd.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_freebsd.rs @@ -1,7 +1,8 @@ -use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; +use crate::spec::{Cc, LinkerFlavor, Lld, RustcAbi, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::freebsd::opts(); + base.rustc_abi = Some(RustcAbi::X86Sse2); base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m32", "-Wl,-znotext"]); diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_haiku.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_haiku.rs index 1ab493c787c2a..464ac46b07c0e 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_haiku.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_haiku.rs @@ -1,7 +1,8 @@ -use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; +use crate::spec::{Cc, LinkerFlavor, Lld, RustcAbi, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::haiku::opts(); + base.rustc_abi = Some(RustcAbi::X86Sse2); base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m32"]); diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_linux_gnu.rs index c95cb308d7f5c..fe699dbcb5109 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_linux_gnu.rs @@ -1,7 +1,19 @@ -use crate::spec::{Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target, base}; +use crate::spec::{Cc, LinkerFlavor, Lld, RustcAbi, SanitizerSet, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::linux_gnu::opts(); + base.rustc_abi = Some(RustcAbi::X86Sse2); + // Dear distribution packager, if you are changing the base CPU model with the goal of removing + // the SSE2 requirement, make sure to also set the `rustc_abi` to `None` above or else the compiler + // will complain that the chosen ABI cannot be realized with the given CPU features. + // Also note that x86 without SSE2 is *not* considered a Tier 1 target by the Rust project, and + // it has some known floating-point correctness issues mostly caused by a lack of people caring + // for LLVM's x87 support (double-rounding, value truncation; see + // for details). This can lead to incorrect + // math (Rust generally promises exact math, so this can break code in unexpected ways) and it + // can lead to memory safety violations if floating-point values are used e.g. to access an + // array. If users run into such issues and report bugs upstream and then it turns out that the + // bugs are caused by distribution patches, that leads to confusion and frustration. base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.supported_sanitizers = SanitizerSet::ADDRESS; diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_linux_musl.rs index 6ba87c732b72d..3d25c951e813f 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_linux_musl.rs @@ -1,7 +1,10 @@ -use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, StackProbeType, Target, base}; +use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, RustcAbi, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); + base.rustc_abi = Some(RustcAbi::X86Sse2); + // If you want to change the base CPU, please see `i686_unknown_linux_gnu.rs` + // for an important comment. base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m32", "-Wl,-melf_i386"]); diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_netbsd.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_netbsd.rs index 092ba5c7baa16..4bc6eee1ac272 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_netbsd.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_netbsd.rs @@ -1,7 +1,8 @@ -use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; +use crate::spec::{Cc, LinkerFlavor, Lld, RustcAbi, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::netbsd::opts(); + base.rustc_abi = Some(RustcAbi::X86Sse2); base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m32"]); diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_openbsd.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_openbsd.rs index 7ae9189e23393..a3bdf66a14d89 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_openbsd.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_openbsd.rs @@ -1,7 +1,8 @@ -use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; +use crate::spec::{Cc, LinkerFlavor, Lld, RustcAbi, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::openbsd::opts(); + base.rustc_abi = Some(RustcAbi::X86Sse2); base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m32", "-fuse-ld=lld"]); diff --git a/compiler/rustc_target/src/spec/targets/i686_uwp_windows_gnu.rs b/compiler/rustc_target/src/spec/targets/i686_uwp_windows_gnu.rs index 6e3733538edf1..0e1b65ef598c0 100644 --- a/compiler/rustc_target/src/spec/targets/i686_uwp_windows_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/i686_uwp_windows_gnu.rs @@ -1,7 +1,8 @@ -use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, Target, base}; +use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, RustcAbi, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_uwp_gnu::opts(); + base.rustc_abi = Some(RustcAbi::X86Sse2); base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.frame_pointer = FramePointer::Always; // Required for backtraces diff --git a/compiler/rustc_target/src/spec/targets/i686_uwp_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/i686_uwp_windows_msvc.rs index e0de9b9af45f2..44cf9b1adda14 100644 --- a/compiler/rustc_target/src/spec/targets/i686_uwp_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/i686_uwp_windows_msvc.rs @@ -1,7 +1,8 @@ -use crate::spec::{Target, base}; +use crate::spec::{RustcAbi, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_uwp_msvc::opts(); + base.rustc_abi = Some(RustcAbi::X86Sse2); base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); diff --git a/compiler/rustc_target/src/spec/targets/i686_win7_windows_gnu.rs b/compiler/rustc_target/src/spec/targets/i686_win7_windows_gnu.rs index 1d084c0729cc1..e9100da14cba2 100644 --- a/compiler/rustc_target/src/spec/targets/i686_win7_windows_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/i686_win7_windows_gnu.rs @@ -1,8 +1,9 @@ -use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, Target, base}; +use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, RustcAbi, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_gnu::opts(); base.vendor = "win7".into(); + base.rustc_abi = Some(RustcAbi::X86Sse2); base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.frame_pointer = FramePointer::Always; // Required for backtraces diff --git a/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs index 7efba3aa986ab..94284a2fe72b2 100644 --- a/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs @@ -1,8 +1,9 @@ -use crate::spec::{LinkerFlavor, Lld, SanitizerSet, Target, base}; +use crate::spec::{LinkerFlavor, Lld, RustcAbi, SanitizerSet, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_msvc::opts(); base.vendor = "win7".into(); + base.rustc_abi = Some(RustcAbi::X86Sse2); base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.supported_sanitizers = SanitizerSet::ADDRESS; diff --git a/compiler/rustc_target/src/spec/targets/i686_wrs_vxworks.rs b/compiler/rustc_target/src/spec/targets/i686_wrs_vxworks.rs index dfffa6e138f85..4e801955d0cb1 100644 --- a/compiler/rustc_target/src/spec/targets/i686_wrs_vxworks.rs +++ b/compiler/rustc_target/src/spec/targets/i686_wrs_vxworks.rs @@ -1,7 +1,8 @@ -use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; +use crate::spec::{Cc, LinkerFlavor, Lld, RustcAbi, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::vxworks::opts(); + base.rustc_abi = Some(RustcAbi::X86Sse2); base.cpu = "pentium4".into(); base.max_atomic_width = Some(64); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m32"]); diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index ea7c15a359538..96b2fc8af70ea 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -789,6 +789,13 @@ impl Target { // x87 must be enabled, soft-float must be disabled. FeatureConstraints { required: &["x87"], incompatible: &["soft-float"] } } + Some(RustcAbi::X86Sse2) => { + // Extended hardfloat ABI. x87 and SSE2 must be enabled, soft-float must be disabled. + FeatureConstraints { + required: &["x87", "sse2"], + incompatible: &["soft-float"], + } + } Some(RustcAbi::X86Softfloat) => { // Softfloat ABI, requires corresponding target feature. That feature trumps // `x87` and all other FPU features so those do not matter. @@ -816,6 +823,7 @@ impl Target { // LLVM handles the rest. FeatureConstraints { required: &["soft-float"], incompatible: &[] } } + Some(r) => panic!("invalid Rust ABI for x86_64: {r:?}"), } } "arm" => { diff --git a/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-pause-without-sse2.stderr b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-pause-without-sse2.stderr new file mode 100644 index 0000000000000..171bf0c82d511 --- /dev/null +++ b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-pause-without-sse2.stderr @@ -0,0 +1,5 @@ +warning: target feature `sse2` must be enabled to ensure that the ABI of the current target can be implemented correctly + | + = note: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116344 + diff --git a/tests/ui/sse-abi-checks.rs b/tests/ui/sse-abi-checks.rs index c453e91d11b2a..d400e6eb698e9 100644 --- a/tests/ui/sse-abi-checks.rs +++ b/tests/ui/sse-abi-checks.rs @@ -1,6 +1,6 @@ //! Ensure we trigger abi_unsupported_vector_types for target features that are usually enabled //! on a target, but disabled in this file via a `-C` flag. -//@ compile-flags: --crate-type=rlib --target=i686-unknown-linux-gnu -C target-feature=-sse,-sse2 +//@ compile-flags: --crate-type=rlib --target=i586-unknown-linux-gnu -C target-feature=-sse,-sse2 //@ build-pass //@ ignore-pass (test emits codegen-time warnings) //@ needs-llvm-components: x86 diff --git a/tests/ui/target-feature/target-cpu-lacks-required-target-feature.rs b/tests/ui/target-feature/target-cpu-lacks-required-target-feature.rs new file mode 100644 index 0000000000000..28d026c1a9a2d --- /dev/null +++ b/tests/ui/target-feature/target-cpu-lacks-required-target-feature.rs @@ -0,0 +1,12 @@ +//@ compile-flags: --target=i686-unknown-linux-gnu --crate-type=lib +//@ needs-llvm-components: x86 +//@ compile-flags: -Ctarget-cpu=pentium +// For now this is just a warning. +//@ build-pass +//@error-pattern: must be enabled + +#![feature(no_core, lang_items)] +#![no_core] + +#[lang = "sized"] +pub trait Sized {} diff --git a/tests/ui/target-feature/target-cpu-lacks-required-target-feature.stderr b/tests/ui/target-feature/target-cpu-lacks-required-target-feature.stderr new file mode 100644 index 0000000000000..7ec8b04cfce01 --- /dev/null +++ b/tests/ui/target-feature/target-cpu-lacks-required-target-feature.stderr @@ -0,0 +1,7 @@ +warning: target feature `sse2` must be enabled to ensure that the ABI of the current target can be implemented correctly + | + = note: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116344 + +warning: 1 warning emitted + From f94ada13deab495c48984a46cac56151a1e98f6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E5=AE=87=E9=80=B8?= Date: Thu, 2 Jan 2025 00:33:04 +0900 Subject: [PATCH 04/15] Add cygwin target. Co-authored-by: Ookiineko Co-authored-by: nora <48135649+Noratrieb@users.noreply.github.com> Co-authored-by: Jubilee --- compiler/rustc_target/src/spec/base/cygwin.rs | 51 +++++++++++++++++++ compiler/rustc_target/src/spec/base/mod.rs | 1 + compiler/rustc_target/src/spec/mod.rs | 5 +- .../src/spec/targets/x86_64_pc_cygwin.rs | 32 ++++++++++++ src/bootstrap/src/core/builder/cargo.rs | 6 ++- src/doc/rustc/src/SUMMARY.md | 1 + src/doc/rustc/src/platform-support.md | 1 + .../src/platform-support/x86_64-pc-cygwin.md | 39 ++++++++++++++ tests/assembly/targets/targets-pe.rs | 3 ++ tests/ui/check-cfg/well-known-values.stderr | 4 +- 10 files changed, 138 insertions(+), 5 deletions(-) create mode 100644 compiler/rustc_target/src/spec/base/cygwin.rs create mode 100644 compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs create mode 100644 src/doc/rustc/src/platform-support/x86_64-pc-cygwin.md diff --git a/compiler/rustc_target/src/spec/base/cygwin.rs b/compiler/rustc_target/src/spec/base/cygwin.rs new file mode 100644 index 0000000000000..2d29060c47a39 --- /dev/null +++ b/compiler/rustc_target/src/spec/base/cygwin.rs @@ -0,0 +1,51 @@ +use std::borrow::Cow; + +use crate::spec::{Cc, DebuginfoKind, LinkerFlavor, Lld, SplitDebuginfo, TargetOptions, cvs}; + +pub(crate) fn opts() -> TargetOptions { + let mut pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ + // FIXME: Disable ASLR for now to fix relocation error + "--disable-dynamicbase", + "--enable-auto-image-base", + ]); + crate::spec::add_link_args(&mut pre_link_args, LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ + // Tell GCC to avoid linker plugins, because we are not bundling + // them with Windows installer, and Rust does its own LTO anyways. + "-fno-use-linker-plugin", + "-Wl,--disable-dynamicbase", + "-Wl,--enable-auto-image-base", + ]); + let cygwin_libs = &["-lcygwin", "-lgcc", "-lcygwin", "-luser32", "-lkernel32", "-lgcc_s"]; + let mut late_link_args = + TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), cygwin_libs); + crate::spec::add_link_args( + &mut late_link_args, + LinkerFlavor::Gnu(Cc::Yes, Lld::No), + cygwin_libs, + ); + TargetOptions { + os: "cygwin".into(), + vendor: "pc".into(), + // FIXME(#13846) this should be enabled for cygwin + function_sections: false, + linker: Some("gcc".into()), + dynamic_linking: true, + dll_prefix: "".into(), + dll_suffix: ".dll".into(), + exe_suffix: ".exe".into(), + families: cvs!["unix"], + is_like_windows: true, + allows_weak_linkage: false, + pre_link_args, + late_link_args, + abi_return_struct_as_int: true, + emit_debug_gdb_scripts: false, + requires_uwtable: true, + eh_frame_header: false, + // FIXME(davidtwco): Support Split DWARF on Cygwin - may require LLVM changes to + // output DWO, despite using DWARF, doesn't use ELF.. + debuginfo_kind: DebuginfoKind::Pdb, + supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]), + ..Default::default() + } +} diff --git a/compiler/rustc_target/src/spec/base/mod.rs b/compiler/rustc_target/src/spec/base/mod.rs index 28d10dcf2ff3a..b9139c8452c5f 100644 --- a/compiler/rustc_target/src/spec/base/mod.rs +++ b/compiler/rustc_target/src/spec/base/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod android; pub(crate) mod apple; pub(crate) mod avr_gnu; pub(crate) mod bpf; +pub(crate) mod cygwin; pub(crate) mod dragonfly; pub(crate) mod freebsd; pub(crate) mod fuchsia; diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index df1862ec27eee..91154edbd0092 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -2020,6 +2020,7 @@ supported_targets! { ("riscv64imac-unknown-nuttx-elf", riscv64imac_unknown_nuttx_elf), ("riscv64gc-unknown-nuttx-elf", riscv64gc_unknown_nuttx_elf), + ("x86_64-pc-cygwin", x86_64_pc_cygwin), } /// Cow-Vec-Str: Cow<'static, [Cow<'static, str>]> @@ -3001,8 +3002,8 @@ impl Target { ); check_eq!( self.is_like_windows, - self.os == "windows" || self.os == "uefi", - "`is_like_windows` must be set if and only if `os` is `windows` or `uefi`" + self.os == "windows" || self.os == "uefi" || self.os == "cygwin", + "`is_like_windows` must be set if and only if `os` is `windows`, `uefi` or `cygwin`" ); check_eq!( self.is_like_wasm, diff --git a/compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs b/compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs new file mode 100644 index 0000000000000..a5bedd07e6be8 --- /dev/null +++ b/compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs @@ -0,0 +1,32 @@ +use crate::spec::{Cc, LinkerFlavor, Lld, Target, base}; + +pub(crate) fn target() -> Target { + let mut base = base::cygwin::opts(); + base.cpu = "x86-64".into(); + // FIXME: Disable ASLR for now to fix relocation error + base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ + "-m", + "i386pep", + "--disable-high-entropy-va", + ]); + base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ + "-m64", + "-Wl,--disable-high-entropy-va", + ]); + base.max_atomic_width = Some(64); + base.linker = Some("x86_64-pc-cygwin-gcc".into()); + Target { + llvm_target: "x86_64-pc-cygwin".into(), + pointer_width: 64, + data_layout: + "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128".into(), + arch: "x86_64".into(), + options: base, + metadata: crate::spec::TargetMetadata { + description: Some("64-bit x86 Cygwin".into()), + tier: Some(3), + host_tools: Some(false), + std: Some(true), + }, + } +} diff --git a/src/bootstrap/src/core/builder/cargo.rs b/src/bootstrap/src/core/builder/cargo.rs index 2ecab262413fa..dc1ef7ce245cf 100644 --- a/src/bootstrap/src/core/builder/cargo.rs +++ b/src/bootstrap/src/core/builder/cargo.rs @@ -245,7 +245,11 @@ impl Cargo { // flesh out rpath support more fully in the future. self.rustflags.arg("-Zosx-rpath-install-name"); Some(format!("-Wl,-rpath,@loader_path/../{libdir}")) - } else if !target.is_windows() && !target.contains("aix") && !target.contains("xous") { + } else if !target.is_windows() + && !target.contains("cygwin") + && !target.contains("aix") + && !target.contains("xous") + { self.rustflags.arg("-Clink-args=-Wl,-z,origin"); Some(format!("-Wl,-rpath,$ORIGIN/../{libdir}")) } else { diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md index f78d3d4aee830..6c7cdec348024 100644 --- a/src/doc/rustc/src/SUMMARY.md +++ b/src/doc/rustc/src/SUMMARY.md @@ -102,6 +102,7 @@ - [\*-win7-windows-gnu](platform-support/win7-windows-gnu.md) - [\*-win7-windows-msvc](platform-support/win7-windows-msvc.md) - [x86_64-fortanix-unknown-sgx](platform-support/x86_64-fortanix-unknown-sgx.md) + - [x86_64-pc-cygwin](platform-support/x86_64-pc-cygwin.md) - [x86_64-pc-solaris](platform-support/solaris.md) - [x86_64-unknown-linux-none.md](platform-support/x86_64-unknown-linux-none.md) - [x86_64-unknown-none](platform-support/x86_64-unknown-none.md) diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index bb89d97a7984d..8b0f9f8b22968 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -407,6 +407,7 @@ target | std | host | notes [`wasm64-unknown-unknown`](platform-support/wasm64-unknown-unknown.md) | ? | | WebAssembly [`x86_64-apple-tvos`](platform-support/apple-tvos.md) | ✓ | | x86 64-bit tvOS [`x86_64-apple-watchos-sim`](platform-support/apple-watchos.md) | ✓ | | x86 64-bit Apple WatchOS simulator +[`x86_64-pc-cygwin`](platform-support/x86_64-pc-cygwin.md) | ? | | 64-bit x86 Cygwin | [`x86_64-pc-nto-qnx710`](platform-support/nto-qnx.md) | ✓ | | x86 64-bit QNX Neutrino 7.1 RTOS with default network stack (io-pkt) | [`x86_64-pc-nto-qnx710_iosock`](platform-support/nto-qnx.md) | ✓ | | x86 64-bit QNX Neutrino 7.1 RTOS with new network stack (io-sock) | [`x86_64-pc-nto-qnx800`](platform-support/nto-qnx.md) | ✓ | | x86 64-bit QNX Neutrino 8.0 RTOS | diff --git a/src/doc/rustc/src/platform-support/x86_64-pc-cygwin.md b/src/doc/rustc/src/platform-support/x86_64-pc-cygwin.md new file mode 100644 index 0000000000000..a8fc4f181d8ad --- /dev/null +++ b/src/doc/rustc/src/platform-support/x86_64-pc-cygwin.md @@ -0,0 +1,39 @@ +# `x86_64-pc-cygwin` + +**Tier: 3** + +Windows targets supporting Cygwin. +The `*-cygwin` targets are **not** intended as native target for applications, +a developer writing Windows applications should use the `*-pc-windows-*` targets instead, which are *native* Windows. + +Cygwin is only intended as an emulation layer for Unix-only programs which do not support the native Windows targets. + +## Target maintainers + +- [Berrysoft](https://github.com/Berrysoft) + +## Requirements + +This target is cross compiled. It needs `x86_64-pc-cygwin-gcc` as linker. + +The `target_os` of the target is `cygwin`, and it is `unix`. + +## Building the target + +For cross-compilation you want LLVM with [llvm/llvm-project#121439 (merged)](https://github.com/llvm/llvm-project/pull/121439) applied to fix the LLVM codegen on importing external global variables from DLLs. +No native builds on Cygwin now. It should be possible theoretically though, but might need a lot of patches. + +## 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 + +Created binaries work fine on Windows with Cygwin. + +## Cross-compilation toolchains and C code + +Compatible C code can be built with GCC shipped with Cygwin. Clang is untested. diff --git a/tests/assembly/targets/targets-pe.rs b/tests/assembly/targets/targets-pe.rs index ab74de5c8ec42..1fa4dc821dd37 100644 --- a/tests/assembly/targets/targets-pe.rs +++ b/tests/assembly/targets/targets-pe.rs @@ -84,6 +84,9 @@ //@ revisions: x86_64_win7_windows_msvc //@ [x86_64_win7_windows_msvc] compile-flags: --target x86_64-win7-windows-msvc //@ [x86_64_win7_windows_msvc] needs-llvm-components: x86 +//@ revisions: x86_64_pc_cygwin +//@ [x86_64_pc_cygwin] compile-flags: --target x86_64-pc-cygwin +//@ [x86_64_pc_cygwin] needs-llvm-components: x86 // Sanity-check that each target can produce assembly code. diff --git a/tests/ui/check-cfg/well-known-values.stderr b/tests/ui/check-cfg/well-known-values.stderr index 6421cb8f2c2e7..ba1900fcddb2d 100644 --- a/tests/ui/check-cfg/well-known-values.stderr +++ b/tests/ui/check-cfg/well-known-values.stderr @@ -201,7 +201,7 @@ warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` LL | target_os = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `macos`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `psp`, `psx`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `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`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `macos`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `psp`, `psx`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `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` @@ -274,7 +274,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`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `macos`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `psp`, `psx`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `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`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `macos`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `psp`, `psx`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm` = note: see for more information about checking conditional configuration warning: 28 warnings emitted From 33d0f386f697ecf870df6fade85cf7183931b9da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E5=AE=87=E9=80=B8?= Date: Wed, 5 Feb 2025 09:26:17 +0800 Subject: [PATCH 05/15] Apply suggestions --- compiler/rustc_target/src/spec/base/cygwin.rs | 8 +------- .../src/spec/targets/x86_64_pc_cygwin.rs | 14 +++----------- 2 files changed, 4 insertions(+), 18 deletions(-) diff --git a/compiler/rustc_target/src/spec/base/cygwin.rs b/compiler/rustc_target/src/spec/base/cygwin.rs index 2d29060c47a39..8cb3cceb2d59b 100644 --- a/compiler/rustc_target/src/spec/base/cygwin.rs +++ b/compiler/rustc_target/src/spec/base/cygwin.rs @@ -4,14 +4,10 @@ use crate::spec::{Cc, DebuginfoKind, LinkerFlavor, Lld, SplitDebuginfo, TargetOp pub(crate) fn opts() -> TargetOptions { let mut pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - // FIXME: Disable ASLR for now to fix relocation error "--disable-dynamicbase", "--enable-auto-image-base", ]); crate::spec::add_link_args(&mut pre_link_args, LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ - // Tell GCC to avoid linker plugins, because we are not bundling - // them with Windows installer, and Rust does its own LTO anyways. - "-fno-use-linker-plugin", "-Wl,--disable-dynamicbase", "-Wl,--enable-auto-image-base", ]); @@ -42,9 +38,7 @@ pub(crate) fn opts() -> TargetOptions { emit_debug_gdb_scripts: false, requires_uwtable: true, eh_frame_header: false, - // FIXME(davidtwco): Support Split DWARF on Cygwin - may require LLVM changes to - // output DWO, despite using DWARF, doesn't use ELF.. - debuginfo_kind: DebuginfoKind::Pdb, + debuginfo_kind: DebuginfoKind::Dwarf, supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]), ..Default::default() } diff --git a/compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs b/compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs index a5bedd07e6be8..8da4fe6b8b152 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs @@ -3,16 +3,8 @@ use crate::spec::{Cc, LinkerFlavor, Lld, Target, base}; pub(crate) fn target() -> Target { let mut base = base::cygwin::opts(); base.cpu = "x86-64".into(); - // FIXME: Disable ASLR for now to fix relocation error - base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "-m", - "i386pep", - "--disable-high-entropy-va", - ]); - base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ - "-m64", - "-Wl,--disable-high-entropy-va", - ]); + base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &["-m", "i386pep"]); + base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m64"]); base.max_atomic_width = Some(64); base.linker = Some("x86_64-pc-cygwin-gcc".into()); Target { @@ -26,7 +18,7 @@ pub(crate) fn target() -> Target { description: Some("64-bit x86 Cygwin".into()), tier: Some(3), host_tools: Some(false), - std: Some(true), + std: None, }, } } From 8e5207e75c63e2b341e9a38ddd511422c274da5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E5=AE=87=E9=80=B8?= Date: Mon, 10 Feb 2025 17:55:54 +0800 Subject: [PATCH 06/15] Reformat files --- compiler/rustc_target/src/spec/base/cygwin.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_target/src/spec/base/cygwin.rs b/compiler/rustc_target/src/spec/base/cygwin.rs index 8cb3cceb2d59b..fe3efb3f46ba0 100644 --- a/compiler/rustc_target/src/spec/base/cygwin.rs +++ b/compiler/rustc_target/src/spec/base/cygwin.rs @@ -3,14 +3,15 @@ use std::borrow::Cow; use crate::spec::{Cc, DebuginfoKind, LinkerFlavor, Lld, SplitDebuginfo, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { - let mut pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "--disable-dynamicbase", - "--enable-auto-image-base", - ]); - crate::spec::add_link_args(&mut pre_link_args, LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ - "-Wl,--disable-dynamicbase", - "-Wl,--enable-auto-image-base", - ]); + let mut pre_link_args = TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &["--disable-dynamicbase", "--enable-auto-image-base"], + ); + crate::spec::add_link_args( + &mut pre_link_args, + LinkerFlavor::Gnu(Cc::Yes, Lld::No), + &["-Wl,--disable-dynamicbase", "-Wl,--enable-auto-image-base"], + ); let cygwin_libs = &["-lcygwin", "-lgcc", "-lcygwin", "-luser32", "-lkernel32", "-lgcc_s"]; let mut late_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), cygwin_libs); From cde7e805ad48e8766a07c95c2046693c6a6e236c Mon Sep 17 00:00:00 2001 From: Flakebi Date: Mon, 10 Feb 2025 21:38:44 +0100 Subject: [PATCH 07/15] Cast allocas to default address space Pointers for variables all need to be in the same address space for correct compilation. Therefore ensure that even if an `alloca` is created in a different address space, it is casted to the default address space before its value is used. This is necessary for the amdgpu target and others where the default address space for `alloca`s is not 0. For example the following code compiles incorrectly when not casting the address space to the default one: ```rust fn f(p: *const i8 /* addrspace(0) */) -> *const i8 /* addrspace(0) */ { let local = 0i8; /* addrspace(5) */ let res = if cond { p } else { &raw const local }; res } ``` results in ```llvm %local = alloca addrspace(5) i8 %res = alloca addrspace(5) ptr if: ; Store 64-bit flat pointer store ptr %p, ptr addrspace(5) %res else: ; Store 32-bit scratch pointer store ptr addrspace(5) %local, ptr addrspace(5) %res ret: ; Load and return 64-bit flat pointer %res.load = load ptr, ptr addrspace(5) %res ret ptr %res.load ``` For amdgpu, `addrspace(0)` are 64-bit pointers, `addrspace(5)` are 32-bit pointers. The above code may store a 32-bit pointer and read it back as a 64-bit pointer, which is obviously wrong and cannot work. Instead, we need to `addrspacecast %local to ptr addrspace(0)`, then we store and load the correct type. --- compiler/rustc_codegen_llvm/src/builder.rs | 6 ++++-- tests/codegen/amdgpu-addrspacecast.rs | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 tests/codegen/amdgpu-addrspacecast.rs diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index ab0e43e60a4f5..fbeedef314dfb 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -421,7 +421,8 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { unsafe { let alloca = llvm::LLVMBuildAlloca(bx.llbuilder, ty, UNNAMED); llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint); - alloca + // Cast to default addrspace if necessary + llvm::LLVMBuildPointerCast(bx.llbuilder, alloca, self.cx().type_ptr(), UNNAMED) } } @@ -430,7 +431,8 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { let alloca = llvm::LLVMBuildArrayAlloca(self.llbuilder, self.cx().type_i8(), size, UNNAMED); llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint); - alloca + // Cast to default addrspace if necessary + llvm::LLVMBuildPointerCast(self.llbuilder, alloca, self.cx().type_ptr(), UNNAMED) } } diff --git a/tests/codegen/amdgpu-addrspacecast.rs b/tests/codegen/amdgpu-addrspacecast.rs new file mode 100644 index 0000000000000..7fe630a7efa0e --- /dev/null +++ b/tests/codegen/amdgpu-addrspacecast.rs @@ -0,0 +1,18 @@ +// Check that pointers are casted to addrspace(0) before they are used + +//@ compile-flags: --crate-type=rlib --target=amdgcn-amd-amdhsa -Ctarget-cpu=gfx900 +//@ needs-llvm-components: amdgpu +//@ add-core-stubs +#![feature(no_core)] +#![no_core] + +extern crate minicore; + +// CHECK-LABEL: @ref_of_local +// CHECK: [[alloca:%[0-9]]] = alloca +// CHECK: %i = addrspacecast ptr addrspace(5) [[alloca]] to ptr +#[no_mangle] +pub fn ref_of_local(f: fn(&i32)) { + let i = 0; + f(&i); +} From 5c907c19eda799db3105767c9fcaea3da5c38c1a Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 29 Jan 2025 12:23:15 +0100 Subject: [PATCH 08/15] x86-sse2 ABI: use SSE registers for floats and SIMD --- compiler/rustc_target/src/callconv/mod.rs | 118 +++++++++++------- compiler/rustc_target/src/callconv/x86.rs | 14 ++- .../closure-inherit-target-feature.rs | 3 +- tests/assembly/x86-return-float.rs | 111 ++++++++-------- tests/codegen/abi-x86-sse.rs | 36 ++++++ tests/codegen/intrinsics/transmute-x64.rs | 7 +- .../simd-intrinsic-transmute-array.rs | 17 ++- tests/codegen/simd/packed-simd.rs | 25 ++-- ...e-abi-checks.rs => sse-simd-abi-checks.rs} | 5 +- ...ecks.stderr => sse-simd-abi-checks.stderr} | 4 +- 10 files changed, 218 insertions(+), 122 deletions(-) create mode 100644 tests/codegen/abi-x86-sse.rs rename tests/ui/{sse-abi-checks.rs => sse-simd-abi-checks.rs} (82%) rename tests/ui/{sse-abi-checks.stderr => sse-simd-abi-checks.stderr} (94%) diff --git a/compiler/rustc_target/src/callconv/mod.rs b/compiler/rustc_target/src/callconv/mod.rs index 50ac6c8fcde16..548fb7913650d 100644 --- a/compiler/rustc_target/src/callconv/mod.rs +++ b/compiler/rustc_target/src/callconv/mod.rs @@ -8,7 +8,7 @@ use rustc_abi::{ use rustc_macros::HashStable_Generic; use rustc_span::Symbol; -use crate::spec::{HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, WasmCAbi}; +use crate::spec::{HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, RustcAbi, WasmCAbi}; mod aarch64; mod amdgpu; @@ -387,6 +387,7 @@ impl<'a, Ty> ArgAbi<'a, Ty> { /// Pass this argument directly instead. Should NOT be used! /// Only exists because of past ABI mistakes that will take time to fix /// (see ). + #[track_caller] pub fn make_direct_deprecated(&mut self) { match self.mode { PassMode::Indirect { .. } => { @@ -399,6 +400,7 @@ impl<'a, Ty> ArgAbi<'a, Ty> { /// Pass this argument indirectly, by passing a (thin or wide) pointer to the argument instead. /// This is valid for both sized and unsized arguments. + #[track_caller] pub fn make_indirect(&mut self) { match self.mode { PassMode::Direct(_) | PassMode::Pair(_, _) => { @@ -413,6 +415,7 @@ impl<'a, Ty> ArgAbi<'a, Ty> { /// Same as `make_indirect`, but for arguments that are ignored. Only needed for ABIs that pass /// ZSTs indirectly. + #[track_caller] pub fn make_indirect_from_ignore(&mut self) { match self.mode { PassMode::Ignore => { @@ -736,7 +739,7 @@ impl<'a, Ty> FnAbi<'a, Ty> { C: HasDataLayout + HasTargetSpec, { let spec = cx.target_spec(); - match &spec.arch[..] { + match &*spec.arch { "x86" => x86::compute_rust_abi_info(cx, self, abi), "riscv32" | "riscv64" => riscv::compute_rust_abi_info(cx, self, abi), "loongarch64" => loongarch::compute_rust_abi_info(cx, self, abi), @@ -744,6 +747,22 @@ impl<'a, Ty> FnAbi<'a, Ty> { _ => {} }; + // Decides whether we can pass the given SIMD argument via `PassMode::Direct`. + // May only return `true` if the target will always pass those arguments the same way, + // no matter what the user does with `-Ctarget-feature`! In other words, whatever + // target features are required to pass a SIMD value in registers must be listed in + // the `abi_required_features` for the current target and ABI. + let can_pass_simd_directly = |arg: &ArgAbi<'_, Ty>| match &*spec.arch { + // On x86, if we have SSE2 (which we have by default for x86_64), we can always pass up + // to 128-bit-sized vectors. + "x86" if spec.rustc_abi == Some(RustcAbi::X86Sse2) => arg.layout.size.bits() <= 128, + "x86_64" if spec.rustc_abi != Some(RustcAbi::X86Softfloat) => { + arg.layout.size.bits() <= 128 + } + // So far, we haven't implemented this logic for any other target. + _ => false, + }; + for (arg_idx, arg) in self .args .iter_mut() @@ -751,12 +770,15 @@ impl<'a, Ty> FnAbi<'a, Ty> { .map(|(idx, arg)| (Some(idx), arg)) .chain(iter::once((None, &mut self.ret))) { - if arg.is_ignore() { + // If the logic above already picked a specific type to cast the argument to, leave that + // in place. + if matches!(arg.mode, PassMode::Ignore | PassMode::Cast { .. }) { continue; } if arg_idx.is_none() && arg.layout.size > Primitive::Pointer(AddressSpace::DATA).size(cx) * 2 + && !matches!(arg.layout.backend_repr, BackendRepr::Vector { .. }) { // Return values larger than 2 registers using a return area // pointer. LLVM and Cranelift disagree about how to return @@ -766,7 +788,8 @@ impl<'a, Ty> FnAbi<'a, Ty> { // return value independently and decide to pass it in a // register or not, which would result in the return value // being passed partially in registers and partially through a - // return area pointer. + // return area pointer. For large IR-level values such as `i128`, + // cranelift will even split up the value into smaller chunks. // // While Cranelift may need to be fixed as the LLVM behavior is // generally more correct with respect to the surface language, @@ -796,53 +819,60 @@ impl<'a, Ty> FnAbi<'a, Ty> { // rustc_target already ensure any return value which doesn't // fit in the available amount of return registers is passed in // the right way for the current target. + // + // The adjustment is not necessary nor desired for types with a vector + // representation; those are handled below. arg.make_indirect(); continue; } match arg.layout.backend_repr { - BackendRepr::Memory { .. } => {} - - // This is a fun case! The gist of what this is doing is - // that we want callers and callees to always agree on the - // ABI of how they pass SIMD arguments. If we were to *not* - // make these arguments indirect then they'd be immediates - // in LLVM, which means that they'd used whatever the - // appropriate ABI is for the callee and the caller. That - // means, for example, if the caller doesn't have AVX - // enabled but the callee does, then passing an AVX argument - // across this boundary would cause corrupt data to show up. - // - // This problem is fixed by unconditionally passing SIMD - // arguments through memory between callers and callees - // which should get them all to agree on ABI regardless of - // target feature sets. Some more information about this - // issue can be found in #44367. - // - // Note that the intrinsic ABI is exempt here as - // that's how we connect up to LLVM and it's unstable - // anyway, we control all calls to it in libstd. - BackendRepr::Vector { .. } - if abi != ExternAbi::RustIntrinsic && spec.simd_types_indirect => - { - arg.make_indirect(); - continue; + BackendRepr::Memory { .. } => { + // Compute `Aggregate` ABI. + + let is_indirect_not_on_stack = + matches!(arg.mode, PassMode::Indirect { on_stack: false, .. }); + assert!(is_indirect_not_on_stack); + + let size = arg.layout.size; + if arg.layout.is_sized() + && size <= Primitive::Pointer(AddressSpace::DATA).size(cx) + { + // We want to pass small aggregates as immediates, but using + // an LLVM aggregate type for this leads to bad optimizations, + // so we pick an appropriately sized integer type instead. + arg.cast_to(Reg { kind: RegKind::Integer, size }); + } } - _ => continue, - } - // Compute `Aggregate` ABI. - - let is_indirect_not_on_stack = - matches!(arg.mode, PassMode::Indirect { on_stack: false, .. }); - assert!(is_indirect_not_on_stack); - - let size = arg.layout.size; - if !arg.layout.is_unsized() && size <= Primitive::Pointer(AddressSpace::DATA).size(cx) { - // We want to pass small aggregates as immediates, but using - // an LLVM aggregate type for this leads to bad optimizations, - // so we pick an appropriately sized integer type instead. - arg.cast_to(Reg { kind: RegKind::Integer, size }); + BackendRepr::Vector { .. } => { + // This is a fun case! The gist of what this is doing is + // that we want callers and callees to always agree on the + // ABI of how they pass SIMD arguments. If we were to *not* + // make these arguments indirect then they'd be immediates + // in LLVM, which means that they'd used whatever the + // appropriate ABI is for the callee and the caller. That + // means, for example, if the caller doesn't have AVX + // enabled but the callee does, then passing an AVX argument + // across this boundary would cause corrupt data to show up. + // + // This problem is fixed by unconditionally passing SIMD + // arguments through memory between callers and callees + // which should get them all to agree on ABI regardless of + // target feature sets. Some more information about this + // issue can be found in #44367. + // + // Note that the intrinsic ABI is exempt here as those are not + // real functions anyway, and the backend expects very specific types. + if abi != ExternAbi::RustIntrinsic + && spec.simd_types_indirect + && !can_pass_simd_directly(arg) + { + arg.make_indirect(); + } + } + + _ => {} } } } diff --git a/compiler/rustc_target/src/callconv/x86.rs b/compiler/rustc_target/src/callconv/x86.rs index 5b9414536d8ca..5f4f4cd57f654 100644 --- a/compiler/rustc_target/src/callconv/x86.rs +++ b/compiler/rustc_target/src/callconv/x86.rs @@ -4,7 +4,7 @@ use rustc_abi::{ }; use crate::callconv::{ArgAttribute, FnAbi, PassMode}; -use crate::spec::HasTargetSpec; +use crate::spec::{HasTargetSpec, RustcAbi}; #[derive(PartialEq)] pub(crate) enum Flavor { @@ -236,8 +236,16 @@ where _ => false, // anyway not passed via registers on x86 }; if has_float { - if fn_abi.ret.layout.size <= Primitive::Pointer(AddressSpace::DATA).size(cx) { - // Same size or smaller than pointer, return in a register. + if cx.target_spec().rustc_abi == Some(RustcAbi::X86Sse2) + && fn_abi.ret.layout.backend_repr.is_scalar() + && fn_abi.ret.layout.size.bits() <= 128 + { + // This is a single scalar that fits into an SSE register, and the target uses the + // SSE ABI. We prefer this over integer registers as float scalars need to be in SSE + // registers for float operations, so that's the best place to pass them around. + fn_abi.ret.cast_to(Reg { kind: RegKind::Vector, size: fn_abi.ret.layout.size }); + } else if fn_abi.ret.layout.size <= Primitive::Pointer(AddressSpace::DATA).size(cx) { + // Same size or smaller than pointer, return in an integer register. fn_abi.ret.cast_to(Reg { kind: RegKind::Integer, size: fn_abi.ret.layout.size }); } else { // Larger than a pointer, return indirectly. diff --git a/tests/assembly/closure-inherit-target-feature.rs b/tests/assembly/closure-inherit-target-feature.rs index 4692653d91fc6..9f73820f0ea1f 100644 --- a/tests/assembly/closure-inherit-target-feature.rs +++ b/tests/assembly/closure-inherit-target-feature.rs @@ -15,9 +15,8 @@ pub unsafe fn sse41_blend_nofeature(x: __m128, y: __m128) -> __m128 { // check that _mm_blend_ps is not being inlined into the closure // CHECK-LABEL: {{sse41_blend_nofeature.*closure.*:}} // CHECK-NOT: blendps - // CHECK: {{call .*_mm_blend_ps.*}} + // CHECK: {{jmp .*_mm_blend_ps.*}} // CHECK-NOT: blendps - // CHECK: ret #[inline(never)] |x, y| _mm_blend_ps(x, y, 0b0101) }; diff --git a/tests/assembly/x86-return-float.rs b/tests/assembly/x86-return-float.rs index acd1af8d38af1..0802116bf61d1 100644 --- a/tests/assembly/x86-return-float.rs +++ b/tests/assembly/x86-return-float.rs @@ -1,19 +1,31 @@ //@ assembly-output: emit-asm -//@ only-x86 -// FIXME(#114479): LLVM miscompiles loading and storing `f32` and `f64` when SSE is disabled. -// There's no compiletest directive to ignore a test on i586 only, so just always explicitly enable -// SSE2. -// Use the same target CPU as `i686` so that LLVM orders the instructions in the same order. -//@ compile-flags: -Ctarget-feature=+sse2 -Ctarget-cpu=pentium4 +//@ revisions: sse nosse +//@[sse] compile-flags: --target i686-unknown-linux-gnu +//@[sse] needs-llvm-components: x86 +// We make SSE available but don't use it for the ABI. +//@[nosse] compile-flags: --target i586-unknown-linux-gnu -Ctarget-feature=+sse2 -Ctarget-cpu=pentium4 +//@[nosse] needs-llvm-components: x86 + // Force frame pointers to make ASM more consistent between targets //@ compile-flags: -O -C force-frame-pointers //@ filecheck-flags: --implicit-check-not fld --implicit-check-not fst -//@ revisions: normal win -//@[normal] ignore-windows -//@[win] only-windows -#![crate_type = "lib"] #![feature(f16, f128)] +#![feature(no_core, lang_items, rustc_attrs, repr_simd)] +#![no_core] +#![crate_type = "lib"] + +#[lang = "sized"] +trait Sized {} + +#[lang = "copy"] +trait Copy {} + +impl Copy for f16 {} +impl Copy for f32 {} +impl Copy for f64 {} +impl Copy for f128 {} +impl Copy for usize {} // Tests that returning `f32` and `f64` with the "Rust" ABI on 32-bit x86 doesn't use the x87 // floating point stack, as loading and storing `f32`s and `f64`s to and from the x87 stack quietens @@ -24,7 +36,8 @@ // CHECK-LABEL: return_f32: #[no_mangle] pub fn return_f32(x: f32) -> f32 { - // CHECK: movl {{.*}}(%ebp), %eax + // sse: movss {{.*}}(%ebp), %xmm0 + // nosse: movl {{.*}}(%ebp), %eax // CHECK-NOT: ax // CHECK: retl x @@ -33,9 +46,11 @@ pub fn return_f32(x: f32) -> f32 { // CHECK-LABEL: return_f64: #[no_mangle] pub fn return_f64(x: f64) -> f64 { - // CHECK: movl [[#%d,OFFSET:]](%ebp), %[[PTR:.*]] - // CHECK-NEXT: movsd [[#%d,OFFSET+4]](%ebp), %[[VAL:.*]] - // CHECK-NEXT: movsd %[[VAL]], (%[[PTR]]) + // nosse: movl [[#%d,OFFSET:]](%ebp), %[[PTR:.*]] + // nosse-NEXT: movsd [[#%d,OFFSET+4]](%ebp), %[[VAL:.*]] + // nosse-NEXT: movsd %[[VAL]], (%[[PTR]]) + // sse: movsd {{.*}}(%ebp), %xmm0 + // sse-NOT: ax // CHECK: retl x } @@ -148,7 +163,8 @@ pub unsafe fn call_f32(x: &mut f32) { } // CHECK: movl {{.*}}(%ebp), %[[PTR:.*]] // CHECK: calll {{()|_}}get_f32 - // CHECK-NEXT: movl %eax, (%[[PTR]]) + // sse-NEXT: movss %xmm0, (%[[PTR]]) + // nosse-NEXT: movl %eax, (%[[PTR]]) *x = get_f32(); } @@ -160,8 +176,9 @@ pub unsafe fn call_f64(x: &mut f64) { } // CHECK: movl {{.*}}(%ebp), %[[PTR:.*]] // CHECK: calll {{()|_}}get_f64 - // CHECK: movsd {{.*}}(%{{ebp|esp}}), %[[VAL:.*]] - // CHECK-NEXT: movsd %[[VAL:.*]], (%[[PTR]]) + // sse: movlps %xmm0, (%[[PTR]]) + // nosse: movsd {{.*}}(%{{ebp|esp}}), %[[VAL:.*]] + // nosse-NEXT: movsd %[[VAL:.*]], (%[[PTR]]) *x = get_f64(); } @@ -190,10 +207,8 @@ pub unsafe fn call_f64_f64(x: &mut (f64, f64)) { } // CHECK: movl {{.*}}(%ebp), %[[PTR:.*]] // CHECK: calll {{()|_}}get_f64_f64 - // normal: movsd [[#%d,OFFSET:]](%ebp), %[[VAL1:.*]] - // normal-NEXT: movsd [[#%d,OFFSET+8]](%ebp), %[[VAL2:.*]] - // win: movsd (%esp), %[[VAL1:.*]] - // win-NEXT: movsd 8(%esp), %[[VAL2:.*]] + // CHECK: movsd [[#%d,OFFSET:]](%ebp), %[[VAL1:.*]] + // CHECK-NEXT: movsd [[#%d,OFFSET+8]](%ebp), %[[VAL2:.*]] // CHECK-NEXT: movsd %[[VAL1]], (%[[PTR]]) // CHECK-NEXT: movsd %[[VAL2]], 8(%[[PTR]]) *x = get_f64_f64(); @@ -207,13 +222,10 @@ pub unsafe fn call_f32_f64(x: &mut (f32, f64)) { } // CHECK: movl {{.*}}(%ebp), %[[PTR:.*]] // CHECK: calll {{()|_}}get_f32_f64 - // normal: movss [[#%d,OFFSET:]](%ebp), %[[VAL1:.*]] - // normal-NEXT: movsd [[#%d,OFFSET+4]](%ebp), %[[VAL2:.*]] - // win: movss (%esp), %[[VAL1:.*]] - // win-NEXT: movsd 8(%esp), %[[VAL2:.*]] + // CHECK: movss [[#%d,OFFSET:]](%ebp), %[[VAL1:.*]] + // CHECK-NEXT: movsd [[#%d,OFFSET+4]](%ebp), %[[VAL2:.*]] // CHECK-NEXT: movss %[[VAL1]], (%[[PTR]]) - // normal-NEXT: movsd %[[VAL2]], 4(%[[PTR]]) - // win-NEXT: movsd %[[VAL2]], 8(%[[PTR]]) + // CHECK-NEXT: movsd %[[VAL2]], 4(%[[PTR]]) *x = get_f32_f64(); } @@ -225,10 +237,8 @@ pub unsafe fn call_f64_f32(x: &mut (f64, f32)) { } // CHECK: movl {{.*}}(%ebp), %[[PTR:.*]] // CHECK: calll {{()|_}}get_f64_f32 - // normal: movsd [[#%d,OFFSET:]](%ebp), %[[VAL1:.*]] - // normal-NEXT: movss [[#%d,OFFSET+8]](%ebp), %[[VAL2:.*]] - // win: movsd (%esp), %[[VAL1:.*]] - // win-NEXT: movss 8(%esp), %[[VAL2:.*]] + // CHECK: movsd [[#%d,OFFSET:]](%ebp), %[[VAL1:.*]] + // CHECK-NEXT: movss [[#%d,OFFSET+8]](%ebp), %[[VAL2:.*]] // CHECK-NEXT: movsd %[[VAL1]], (%[[PTR]]) // CHECK-NEXT: movss %[[VAL2]], 8(%[[PTR]]) *x = get_f64_f32(); @@ -257,10 +267,8 @@ pub unsafe fn call_f64_other(x: &mut (f64, usize)) { } // CHECK: movl {{.*}}(%ebp), %[[PTR:.*]] // CHECK: calll {{()|_}}get_f64_other - // normal: movsd [[#%d,OFFSET:]](%ebp), %[[VAL1:.*]] - // normal-NEXT: movl [[#%d,OFFSET+8]](%ebp), %[[VAL2:.*]] - // win: movsd (%esp), %[[VAL1:.*]] - // win-NEXT: movl 8(%esp), %[[VAL2:.*]] + // CHECK: movsd [[#%d,OFFSET:]](%ebp), %[[VAL1:.*]] + // CHECK-NEXT: movl [[#%d,OFFSET+8]](%ebp), %[[VAL2:.*]] // CHECK-NEXT: movsd %[[VAL1]], (%[[PTR]]) // CHECK-NEXT: movl %[[VAL2]], 8(%[[PTR]]) *x = get_f64_other(); @@ -289,13 +297,10 @@ pub unsafe fn call_other_f64(x: &mut (usize, f64)) { } // CHECK: movl {{.*}}(%ebp), %[[PTR:.*]] // CHECK: calll {{()|_}}get_other_f64 - // normal: movl [[#%d,OFFSET:]](%ebp), %[[VAL1:.*]] - // normal-NEXT: movsd [[#%d,OFFSET+4]](%ebp), %[[VAL2:.*]] - // win: movl (%esp), %[[VAL1:.*]] - // win-NEXT: movsd 8(%esp), %[[VAL2:.*]] + // CHECK: movl [[#%d,OFFSET:]](%ebp), %[[VAL1:.*]] + // CHECK-NEXT: movsd [[#%d,OFFSET+4]](%ebp), %[[VAL2:.*]] // CHECK-NEXT: movl %[[VAL1]], (%[[PTR]]) - // normal-NEXT: movsd %[[VAL2]], 4(%[[PTR]]) - // win-NEXT: movsd %[[VAL2]], 8(%[[PTR]]) + // CHECK-NEXT: movsd %[[VAL2]], 4(%[[PTR]]) *x = get_other_f64(); } @@ -307,7 +312,8 @@ pub unsafe fn call_other_f64(x: &mut (usize, f64)) { pub fn return_f16(x: f16) -> f16 { // CHECK: pushl %ebp // CHECK: movl %esp, %ebp - // CHECK: movzwl 8(%ebp), %eax + // nosse: movzwl 8(%ebp), %eax + // sse: pinsrw $0, 8(%ebp), %xmm0 // CHECK: popl %ebp // CHECK: retl x @@ -316,15 +322,18 @@ pub fn return_f16(x: f16) -> f16 { // CHECK-LABEL: return_f128: #[no_mangle] pub fn return_f128(x: f128) -> f128 { - // CHECK: movl [[#%d,OFFSET:]](%ebp), %[[PTR:.*]] - // CHECK-NEXT: movl [[#%d,OFFSET+4]](%ebp), %[[VAL1:.*]] - // CHECK-NEXT: movl [[#%d,OFFSET+8]](%ebp), %[[VAL2:.*]] - // CHECK-NEXT: movl [[#%d,OFFSET+12]](%ebp), %[[VAL3:.*]] - // CHECK-NEXT: movl [[#%d,OFFSET+16]](%ebp), %[[VAL4:.*]] - // CHECK-NEXT: movl %[[VAL4:.*]] 12(%[[PTR]]) - // CHECK-NEXT: movl %[[VAL3:.*]] 8(%[[PTR]]) - // CHECK-NEXT: movl %[[VAL2:.*]] 4(%[[PTR]]) - // CHECK-NEXT: movl %[[VAL1:.*]] (%[[PTR]]) + // CHECK: pushl %ebp + // sse: movaps [[#%d,OFFSET:]](%ebp), %xmm0 + // nosse: movl [[#%d,OFFSET:]](%ebp), %[[PTR:.*]] + // nosse-NEXT: movl [[#%d,OFFSET+4]](%ebp), %[[VAL1:.*]] + // nosse-NEXT: movl [[#%d,OFFSET+8]](%ebp), %[[VAL2:.*]] + // nosse-NEXT: movl [[#%d,OFFSET+12]](%ebp), %[[VAL3:.*]] + // nosse-NEXT: movl [[#%d,OFFSET+16]](%ebp), %[[VAL4:.*]] + // nosse-NEXT: movl %[[VAL4:.*]] 12(%[[PTR]]) + // nosse-NEXT: movl %[[VAL3:.*]] 8(%[[PTR]]) + // nosse-NEXT: movl %[[VAL2:.*]] 4(%[[PTR]]) + // nosse-NEXT: movl %[[VAL1:.*]] (%[[PTR]]) + // CHECK: popl %ebp // CHECK: retl x } diff --git a/tests/codegen/abi-x86-sse.rs b/tests/codegen/abi-x86-sse.rs new file mode 100644 index 0000000000000..6a0f3dd18d472 --- /dev/null +++ b/tests/codegen/abi-x86-sse.rs @@ -0,0 +1,36 @@ +//@ compile-flags: -Z merge-functions=disabled + +//@ revisions: x86-64 +//@[x86-64] compile-flags: --target x86_64-unknown-linux-gnu +//@[x86-64] needs-llvm-components: x86 + +//@ revisions: x86-32 +//@[x86-32] compile-flags: --target i686-unknown-linux-gnu +//@[x86-32] needs-llvm-components: x86 + +//@ revisions: x86-32-nosse +//@[x86-32-nosse] compile-flags: --target i586-unknown-linux-gnu +//@[x86-32-nosse] needs-llvm-components: x86 + +#![feature(no_core, lang_items, rustc_attrs, repr_simd)] +#![no_core] +#![crate_type = "lib"] + +#[lang = "sized"] +trait Sized {} + +#[lang = "copy"] +trait Copy {} + +// Ensure this type is passed without ptr indirection on targets that +// require SSE2. +#[repr(simd)] +pub struct Sse([f32; 4]); + +// x86-64: <4 x float> @sse_id(<4 x float> {{[^,]*}}) +// x86-32: <4 x float> @sse_id(<4 x float> {{[^,]*}}) +// x86-32-nosse: void @sse_id(ptr {{[^,]*}} sret{{[^,]*}}, ptr {{[^,]*}}) +#[no_mangle] +pub fn sse_id(x: Sse) -> Sse { + x +} diff --git a/tests/codegen/intrinsics/transmute-x64.rs b/tests/codegen/intrinsics/transmute-x64.rs index ea1c6b0e7e801..5744c42999975 100644 --- a/tests/codegen/intrinsics/transmute-x64.rs +++ b/tests/codegen/intrinsics/transmute-x64.rs @@ -9,9 +9,10 @@ use std::mem::transmute; // CHECK-LABEL: @check_sse_float_to_int( #[no_mangle] pub unsafe fn check_sse_float_to_int(x: __m128) -> __m128i { - // CHECK-NOT: alloca - // CHECK: %0 = load <4 x float>, ptr %x, align 16 - // CHECK: store <4 x float> %0, ptr %_0, align 16 + // FIXME: the MIR opt still works, but the ABI logic now introduces + // an alloca here. + // CHECK: alloca + // CHECK: store <4 x float> %x, ptr %_0, align 16 transmute(x) } diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-transmute-array.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-transmute-array.rs index 75f989d6e12c4..14b31e3da0411 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-transmute-array.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-transmute-array.rs @@ -1,5 +1,14 @@ // //@ compile-flags: -C no-prepopulate-passes +// LLVM IR isn't very portable and the one tested here depends on the ABI +// which is different between x86 (where we use SSE registers) and others +//@ revisions: x86-32 x86-64 other +// The two x86 revisions are identical. Ideally we would say "x86-32 or x86-64" in a single revision +// but compiletest does not permit that. +//@[x86-32] only-x86 +//@[x86-64] only-x86_64 +//@[other] ignore-x86 +//@[other] ignore-x86_64 #![crate_type = "lib"] #![allow(non_camel_case_types)] @@ -38,7 +47,9 @@ pub fn build_array_s(x: [f32; 4]) -> S<4> { #[no_mangle] pub fn build_array_transmute_s(x: [f32; 4]) -> S<4> { // CHECK: %[[VAL:.+]] = load <4 x float>, ptr %x, align [[ARRAY_ALIGN]] - // CHECK: store <4 x float> %[[VAL:.+]], ptr %_0, align [[VECTOR_ALIGN]] + // x86-32: ret <4 x float> %[[VAL:.+]] + // x86-64: ret <4 x float> %[[VAL:.+]] + // other: store <4 x float> %[[VAL:.+]], ptr %_0, align [[VECTOR_ALIGN]] unsafe { std::mem::transmute(x) } } @@ -53,6 +64,8 @@ pub fn build_array_t(x: [f32; 4]) -> T { #[no_mangle] pub fn build_array_transmute_t(x: [f32; 4]) -> T { // CHECK: %[[VAL:.+]] = load <4 x float>, ptr %x, align [[ARRAY_ALIGN]] - // CHECK: store <4 x float> %[[VAL:.+]], ptr %_0, align [[VECTOR_ALIGN]] + // x86-32: ret <4 x float> %[[VAL:.+]] + // x86-64: ret <4 x float> %[[VAL:.+]] + // other: store <4 x float> %[[VAL:.+]], ptr %_0, align [[VECTOR_ALIGN]] unsafe { std::mem::transmute(x) } } diff --git a/tests/codegen/simd/packed-simd.rs b/tests/codegen/simd/packed-simd.rs index 1df09c96e6cc0..a27d5e3af452a 100644 --- a/tests/codegen/simd/packed-simd.rs +++ b/tests/codegen/simd/packed-simd.rs @@ -1,4 +1,5 @@ //@ revisions:opt3 noopt +//@ only-x86_64 //@[opt3] compile-flags: -Copt-level=3 //@[noopt] compile-flags: -Cno-prepopulate-passes @@ -14,14 +15,14 @@ use core::{mem, ptr}; #[repr(simd, packed)] #[derive(Copy, Clone)] -pub struct Simd([T; N]); +pub struct PackedSimd([T; N]); #[repr(simd)] #[derive(Copy, Clone)] pub struct FullSimd([T; N]); // non-powers-of-two have padding and need to be expanded to full vectors -fn load(v: Simd) -> FullSimd { +fn load(v: PackedSimd) -> FullSimd { unsafe { let mut tmp = mem::MaybeUninit::>::uninit(); ptr::copy_nonoverlapping(&v as *const _, tmp.as_mut_ptr().cast(), 1); @@ -29,18 +30,16 @@ fn load(v: Simd) -> FullSimd { } } -// CHECK-LABEL: square_packed_full -// CHECK-SAME: ptr{{[a-z_ ]*}} sret([[RET_TYPE:[^)]+]]) [[RET_ALIGN:align (8|16)]]{{[^%]*}} [[RET_VREG:%[_0-9]*]] -// CHECK-SAME: ptr{{[a-z_ ]*}} align 4 +// CHECK-LABEL: define <3 x float> @square_packed_full(ptr{{[a-z_ ]*}} align 4 {{[^,]*}}) #[no_mangle] -pub fn square_packed_full(x: Simd) -> FullSimd { - // CHECK-NEXT: start - // noopt: alloca [[RET_TYPE]], [[RET_ALIGN]] - // CHECK: load <3 x float> +pub fn square_packed_full(x: PackedSimd) -> FullSimd { + // The unoptimized version of this is not very interesting to check + // since `load` does not get inlined. + // opt3-NEXT: start: + // opt3-NEXT: load <3 x float> let x = load(x); - // CHECK: [[VREG:%[a-z0-9_]+]] = fmul <3 x float> - // CHECK-NEXT: store <3 x float> [[VREG]], ptr [[RET_VREG]], [[RET_ALIGN]] - // CHECK-NEXT: ret void + // opt3-NEXT: [[VREG:%[a-z0-9_]+]] = fmul <3 x float> + // opt3-NEXT: ret <3 x float> [[VREG:%[a-z0-9_]+]] unsafe { intrinsics::simd_mul(x, x) } } @@ -48,7 +47,7 @@ pub fn square_packed_full(x: Simd) -> FullSimd { // CHECK-SAME: ptr{{[a-z_ ]*}} sret([[RET_TYPE:[^)]+]]) [[RET_ALIGN:align 4]]{{[^%]*}} [[RET_VREG:%[_0-9]*]] // CHECK-SAME: ptr{{[a-z_ ]*}} align 4 #[no_mangle] -pub fn square_packed(x: Simd) -> Simd { +pub fn square_packed(x: PackedSimd) -> PackedSimd { // CHECK-NEXT: start // CHECK-NEXT: load <3 x float> // noopt-NEXT: load <3 x float> diff --git a/tests/ui/sse-abi-checks.rs b/tests/ui/sse-simd-abi-checks.rs similarity index 82% rename from tests/ui/sse-abi-checks.rs rename to tests/ui/sse-simd-abi-checks.rs index d400e6eb698e9..6b4e4afee348a 100644 --- a/tests/ui/sse-abi-checks.rs +++ b/tests/ui/sse-simd-abi-checks.rs @@ -1,6 +1,7 @@ //! Ensure we trigger abi_unsupported_vector_types for target features that are usually enabled -//! on a target, but disabled in this file via a `-C` flag. -//@ compile-flags: --crate-type=rlib --target=i586-unknown-linux-gnu -C target-feature=-sse,-sse2 +//! on a target via the base CPU, but disabled in this file via a `-C` flag. +//@ compile-flags: --crate-type=rlib --target=i586-unknown-linux-gnu +//@ compile-flags: -Ctarget-cpu=pentium4 -C target-feature=-sse,-sse2 //@ build-pass //@ ignore-pass (test emits codegen-time warnings) //@ needs-llvm-components: x86 diff --git a/tests/ui/sse-abi-checks.stderr b/tests/ui/sse-simd-abi-checks.stderr similarity index 94% rename from tests/ui/sse-abi-checks.stderr rename to tests/ui/sse-simd-abi-checks.stderr index e08b2d4e19179..f777d341b5343 100644 --- a/tests/ui/sse-abi-checks.stderr +++ b/tests/ui/sse-simd-abi-checks.stderr @@ -1,5 +1,5 @@ warning: this function definition uses a SIMD vector type that (with the chosen ABI) requires the `sse` target feature, which is not enabled - --> $DIR/sse-abi-checks.rs:21:1 + --> $DIR/sse-simd-abi-checks.rs:22:1 | LL | pub unsafe extern "C" fn f(_: SseVector) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function defined here @@ -13,7 +13,7 @@ warning: 1 warning emitted Future incompatibility report: Future breakage diagnostic: warning: this function definition uses a SIMD vector type that (with the chosen ABI) requires the `sse` target feature, which is not enabled - --> $DIR/sse-abi-checks.rs:21:1 + --> $DIR/sse-simd-abi-checks.rs:22:1 | LL | pub unsafe extern "C" fn f(_: SseVector) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function defined here From 644c6948d01c66b744d8d7b8d06ea131a75e8311 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Fri, 24 Jan 2025 15:57:13 +0000 Subject: [PATCH 09/15] Add ffi tests for pattern types --- tests/ui/lint/clashing-extern-fn.rs | 41 ++++++++- tests/ui/lint/clashing-extern-fn.stderr | 116 +++++++++++++++++++++++- tests/ui/lint/lint-ctypes-enum.rs | 1 + tests/ui/lint/lint-ctypes-enum.stderr | 49 ++++++---- 4 files changed, 185 insertions(+), 22 deletions(-) diff --git a/tests/ui/lint/clashing-extern-fn.rs b/tests/ui/lint/clashing-extern-fn.rs index 9bbb20246df9d..0464299348bdb 100644 --- a/tests/ui/lint/clashing-extern-fn.rs +++ b/tests/ui/lint/clashing-extern-fn.rs @@ -1,7 +1,7 @@ //@ check-pass //@ aux-build:external_extern_fn.rs #![crate_type = "lib"] - +#![feature(pattern_type_macro, pattern_types)] mod redeclared_different_signature { mod a { extern "C" { @@ -490,3 +490,42 @@ mod hidden_niche { } } } + +mod pattern_types { + mod a { + use std::pat::pattern_type; + #[repr(transparent)] + struct NonZeroUsize(pattern_type!(usize is 1..)); + extern "C" { + fn pt_non_zero_usize() -> pattern_type!(usize is 1..); + //~^ WARN not FFI-safe + fn pt_non_zero_usize_opt() -> Option; + //~^ WARN not FFI-safe + fn pt_non_zero_usize_opt_full_range() -> Option; + //~^ WARN not FFI-safe + fn pt_non_null_ptr() -> pattern_type!(usize is 1..); + //~^ WARN not FFI-safe + fn pt_non_zero_usize_wrapper() -> NonZeroUsize; + //~^ WARN not FFI-safe + fn pt_non_zero_usize_wrapper_opt() -> Option; + //~^ WARN not FFI-safe + } + } + mod b { + extern "C" { + // If there's a clash in either of these cases you're either gaining an incorrect + // invariant that the value is non-zero, or you're missing out on that invariant. Both + // cases are warning for, from both a caller-convenience and optimisation perspective. + fn pt_non_zero_usize() -> usize; + //~^ WARN `pt_non_zero_usize` redeclared with a different signature + fn pt_non_zero_usize_opt() -> usize; + //~^ WARN `pt_non_zero_usize_opt` redeclared with a different signature + fn pt_non_null_ptr() -> *const (); + //~^ WARN `pt_non_null_ptr` redeclared with a different signature + fn pt_non_zero_usize_wrapper() -> usize; + //~^ WARN `pt_non_zero_usize_wrapper` redeclared with a different signature + fn pt_non_zero_usize_wrapper_opt() -> usize; + //~^ WARN `pt_non_zero_usize_wrapper_opt` redeclared with a different signature + } + } +} diff --git a/tests/ui/lint/clashing-extern-fn.stderr b/tests/ui/lint/clashing-extern-fn.stderr index 48dd1adbc1fa2..acf31a1f5dd46 100644 --- a/tests/ui/lint/clashing-extern-fn.stderr +++ b/tests/ui/lint/clashing-extern-fn.stderr @@ -17,6 +17,60 @@ LL | fn hidden_niche_unsafe_cell() -> Option $DIR/clashing-extern-fn.rs:500:39 + | +LL | fn pt_non_zero_usize() -> pattern_type!(usize is 1..); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider using the base type instead + = note: pattern types have no C equivalent + +warning: `extern` block uses type `Option<(usize) is 1..=>`, which is not FFI-safe + --> $DIR/clashing-extern-fn.rs:502:43 + | +LL | fn pt_non_zero_usize_opt() -> Option; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +warning: `extern` block uses type `Option<(usize) is 0..=>`, which is not FFI-safe + --> $DIR/clashing-extern-fn.rs:504:54 + | +LL | fn pt_non_zero_usize_opt_full_range() -> Option; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +warning: `extern` block uses type `(usize) is 1..=`, which is not FFI-safe + --> $DIR/clashing-extern-fn.rs:506:37 + | +LL | fn pt_non_null_ptr() -> pattern_type!(usize is 1..); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider using the base type instead + = note: pattern types have no C equivalent + +warning: `extern` block uses type `(usize) is 1..=`, which is not FFI-safe + --> $DIR/clashing-extern-fn.rs:508:47 + | +LL | fn pt_non_zero_usize_wrapper() -> NonZeroUsize; + | ^^^^^^^^^^^^ not FFI-safe + | + = help: consider using the base type instead + = note: pattern types have no C equivalent + +warning: `extern` block uses type `Option`, which is not FFI-safe + --> $DIR/clashing-extern-fn.rs:510:51 + | +LL | fn pt_non_zero_usize_wrapper_opt() -> Option; + | ^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + warning: `clash` redeclared with a different signature --> $DIR/clashing-extern-fn.rs:13:13 | @@ -258,5 +312,65 @@ LL | fn hidden_niche_unsafe_cell() -> Option usize` found `unsafe extern "C" fn() -> Option>>` -warning: 22 warnings emitted +warning: `pt_non_zero_usize` redeclared with a different signature + --> $DIR/clashing-extern-fn.rs:519:13 + | +LL | fn pt_non_zero_usize() -> pattern_type!(usize is 1..); + | ------------------------------------------------------ `pt_non_zero_usize` previously declared here +... +LL | fn pt_non_zero_usize() -> usize; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this signature doesn't match the previous declaration + | + = note: expected `unsafe extern "C" fn() -> (usize) is 1..=` + found `unsafe extern "C" fn() -> usize` + +warning: `pt_non_zero_usize_opt` redeclared with a different signature + --> $DIR/clashing-extern-fn.rs:521:13 + | +LL | fn pt_non_zero_usize_opt() -> Option; + | ------------------------------------------------------------------ `pt_non_zero_usize_opt` previously declared here +... +LL | fn pt_non_zero_usize_opt() -> usize; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this signature doesn't match the previous declaration + | + = note: expected `unsafe extern "C" fn() -> Option<(usize) is 1..=>` + found `unsafe extern "C" fn() -> usize` + +warning: `pt_non_null_ptr` redeclared with a different signature + --> $DIR/clashing-extern-fn.rs:523:13 + | +LL | fn pt_non_null_ptr() -> pattern_type!(usize is 1..); + | ---------------------------------------------------- `pt_non_null_ptr` previously declared here +... +LL | fn pt_non_null_ptr() -> *const (); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this signature doesn't match the previous declaration + | + = note: expected `unsafe extern "C" fn() -> (usize) is 1..=` + found `unsafe extern "C" fn() -> *const ()` + +warning: `pt_non_zero_usize_wrapper` redeclared with a different signature + --> $DIR/clashing-extern-fn.rs:525:13 + | +LL | fn pt_non_zero_usize_wrapper() -> NonZeroUsize; + | ----------------------------------------------- `pt_non_zero_usize_wrapper` previously declared here +... +LL | fn pt_non_zero_usize_wrapper() -> usize; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this signature doesn't match the previous declaration + | + = note: expected `unsafe extern "C" fn() -> NonZeroUsize` + found `unsafe extern "C" fn() -> usize` + +warning: `pt_non_zero_usize_wrapper_opt` redeclared with a different signature + --> $DIR/clashing-extern-fn.rs:527:13 + | +LL | fn pt_non_zero_usize_wrapper_opt() -> Option; + | ----------------------------------------------------------- `pt_non_zero_usize_wrapper_opt` previously declared here +... +LL | fn pt_non_zero_usize_wrapper_opt() -> usize; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this signature doesn't match the previous declaration + | + = note: expected `unsafe extern "C" fn() -> Option` + found `unsafe extern "C" fn() -> usize` + +warning: 33 warnings emitted diff --git a/tests/ui/lint/lint-ctypes-enum.rs b/tests/ui/lint/lint-ctypes-enum.rs index 19af1de95760b..0d19d5b534713 100644 --- a/tests/ui/lint/lint-ctypes-enum.rs +++ b/tests/ui/lint/lint-ctypes-enum.rs @@ -94,6 +94,7 @@ extern "C" { fn option_transparent_union(x: Option>>); //~^ ERROR `extern` block uses type fn option_repr_rust(x: Option>>); //~ ERROR `extern` block uses type + fn option_u8(x: Option); //~ ERROR `extern` block uses type fn result_ref_t(x: Result<&'static u8, ()>); fn result_fn_t(x: Result); diff --git a/tests/ui/lint/lint-ctypes-enum.stderr b/tests/ui/lint/lint-ctypes-enum.stderr index 8e92e7e694627..a491bd1960563 100644 --- a/tests/ui/lint/lint-ctypes-enum.stderr +++ b/tests/ui/lint/lint-ctypes-enum.stderr @@ -79,8 +79,17 @@ LL | fn option_repr_rust(x: Option>>); = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum = note: enum has no representation hint +error: `extern` block uses type `Option`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:97:21 + | +LL | fn option_u8(x: Option); + | ^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + error: `extern` block uses type `u128`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:106:33 + --> $DIR/lint-ctypes-enum.rs:107:33 | LL | fn result_nonzero_u128_t(x: Result, ()>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -88,7 +97,7 @@ LL | fn result_nonzero_u128_t(x: Result, ()>); = note: 128-bit integers don't currently have a known stable ABI error: `extern` block uses type `i128`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:113:33 + --> $DIR/lint-ctypes-enum.rs:114:33 | LL | fn result_nonzero_i128_t(x: Result, ()>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -96,7 +105,7 @@ LL | fn result_nonzero_i128_t(x: Result, ()>); = note: 128-bit integers don't currently have a known stable ABI error: `extern` block uses type `Result>, ()>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:118:38 + --> $DIR/lint-ctypes-enum.rs:119:38 | LL | fn result_transparent_union_t(x: Result>, ()>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -105,7 +114,7 @@ LL | fn result_transparent_union_t(x: Result>, ()>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:120:30 + --> $DIR/lint-ctypes-enum.rs:121:30 | LL | fn result_repr_rust_t(x: Result>, ()>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -114,7 +123,7 @@ LL | fn result_repr_rust_t(x: Result>, ()>); = note: enum has no representation hint error: `extern` block uses type `Result, U>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:124:51 + --> $DIR/lint-ctypes-enum.rs:125:51 | LL | fn result_1zst_exhaustive_single_variant_t(x: Result, U>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -123,7 +132,7 @@ LL | fn result_1zst_exhaustive_single_variant_t(x: Result, = note: enum has no representation hint error: `extern` block uses type `Result, B>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:126:53 + --> $DIR/lint-ctypes-enum.rs:127:53 | LL | fn result_1zst_exhaustive_multiple_variant_t(x: Result, B>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -132,7 +141,7 @@ LL | fn result_1zst_exhaustive_multiple_variant_t(x: Result = note: enum has no representation hint error: `extern` block uses type `Result, NonExhaustive>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:128:51 + --> $DIR/lint-ctypes-enum.rs:129:51 | LL | fn result_1zst_non_exhaustive_no_variant_t(x: Result, NonExhaustive>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -141,7 +150,7 @@ LL | fn result_1zst_non_exhaustive_no_variant_t(x: Result, = note: enum has no representation hint error: `extern` block uses type `Result, Field>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:131:49 + --> $DIR/lint-ctypes-enum.rs:132:49 | LL | fn result_1zst_exhaustive_single_field_t(x: Result, Field>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -150,7 +159,7 @@ LL | fn result_1zst_exhaustive_single_field_t(x: Result, Fi = note: enum has no representation hint error: `extern` block uses type `Result>, ()>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:133:30 + --> $DIR/lint-ctypes-enum.rs:134:30 | LL | fn result_cascading_t(x: Result>, ()>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -159,7 +168,7 @@ LL | fn result_cascading_t(x: Result>, ()>); = note: enum has no representation hint error: `extern` block uses type `u128`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:144:33 + --> $DIR/lint-ctypes-enum.rs:145:33 | LL | fn result_nonzero_u128_e(x: Result<(), num::NonZero>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -167,7 +176,7 @@ LL | fn result_nonzero_u128_e(x: Result<(), num::NonZero>); = note: 128-bit integers don't currently have a known stable ABI error: `extern` block uses type `i128`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:151:33 + --> $DIR/lint-ctypes-enum.rs:152:33 | LL | fn result_nonzero_i128_e(x: Result<(), num::NonZero>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -175,7 +184,7 @@ LL | fn result_nonzero_i128_e(x: Result<(), num::NonZero>); = note: 128-bit integers don't currently have a known stable ABI error: `extern` block uses type `Result<(), TransparentUnion>>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:156:38 + --> $DIR/lint-ctypes-enum.rs:157:38 | LL | fn result_transparent_union_e(x: Result<(), TransparentUnion>>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -184,7 +193,7 @@ LL | fn result_transparent_union_e(x: Result<(), TransparentUnion>>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:158:30 + --> $DIR/lint-ctypes-enum.rs:159:30 | LL | fn result_repr_rust_e(x: Result<(), Rust>>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -193,7 +202,7 @@ LL | fn result_repr_rust_e(x: Result<(), Rust>>); = note: enum has no representation hint error: `extern` block uses type `Result>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:162:51 + --> $DIR/lint-ctypes-enum.rs:163:51 | LL | fn result_1zst_exhaustive_single_variant_e(x: Result>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -202,7 +211,7 @@ LL | fn result_1zst_exhaustive_single_variant_e(x: Result>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:164:53 + --> $DIR/lint-ctypes-enum.rs:165:53 | LL | fn result_1zst_exhaustive_multiple_variant_e(x: Result>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -211,7 +220,7 @@ LL | fn result_1zst_exhaustive_multiple_variant_e(x: Result>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:166:51 + --> $DIR/lint-ctypes-enum.rs:167:51 | LL | fn result_1zst_non_exhaustive_no_variant_e(x: Result>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -220,7 +229,7 @@ LL | fn result_1zst_non_exhaustive_no_variant_e(x: Result>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:169:49 + --> $DIR/lint-ctypes-enum.rs:170:49 | LL | fn result_1zst_exhaustive_single_field_e(x: Result>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -229,7 +238,7 @@ LL | fn result_1zst_exhaustive_single_field_e(x: Result>>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:171:30 + --> $DIR/lint-ctypes-enum.rs:172:30 | LL | fn result_cascading_e(x: Result<(), Result<(), num::NonZero>>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -238,7 +247,7 @@ LL | fn result_cascading_e(x: Result<(), Result<(), num::NonZero>>); = note: enum has no representation hint error: `extern` block uses type `Result<(), ()>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:173:27 + --> $DIR/lint-ctypes-enum.rs:174:27 | LL | fn result_unit_t_e(x: Result<(), ()>); | ^^^^^^^^^^^^^^ not FFI-safe @@ -246,5 +255,5 @@ LL | fn result_unit_t_e(x: Result<(), ()>); = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum = note: enum has no representation hint -error: aborting due to 26 previous errors +error: aborting due to 27 previous errors From 473352da311f79bfaadb90c02c6458d02b1fb119 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Fri, 24 Jan 2025 15:57:13 +0000 Subject: [PATCH 10/15] Correctly handle pattern types in FFI safety --- compiler/rustc_lint/messages.ftl | 3 -- compiler/rustc_lint/src/types.rs | 8 ++--- tests/ui/lint/clashing-extern-fn.rs | 3 -- tests/ui/lint/clashing-extern-fn.stderr | 45 +++++-------------------- 4 files changed, 12 insertions(+), 47 deletions(-) diff --git a/compiler/rustc_lint/messages.ftl b/compiler/rustc_lint/messages.ftl index 55c6a122d35d5..480d97e377a40 100644 --- a/compiler/rustc_lint/messages.ftl +++ b/compiler/rustc_lint/messages.ftl @@ -390,9 +390,6 @@ lint_improper_ctypes_only_phantomdata = composed only of `PhantomData` lint_improper_ctypes_opaque = opaque types have no C equivalent -lint_improper_ctypes_pat_help = consider using the base type instead - -lint_improper_ctypes_pat_reason = pattern types have no C equivalent lint_improper_ctypes_slice_help = consider using a raw pointer instead lint_improper_ctypes_slice_reason = slices have no C equivalent diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 601d2fbfb67f2..0dccb8d336d3f 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1256,11 +1256,9 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { help: Some(fluent::lint_improper_ctypes_char_help), }, - ty::Pat(..) => FfiUnsafe { - ty, - reason: fluent::lint_improper_ctypes_pat_reason, - help: Some(fluent::lint_improper_ctypes_pat_help), - }, + // It's just extra invariants on the type that you need to uphold, + // but only the base type is relevant for being representable in FFI. + ty::Pat(base, ..) => self.check_type_for_ffi(acc, base), ty::Int(ty::IntTy::I128) | ty::Uint(ty::UintTy::U128) => { FfiUnsafe { ty, reason: fluent::lint_improper_ctypes_128bit, help: None } diff --git a/tests/ui/lint/clashing-extern-fn.rs b/tests/ui/lint/clashing-extern-fn.rs index 0464299348bdb..012eda761f424 100644 --- a/tests/ui/lint/clashing-extern-fn.rs +++ b/tests/ui/lint/clashing-extern-fn.rs @@ -498,15 +498,12 @@ mod pattern_types { struct NonZeroUsize(pattern_type!(usize is 1..)); extern "C" { fn pt_non_zero_usize() -> pattern_type!(usize is 1..); - //~^ WARN not FFI-safe fn pt_non_zero_usize_opt() -> Option; //~^ WARN not FFI-safe fn pt_non_zero_usize_opt_full_range() -> Option; //~^ WARN not FFI-safe fn pt_non_null_ptr() -> pattern_type!(usize is 1..); - //~^ WARN not FFI-safe fn pt_non_zero_usize_wrapper() -> NonZeroUsize; - //~^ WARN not FFI-safe fn pt_non_zero_usize_wrapper_opt() -> Option; //~^ WARN not FFI-safe } diff --git a/tests/ui/lint/clashing-extern-fn.stderr b/tests/ui/lint/clashing-extern-fn.stderr index acf31a1f5dd46..16d251c1d7a7b 100644 --- a/tests/ui/lint/clashing-extern-fn.stderr +++ b/tests/ui/lint/clashing-extern-fn.stderr @@ -17,17 +17,8 @@ LL | fn hidden_niche_unsafe_cell() -> Option $DIR/clashing-extern-fn.rs:500:39 - | -LL | fn pt_non_zero_usize() -> pattern_type!(usize is 1..); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe - | - = help: consider using the base type instead - = note: pattern types have no C equivalent - warning: `extern` block uses type `Option<(usize) is 1..=>`, which is not FFI-safe - --> $DIR/clashing-extern-fn.rs:502:43 + --> $DIR/clashing-extern-fn.rs:501:43 | LL | fn pt_non_zero_usize_opt() -> Option; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -36,7 +27,7 @@ LL | fn pt_non_zero_usize_opt() -> Option`, which is not FFI-safe - --> $DIR/clashing-extern-fn.rs:504:54 + --> $DIR/clashing-extern-fn.rs:503:54 | LL | fn pt_non_zero_usize_opt_full_range() -> Option; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -44,26 +35,8 @@ LL | fn pt_non_zero_usize_opt_full_range() -> Option $DIR/clashing-extern-fn.rs:506:37 - | -LL | fn pt_non_null_ptr() -> pattern_type!(usize is 1..); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe - | - = help: consider using the base type instead - = note: pattern types have no C equivalent - -warning: `extern` block uses type `(usize) is 1..=`, which is not FFI-safe - --> $DIR/clashing-extern-fn.rs:508:47 - | -LL | fn pt_non_zero_usize_wrapper() -> NonZeroUsize; - | ^^^^^^^^^^^^ not FFI-safe - | - = help: consider using the base type instead - = note: pattern types have no C equivalent - warning: `extern` block uses type `Option`, which is not FFI-safe - --> $DIR/clashing-extern-fn.rs:510:51 + --> $DIR/clashing-extern-fn.rs:507:51 | LL | fn pt_non_zero_usize_wrapper_opt() -> Option; | ^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -313,7 +286,7 @@ LL | fn hidden_niche_unsafe_cell() -> Option Option>>` warning: `pt_non_zero_usize` redeclared with a different signature - --> $DIR/clashing-extern-fn.rs:519:13 + --> $DIR/clashing-extern-fn.rs:516:13 | LL | fn pt_non_zero_usize() -> pattern_type!(usize is 1..); | ------------------------------------------------------ `pt_non_zero_usize` previously declared here @@ -325,7 +298,7 @@ LL | fn pt_non_zero_usize() -> usize; found `unsafe extern "C" fn() -> usize` warning: `pt_non_zero_usize_opt` redeclared with a different signature - --> $DIR/clashing-extern-fn.rs:521:13 + --> $DIR/clashing-extern-fn.rs:518:13 | LL | fn pt_non_zero_usize_opt() -> Option; | ------------------------------------------------------------------ `pt_non_zero_usize_opt` previously declared here @@ -337,7 +310,7 @@ LL | fn pt_non_zero_usize_opt() -> usize; found `unsafe extern "C" fn() -> usize` warning: `pt_non_null_ptr` redeclared with a different signature - --> $DIR/clashing-extern-fn.rs:523:13 + --> $DIR/clashing-extern-fn.rs:520:13 | LL | fn pt_non_null_ptr() -> pattern_type!(usize is 1..); | ---------------------------------------------------- `pt_non_null_ptr` previously declared here @@ -349,7 +322,7 @@ LL | fn pt_non_null_ptr() -> *const (); found `unsafe extern "C" fn() -> *const ()` warning: `pt_non_zero_usize_wrapper` redeclared with a different signature - --> $DIR/clashing-extern-fn.rs:525:13 + --> $DIR/clashing-extern-fn.rs:522:13 | LL | fn pt_non_zero_usize_wrapper() -> NonZeroUsize; | ----------------------------------------------- `pt_non_zero_usize_wrapper` previously declared here @@ -361,7 +334,7 @@ LL | fn pt_non_zero_usize_wrapper() -> usize; found `unsafe extern "C" fn() -> usize` warning: `pt_non_zero_usize_wrapper_opt` redeclared with a different signature - --> $DIR/clashing-extern-fn.rs:527:13 + --> $DIR/clashing-extern-fn.rs:524:13 | LL | fn pt_non_zero_usize_wrapper_opt() -> Option; | ----------------------------------------------------------- `pt_non_zero_usize_wrapper_opt` previously declared here @@ -372,5 +345,5 @@ LL | fn pt_non_zero_usize_wrapper_opt() -> usize; = note: expected `unsafe extern "C" fn() -> Option` found `unsafe extern "C" fn() -> usize` -warning: 33 warnings emitted +warning: 30 warnings emitted From 5bae8ca77c3f6a0050a58b1bc96ee3d51d3feb32 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Fri, 24 Jan 2025 15:57:13 +0000 Subject: [PATCH 11/15] Correctly handle pattern types in FFI redeclaration lints --- compiler/rustc_lint/src/foreign_modules.rs | 9 +- compiler/rustc_lint/src/types.rs | 109 +++++++++++---------- tests/ui/lint/clashing-extern-fn.rs | 2 - tests/ui/lint/clashing-extern-fn.stderr | 32 +----- 4 files changed, 64 insertions(+), 88 deletions(-) diff --git a/compiler/rustc_lint/src/foreign_modules.rs b/compiler/rustc_lint/src/foreign_modules.rs index 45b188205d228..636779fe9b4cf 100644 --- a/compiler/rustc_lint/src/foreign_modules.rs +++ b/compiler/rustc_lint/src/foreign_modules.rs @@ -241,10 +241,7 @@ fn structurally_same_type_impl<'tcx>( if let ty::Adt(def, args) = *ty.kind() { let is_transparent = def.repr().transparent(); let is_non_null = types::nonnull_optimization_guaranteed(tcx, def); - debug!( - "non_transparent_ty({:?}) -- type is transparent? {}, type is non-null? {}", - ty, is_transparent, is_non_null - ); + debug!(?ty, is_transparent, is_non_null); if is_transparent && !is_non_null { debug_assert_eq!(def.variants().len(), 1); let v = &def.variant(FIRST_VARIANT); @@ -378,14 +375,14 @@ fn structurally_same_type_impl<'tcx>( // An Adt and a primitive or pointer type. This can be FFI-safe if non-null // enum layout optimisation is being applied. - (Adt(..), _) if is_primitive_or_pointer(b) => { + (Adt(..) | Pat(..), _) if is_primitive_or_pointer(b) => { if let Some(a_inner) = types::repr_nullable_ptr(tcx, typing_env, a, ckind) { a_inner == b } else { false } } - (_, Adt(..)) if is_primitive_or_pointer(a) => { + (_, Adt(..) | Pat(..)) if is_primitive_or_pointer(a) => { if let Some(b_inner) = types::repr_nullable_ptr(tcx, typing_env, b, ckind) { b_inner == a } else { diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 0dccb8d336d3f..47ceb4b7d2826 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -907,9 +907,8 @@ fn get_nullable_type<'tcx>( }; return get_nullable_type(tcx, typing_env, inner_field_ty); } - ty::Int(ty) => Ty::new_int(tcx, ty), - ty::Uint(ty) => Ty::new_uint(tcx, ty), - ty::RawPtr(ty, mutbl) => Ty::new_ptr(tcx, ty, mutbl), + ty::Pat(base, ..) => return get_nullable_type(tcx, typing_env, base), + ty::Int(_) | ty::Uint(_) | ty::RawPtr(..) => ty, // As these types are always non-null, the nullable equivalent of // `Option` of these types are their raw pointer counterparts. ty::Ref(_region, ty, mutbl) => Ty::new_ptr(tcx, ty, mutbl), @@ -965,63 +964,69 @@ pub(crate) fn repr_nullable_ptr<'tcx>( ckind: CItemKind, ) -> Option> { debug!("is_repr_nullable_ptr(tcx, ty = {:?})", ty); - if let ty::Adt(ty_def, args) = ty.kind() { - let field_ty = match &ty_def.variants().raw[..] { - [var_one, var_two] => match (&var_one.fields.raw[..], &var_two.fields.raw[..]) { - ([], [field]) | ([field], []) => field.ty(tcx, args), - ([field1], [field2]) => { - let ty1 = field1.ty(tcx, args); - let ty2 = field2.ty(tcx, args); - - if is_niche_optimization_candidate(tcx, typing_env, ty1) { - ty2 - } else if is_niche_optimization_candidate(tcx, typing_env, ty2) { - ty1 - } else { - return None; + match ty.kind() { + ty::Adt(ty_def, args) => { + let field_ty = match &ty_def.variants().raw[..] { + [var_one, var_two] => match (&var_one.fields.raw[..], &var_two.fields.raw[..]) { + ([], [field]) | ([field], []) => field.ty(tcx, args), + ([field1], [field2]) => { + let ty1 = field1.ty(tcx, args); + let ty2 = field2.ty(tcx, args); + + if is_niche_optimization_candidate(tcx, typing_env, ty1) { + ty2 + } else if is_niche_optimization_candidate(tcx, typing_env, ty2) { + ty1 + } else { + return None; + } } - } + _ => return None, + }, _ => return None, - }, - _ => return None, - }; + }; - if !ty_is_known_nonnull(tcx, typing_env, field_ty, ckind) { - return None; - } + if !ty_is_known_nonnull(tcx, typing_env, field_ty, ckind) { + return None; + } - // At this point, the field's type is known to be nonnull and the parent enum is Option-like. - // If the computed size for the field and the enum are different, the nonnull optimization isn't - // being applied (and we've got a problem somewhere). - let compute_size_skeleton = |t| SizeSkeleton::compute(t, tcx, typing_env).ok(); - if !compute_size_skeleton(ty)?.same_size(compute_size_skeleton(field_ty)?) { - bug!("improper_ctypes: Option nonnull optimization not applied?"); - } + // At this point, the field's type is known to be nonnull and the parent enum is Option-like. + // If the computed size for the field and the enum are different, the nonnull optimization isn't + // being applied (and we've got a problem somewhere). + let compute_size_skeleton = |t| SizeSkeleton::compute(t, tcx, typing_env).ok(); + if !compute_size_skeleton(ty)?.same_size(compute_size_skeleton(field_ty)?) { + bug!("improper_ctypes: Option nonnull optimization not applied?"); + } - // Return the nullable type this Option-like enum can be safely represented with. - let field_ty_layout = tcx.layout_of(typing_env.as_query_input(field_ty)); - if field_ty_layout.is_err() && !field_ty.has_non_region_param() { - bug!("should be able to compute the layout of non-polymorphic type"); - } + // Return the nullable type this Option-like enum can be safely represented with. + let field_ty_layout = tcx.layout_of(typing_env.as_query_input(field_ty)); + if field_ty_layout.is_err() && !field_ty.has_non_region_param() { + bug!("should be able to compute the layout of non-polymorphic type"); + } - let field_ty_abi = &field_ty_layout.ok()?.backend_repr; - if let BackendRepr::Scalar(field_ty_scalar) = field_ty_abi { - match field_ty_scalar.valid_range(&tcx) { - WrappingRange { start: 0, end } - if end == field_ty_scalar.size(&tcx).unsigned_int_max() - 1 => - { - return Some(get_nullable_type(tcx, typing_env, field_ty).unwrap()); - } - WrappingRange { start: 1, .. } => { - return Some(get_nullable_type(tcx, typing_env, field_ty).unwrap()); - } - WrappingRange { start, end } => { - unreachable!("Unhandled start and end range: ({}, {})", start, end) - } - }; + let field_ty_abi = &field_ty_layout.ok()?.backend_repr; + if let BackendRepr::Scalar(field_ty_scalar) = field_ty_abi { + match field_ty_scalar.valid_range(&tcx) { + WrappingRange { start: 0, end } + if end == field_ty_scalar.size(&tcx).unsigned_int_max() - 1 => + { + return Some(get_nullable_type(tcx, typing_env, field_ty).unwrap()); + } + WrappingRange { start: 1, .. } => { + return Some(get_nullable_type(tcx, typing_env, field_ty).unwrap()); + } + WrappingRange { start, end } => { + unreachable!("Unhandled start and end range: ({}, {})", start, end) + } + }; + } + None } + ty::Pat(base, pat) => match **pat { + ty::PatternKind::Range { .. } => get_nullable_type(tcx, typing_env, *base), + }, + _ => None, } - None } impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { diff --git a/tests/ui/lint/clashing-extern-fn.rs b/tests/ui/lint/clashing-extern-fn.rs index 012eda761f424..1d1c07b66b2f2 100644 --- a/tests/ui/lint/clashing-extern-fn.rs +++ b/tests/ui/lint/clashing-extern-fn.rs @@ -514,13 +514,11 @@ mod pattern_types { // invariant that the value is non-zero, or you're missing out on that invariant. Both // cases are warning for, from both a caller-convenience and optimisation perspective. fn pt_non_zero_usize() -> usize; - //~^ WARN `pt_non_zero_usize` redeclared with a different signature fn pt_non_zero_usize_opt() -> usize; //~^ WARN `pt_non_zero_usize_opt` redeclared with a different signature fn pt_non_null_ptr() -> *const (); //~^ WARN `pt_non_null_ptr` redeclared with a different signature fn pt_non_zero_usize_wrapper() -> usize; - //~^ WARN `pt_non_zero_usize_wrapper` redeclared with a different signature fn pt_non_zero_usize_wrapper_opt() -> usize; //~^ WARN `pt_non_zero_usize_wrapper_opt` redeclared with a different signature } diff --git a/tests/ui/lint/clashing-extern-fn.stderr b/tests/ui/lint/clashing-extern-fn.stderr index 16d251c1d7a7b..a2fc9e7749237 100644 --- a/tests/ui/lint/clashing-extern-fn.stderr +++ b/tests/ui/lint/clashing-extern-fn.stderr @@ -285,20 +285,8 @@ LL | fn hidden_niche_unsafe_cell() -> Option usize` found `unsafe extern "C" fn() -> Option>>` -warning: `pt_non_zero_usize` redeclared with a different signature - --> $DIR/clashing-extern-fn.rs:516:13 - | -LL | fn pt_non_zero_usize() -> pattern_type!(usize is 1..); - | ------------------------------------------------------ `pt_non_zero_usize` previously declared here -... -LL | fn pt_non_zero_usize() -> usize; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this signature doesn't match the previous declaration - | - = note: expected `unsafe extern "C" fn() -> (usize) is 1..=` - found `unsafe extern "C" fn() -> usize` - warning: `pt_non_zero_usize_opt` redeclared with a different signature - --> $DIR/clashing-extern-fn.rs:518:13 + --> $DIR/clashing-extern-fn.rs:517:13 | LL | fn pt_non_zero_usize_opt() -> Option; | ------------------------------------------------------------------ `pt_non_zero_usize_opt` previously declared here @@ -310,7 +298,7 @@ LL | fn pt_non_zero_usize_opt() -> usize; found `unsafe extern "C" fn() -> usize` warning: `pt_non_null_ptr` redeclared with a different signature - --> $DIR/clashing-extern-fn.rs:520:13 + --> $DIR/clashing-extern-fn.rs:519:13 | LL | fn pt_non_null_ptr() -> pattern_type!(usize is 1..); | ---------------------------------------------------- `pt_non_null_ptr` previously declared here @@ -321,20 +309,8 @@ LL | fn pt_non_null_ptr() -> *const (); = note: expected `unsafe extern "C" fn() -> (usize) is 1..=` found `unsafe extern "C" fn() -> *const ()` -warning: `pt_non_zero_usize_wrapper` redeclared with a different signature - --> $DIR/clashing-extern-fn.rs:522:13 - | -LL | fn pt_non_zero_usize_wrapper() -> NonZeroUsize; - | ----------------------------------------------- `pt_non_zero_usize_wrapper` previously declared here -... -LL | fn pt_non_zero_usize_wrapper() -> usize; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this signature doesn't match the previous declaration - | - = note: expected `unsafe extern "C" fn() -> NonZeroUsize` - found `unsafe extern "C" fn() -> usize` - warning: `pt_non_zero_usize_wrapper_opt` redeclared with a different signature - --> $DIR/clashing-extern-fn.rs:524:13 + --> $DIR/clashing-extern-fn.rs:522:13 | LL | fn pt_non_zero_usize_wrapper_opt() -> Option; | ----------------------------------------------------------- `pt_non_zero_usize_wrapper_opt` previously declared here @@ -345,5 +321,5 @@ LL | fn pt_non_zero_usize_wrapper_opt() -> usize; = note: expected `unsafe extern "C" fn() -> Option` found `unsafe extern "C" fn() -> usize` -warning: 30 warnings emitted +warning: 28 warnings emitted From f1f996a4d590e3d75eb5c5dab5098b7ae2ebf7eb Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 28 Jan 2025 11:08:22 +0000 Subject: [PATCH 12/15] Handle pattern types wrapped in `Option` in FFI checks --- compiler/rustc_lint/src/lib.rs | 1 + compiler/rustc_lint/src/types.rs | 31 ++++++++++++++++ tests/ui/lint/clashing-extern-fn.rs | 4 --- tests/ui/lint/clashing-extern-fn.stderr | 48 ++----------------------- 4 files changed, 35 insertions(+), 49 deletions(-) diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index d89e615e14ad3..c8de5e877531e 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -33,6 +33,7 @@ #![feature(let_chains)] #![feature(rustc_attrs)] #![feature(rustdoc_internals)] +#![feature(try_blocks)] #![warn(unreachable_pub)] // tidy-alphabetical-end diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 47ceb4b7d2826..68b1f435a4cf7 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -877,6 +877,37 @@ fn ty_is_known_nonnull<'tcx>( .filter_map(|variant| transparent_newtype_field(tcx, variant)) .any(|field| ty_is_known_nonnull(tcx, typing_env, field.ty(tcx, args), mode)) } + ty::Pat(base, pat) => { + ty_is_known_nonnull(tcx, typing_env, *base, mode) + || Option::unwrap_or_default( + try { + match **pat { + ty::PatternKind::Range { start, end, include_end } => { + match (start, end) { + (Some(start), None) => { + start.try_to_value()?.try_to_bits(tcx, typing_env)? > 0 + } + (Some(start), Some(end)) => { + let start = + start.try_to_value()?.try_to_bits(tcx, typing_env)?; + let end = + end.try_to_value()?.try_to_bits(tcx, typing_env)?; + + if include_end { + // This also works for negative numbers, as we just need + // to ensure we aren't wrapping over zero. + start > 0 && end >= start + } else { + start > 0 && end > start + } + } + _ => false, + } + } + } + }, + ) + } _ => false, } } diff --git a/tests/ui/lint/clashing-extern-fn.rs b/tests/ui/lint/clashing-extern-fn.rs index 1d1c07b66b2f2..e4477c9620221 100644 --- a/tests/ui/lint/clashing-extern-fn.rs +++ b/tests/ui/lint/clashing-extern-fn.rs @@ -499,13 +499,11 @@ mod pattern_types { extern "C" { fn pt_non_zero_usize() -> pattern_type!(usize is 1..); fn pt_non_zero_usize_opt() -> Option; - //~^ WARN not FFI-safe fn pt_non_zero_usize_opt_full_range() -> Option; //~^ WARN not FFI-safe fn pt_non_null_ptr() -> pattern_type!(usize is 1..); fn pt_non_zero_usize_wrapper() -> NonZeroUsize; fn pt_non_zero_usize_wrapper_opt() -> Option; - //~^ WARN not FFI-safe } } mod b { @@ -515,12 +513,10 @@ mod pattern_types { // cases are warning for, from both a caller-convenience and optimisation perspective. fn pt_non_zero_usize() -> usize; fn pt_non_zero_usize_opt() -> usize; - //~^ WARN `pt_non_zero_usize_opt` redeclared with a different signature fn pt_non_null_ptr() -> *const (); //~^ WARN `pt_non_null_ptr` redeclared with a different signature fn pt_non_zero_usize_wrapper() -> usize; fn pt_non_zero_usize_wrapper_opt() -> usize; - //~^ WARN `pt_non_zero_usize_wrapper_opt` redeclared with a different signature } } } diff --git a/tests/ui/lint/clashing-extern-fn.stderr b/tests/ui/lint/clashing-extern-fn.stderr index a2fc9e7749237..118b18b224c05 100644 --- a/tests/ui/lint/clashing-extern-fn.stderr +++ b/tests/ui/lint/clashing-extern-fn.stderr @@ -17,17 +17,8 @@ LL | fn hidden_niche_unsafe_cell() -> Option`, which is not FFI-safe - --> $DIR/clashing-extern-fn.rs:501:43 - | -LL | fn pt_non_zero_usize_opt() -> Option; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe - | - = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum - = note: enum has no representation hint - warning: `extern` block uses type `Option<(usize) is 0..=>`, which is not FFI-safe - --> $DIR/clashing-extern-fn.rs:503:54 + --> $DIR/clashing-extern-fn.rs:502:54 | LL | fn pt_non_zero_usize_opt_full_range() -> Option; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe @@ -35,15 +26,6 @@ LL | fn pt_non_zero_usize_opt_full_range() -> Option`, which is not FFI-safe - --> $DIR/clashing-extern-fn.rs:507:51 - | -LL | fn pt_non_zero_usize_wrapper_opt() -> Option; - | ^^^^^^^^^^^^^^^^^^^^ not FFI-safe - | - = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum - = note: enum has no representation hint - warning: `clash` redeclared with a different signature --> $DIR/clashing-extern-fn.rs:13:13 | @@ -285,20 +267,8 @@ LL | fn hidden_niche_unsafe_cell() -> Option usize` found `unsafe extern "C" fn() -> Option>>` -warning: `pt_non_zero_usize_opt` redeclared with a different signature - --> $DIR/clashing-extern-fn.rs:517:13 - | -LL | fn pt_non_zero_usize_opt() -> Option; - | ------------------------------------------------------------------ `pt_non_zero_usize_opt` previously declared here -... -LL | fn pt_non_zero_usize_opt() -> usize; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this signature doesn't match the previous declaration - | - = note: expected `unsafe extern "C" fn() -> Option<(usize) is 1..=>` - found `unsafe extern "C" fn() -> usize` - warning: `pt_non_null_ptr` redeclared with a different signature - --> $DIR/clashing-extern-fn.rs:519:13 + --> $DIR/clashing-extern-fn.rs:516:13 | LL | fn pt_non_null_ptr() -> pattern_type!(usize is 1..); | ---------------------------------------------------- `pt_non_null_ptr` previously declared here @@ -309,17 +279,5 @@ LL | fn pt_non_null_ptr() -> *const (); = note: expected `unsafe extern "C" fn() -> (usize) is 1..=` found `unsafe extern "C" fn() -> *const ()` -warning: `pt_non_zero_usize_wrapper_opt` redeclared with a different signature - --> $DIR/clashing-extern-fn.rs:522:13 - | -LL | fn pt_non_zero_usize_wrapper_opt() -> Option; - | ----------------------------------------------------------- `pt_non_zero_usize_wrapper_opt` previously declared here -... -LL | fn pt_non_zero_usize_wrapper_opt() -> usize; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this signature doesn't match the previous declaration - | - = note: expected `unsafe extern "C" fn() -> Option` - found `unsafe extern "C" fn() -> usize` - -warning: 28 warnings emitted +warning: 24 warnings emitted From b2cd1b8ead95530e61ad108a3113c588e590187a Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 14 Jan 2025 12:25:16 +0000 Subject: [PATCH 13/15] Remove an unsafe closure invariant by inlining the closure wrapper into the called function --- compiler/rustc_codegen_llvm/src/back/write.rs | 130 +++++++----------- 1 file changed, 50 insertions(+), 80 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index ae4c4d5876e2b..6a7b699634753 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -40,7 +40,7 @@ use crate::errors::{ WithLlvmError, WriteBytecode, }; use crate::llvm::diagnostic::OptimizationDiagnosticKind::*; -use crate::llvm::{self, DiagnosticInfo, PassManager}; +use crate::llvm::{self, DiagnosticInfo}; use crate::type_::Type; use crate::{LlvmCodegenBackend, ModuleLlvm, base, common, llvm_util}; @@ -54,7 +54,7 @@ pub(crate) fn llvm_err<'a>(dcx: DiagCtxtHandle<'_>, err: LlvmError<'a>) -> Fatal fn write_output_file<'ll>( dcx: DiagCtxtHandle<'_>, target: &'ll llvm::TargetMachine, - pm: &llvm::PassManager<'ll>, + no_builtins: bool, m: &'ll llvm::Module, output: &Path, dwo_output: Option<&Path>, @@ -63,16 +63,19 @@ fn write_output_file<'ll>( verify_llvm_ir: bool, ) -> Result<(), FatalError> { debug!("write_output_file output={:?} dwo_output={:?}", output, dwo_output); - unsafe { - let output_c = path_to_c_string(output); - let dwo_output_c; - let dwo_output_ptr = if let Some(dwo_output) = dwo_output { - dwo_output_c = path_to_c_string(dwo_output); - dwo_output_c.as_ptr() - } else { - std::ptr::null() - }; - let result = llvm::LLVMRustWriteOutputFile( + let output_c = path_to_c_string(output); + let dwo_output_c; + let dwo_output_ptr = if let Some(dwo_output) = dwo_output { + dwo_output_c = path_to_c_string(dwo_output); + dwo_output_c.as_ptr() + } else { + std::ptr::null() + }; + let result = unsafe { + let pm = llvm::LLVMCreatePassManager(); + llvm::LLVMAddAnalysisPasses(target, pm); + llvm::LLVMRustAddLibraryInfo(pm, m, no_builtins); + llvm::LLVMRustWriteOutputFile( target, pm, m, @@ -80,22 +83,22 @@ fn write_output_file<'ll>( dwo_output_ptr, file_type, verify_llvm_ir, - ); + ) + }; - // Record artifact sizes for self-profiling - if result == llvm::LLVMRustResult::Success { - let artifact_kind = match file_type { - llvm::FileType::ObjectFile => "object_file", - llvm::FileType::AssemblyFile => "assembly_file", - }; - record_artifact_size(self_profiler_ref, artifact_kind, output); - if let Some(dwo_file) = dwo_output { - record_artifact_size(self_profiler_ref, "dwo_file", dwo_file); - } + // Record artifact sizes for self-profiling + if result == llvm::LLVMRustResult::Success { + let artifact_kind = match file_type { + llvm::FileType::ObjectFile => "object_file", + llvm::FileType::AssemblyFile => "assembly_file", + }; + record_artifact_size(self_profiler_ref, artifact_kind, output); + if let Some(dwo_file) = dwo_output { + record_artifact_size(self_profiler_ref, "dwo_file", dwo_file); } - - result.into_result().map_err(|()| llvm_err(dcx, LlvmError::WriteOutput { path: output })) } + + result.into_result().map_err(|()| llvm_err(dcx, LlvmError::WriteOutput { path: output })) } pub(crate) fn create_informational_target_machine( @@ -755,31 +758,6 @@ pub(crate) unsafe fn codegen( create_msvc_imps(cgcx, llcx, llmod); } - // A codegen-specific pass manager is used to generate object - // files for an LLVM module. - // - // Apparently each of these pass managers is a one-shot kind of - // thing, so we create a new one for each type of output. The - // pass manager passed to the closure should be ensured to not - // escape the closure itself, and the manager should only be - // used once. - unsafe fn with_codegen<'ll, F, R>( - tm: &'ll llvm::TargetMachine, - llmod: &'ll llvm::Module, - no_builtins: bool, - f: F, - ) -> R - where - F: FnOnce(&'ll mut PassManager<'ll>) -> R, - { - unsafe { - let cpm = llvm::LLVMCreatePassManager(); - llvm::LLVMAddAnalysisPasses(tm, cpm); - llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins); - f(cpm) - } - } - // Note that if object files are just LLVM bitcode we write bitcode, // copy it to the .o file, and delete the bitcode if it wasn't // otherwise requested. @@ -898,21 +876,17 @@ pub(crate) unsafe fn codegen( } else { llmod }; - unsafe { - with_codegen(tm, llmod, config.no_builtins, |cpm| { - write_output_file( - dcx, - tm, - cpm, - llmod, - &path, - None, - llvm::FileType::AssemblyFile, - &cgcx.prof, - config.verify_llvm_ir, - ) - })?; - } + write_output_file( + dcx, + tm, + config.no_builtins, + llmod, + &path, + None, + llvm::FileType::AssemblyFile, + &cgcx.prof, + config.verify_llvm_ir, + )?; } match config.emit_obj { @@ -936,21 +910,17 @@ pub(crate) unsafe fn codegen( (_, SplitDwarfKind::Split) => Some(dwo_out.as_path()), }; - unsafe { - with_codegen(tm, llmod, config.no_builtins, |cpm| { - write_output_file( - dcx, - tm, - cpm, - llmod, - &obj_out, - dwo_out, - llvm::FileType::ObjectFile, - &cgcx.prof, - config.verify_llvm_ir, - ) - })?; - } + write_output_file( + dcx, + tm, + config.no_builtins, + llmod, + &obj_out, + dwo_out, + llvm::FileType::ObjectFile, + &cgcx.prof, + config.verify_llvm_ir, + )?; } EmitObj::Bitcode => { From 4b83038d637c1664df94895c82cb8b26716bad1d Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 14 Jan 2025 12:25:16 +0000 Subject: [PATCH 14/15] Add a safe wrapper for `WriteBitcodeToFile` --- compiler/rustc_codegen_llvm/src/back/write.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index 6a7b699634753..39aa3a033dcc3 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -328,13 +328,17 @@ pub(crate) fn save_temp_bitcode( if !cgcx.save_temps { return; } + let ext = format!("{name}.bc"); + let cgu = Some(&module.name[..]); + let path = cgcx.output_filenames.temp_path_ext(&ext, cgu); + write_bitcode_to_file(module, &path) +} + +fn write_bitcode_to_file(module: &ModuleCodegen, path: &Path) { unsafe { - let ext = format!("{name}.bc"); - let cgu = Some(&module.name[..]); - let path = cgcx.output_filenames.temp_path_ext(&ext, cgu); - let cstr = path_to_c_string(&path); + let path = path_to_c_string(&path); let llmod = module.module_llvm.llmod(); - llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr()); + llvm::LLVMWriteBitcodeToFile(llmod, path.as_ptr()); } } @@ -679,7 +683,6 @@ pub(crate) unsafe fn optimize( ) -> Result<(), FatalError> { let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &*module.name); - let llmod = module.module_llvm.llmod(); let llcx = &*module.module_llvm.llcx; let _handlers = DiagnosticHandlers::new(cgcx, dcx, llcx, module, CodegenDiagnosticsStage::Opt); @@ -688,8 +691,7 @@ pub(crate) unsafe fn optimize( if config.emit_no_opt_bc { let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name); - let out = path_to_c_string(&out); - unsafe { llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr()) }; + write_bitcode_to_file(module, &out) } // FIXME(ZuseZ4): support SanitizeHWAddress and prevent illegal/unsupported opts From dcf1e4d72b4dbda592050dcde7d7972414b05d3c Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 14 Jan 2025 12:25:16 +0000 Subject: [PATCH 15/15] Document some safety constraints and use more safe wrappers --- compiler/rustc_codegen_llvm/src/allocator.rs | 4 +- .../rustc_codegen_llvm/src/back/archive.rs | 11 ++-- compiler/rustc_codegen_llvm/src/back/write.rs | 64 ++++++++----------- compiler/rustc_codegen_llvm/src/common.rs | 2 +- compiler/rustc_codegen_llvm/src/consts.rs | 6 +- compiler/rustc_codegen_llvm/src/context.rs | 10 ++- .../rustc_codegen_llvm/src/debuginfo/gdb.rs | 2 +- compiler/rustc_codegen_llvm/src/declare.rs | 2 +- compiler/rustc_codegen_llvm/src/intrinsic.rs | 2 +- compiler/rustc_codegen_llvm/src/llvm/ffi.rs | 2 +- compiler/rustc_codegen_llvm/src/llvm/mod.rs | 4 ++ 11 files changed, 50 insertions(+), 59 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/allocator.rs b/compiler/rustc_codegen_llvm/src/allocator.rs index 149ded28356b8..66723cbf88206 100644 --- a/compiler/rustc_codegen_llvm/src/allocator.rs +++ b/compiler/rustc_codegen_llvm/src/allocator.rs @@ -81,13 +81,13 @@ pub(crate) unsafe fn codegen( llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility())); let val = tcx.sess.opts.unstable_opts.oom.should_panic(); let llval = llvm::LLVMConstInt(i8, val as u64, False); - llvm::LLVMSetInitializer(ll_g, llval); + llvm::set_initializer(ll_g, llval); let name = NO_ALLOC_SHIM_IS_UNSTABLE; let ll_g = llvm::LLVMRustGetOrInsertGlobal(llmod, name.as_c_char_ptr(), name.len(), i8); llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility())); let llval = llvm::LLVMConstInt(i8, 0, False); - llvm::LLVMSetInitializer(ll_g, llval); + llvm::set_initializer(ll_g, llval); } if tcx.sess.opts.debuginfo != DebugInfo::None { diff --git a/compiler/rustc_codegen_llvm/src/back/archive.rs b/compiler/rustc_codegen_llvm/src/back/archive.rs index 33a956e552fbe..93553f3f3648a 100644 --- a/compiler/rustc_codegen_llvm/src/back/archive.rs +++ b/compiler/rustc_codegen_llvm/src/back/archive.rs @@ -11,7 +11,7 @@ use rustc_codegen_ssa::back::archive::{ use rustc_session::Session; use crate::llvm::archive_ro::{ArchiveRO, Child}; -use crate::llvm::{self, ArchiveKind}; +use crate::llvm::{self, ArchiveKind, last_error}; /// Helper for adding many files to an archive. #[must_use = "must call build() to finish building the archive"] @@ -169,6 +169,8 @@ impl<'a> LlvmArchiveBuilder<'a> { .unwrap_or_else(|kind| self.sess.dcx().emit_fatal(UnknownArchiveKind { kind })); let mut additions = mem::take(&mut self.additions); + // Values in the `members` list below will contain pointers to the strings allocated here. + // So they need to get dropped after all elements of `members` get freed. let mut strings = Vec::new(); let mut members = Vec::new(); @@ -229,12 +231,7 @@ impl<'a> LlvmArchiveBuilder<'a> { self.sess.target.arch == "arm64ec", ); let ret = if r.into_result().is_err() { - let err = llvm::LLVMRustGetLastError(); - let msg = if err.is_null() { - "failed to write archive".into() - } else { - String::from_utf8_lossy(CStr::from_ptr(err).to_bytes()) - }; + let msg = last_error().unwrap_or_else(|| "failed to write archive".into()); Err(io::Error::new(io::ErrorKind::Other, msg)) } else { Ok(!members.is_empty()) diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index 39aa3a033dcc3..58933a77e53d1 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -1049,24 +1049,18 @@ unsafe fn embed_bitcode( { // We don't need custom section flags, create LLVM globals. let llconst = common::bytes_in_context(llcx, bitcode); - let llglobal = llvm::LLVMAddGlobal( - llmod, - common::val_ty(llconst), - c"rustc.embedded.module".as_ptr(), - ); - llvm::LLVMSetInitializer(llglobal, llconst); + let llglobal = + llvm::add_global(llmod, common::val_ty(llconst), c"rustc.embedded.module"); + llvm::set_initializer(llglobal, llconst); llvm::set_section(llglobal, bitcode_section_name(cgcx)); llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage); llvm::LLVMSetGlobalConstant(llglobal, llvm::True); let llconst = common::bytes_in_context(llcx, cmdline.as_bytes()); - let llglobal = llvm::LLVMAddGlobal( - llmod, - common::val_ty(llconst), - c"rustc.embedded.cmdline".as_ptr(), - ); - llvm::LLVMSetInitializer(llglobal, llconst); + let llglobal = + llvm::add_global(llmod, common::val_ty(llconst), c"rustc.embedded.cmdline"); + llvm::set_initializer(llglobal, llconst); let section = if cgcx.target_is_like_osx { c"__LLVM,__cmdline" } else if cgcx.target_is_like_aix { @@ -1106,31 +1100,29 @@ fn create_msvc_imps( // underscores added in front). let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" }; - unsafe { - let ptr_ty = Type::ptr_llcx(llcx); - let globals = base::iter_globals(llmod) - .filter(|&val| { - llvm::get_linkage(val) == llvm::Linkage::ExternalLinkage - && llvm::LLVMIsDeclaration(val) == 0 - }) - .filter_map(|val| { - // Exclude some symbols that we know are not Rust symbols. - let name = llvm::get_value_name(val); - if ignored(name) { None } else { Some((val, name)) } - }) - .map(move |(val, name)| { - let mut imp_name = prefix.as_bytes().to_vec(); - imp_name.extend(name); - let imp_name = CString::new(imp_name).unwrap(); - (imp_name, val) - }) - .collect::>(); + let ptr_ty = Type::ptr_llcx(llcx); + let globals = base::iter_globals(llmod) + .filter(|&val| { + llvm::get_linkage(val) == llvm::Linkage::ExternalLinkage && !llvm::is_declaration(val) + }) + .filter_map(|val| { + // Exclude some symbols that we know are not Rust symbols. + let name = llvm::get_value_name(val); + if ignored(name) { None } else { Some((val, name)) } + }) + .map(move |(val, name)| { + let mut imp_name = prefix.as_bytes().to_vec(); + imp_name.extend(name); + let imp_name = CString::new(imp_name).unwrap(); + (imp_name, val) + }) + .collect::>(); - for (imp_name, val) in globals { - let imp = llvm::LLVMAddGlobal(llmod, ptr_ty, imp_name.as_ptr()); - llvm::LLVMSetInitializer(imp, val); - llvm::set_linkage(imp, llvm::Linkage::ExternalLinkage); - } + for (imp_name, val) in globals { + let imp = llvm::add_global(llmod, ptr_ty, &imp_name); + + llvm::set_initializer(imp, val); + llvm::set_linkage(imp, llvm::Linkage::ExternalLinkage); } // Use this function to exclude certain symbols from `__imp` generation. diff --git a/compiler/rustc_codegen_llvm/src/common.rs b/compiler/rustc_codegen_llvm/src/common.rs index 8c94a46ebf305..78b3a7f85417b 100644 --- a/compiler/rustc_codegen_llvm/src/common.rs +++ b/compiler/rustc_codegen_llvm/src/common.rs @@ -219,8 +219,8 @@ impl<'ll, 'tcx> ConstCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { let g = self.define_global(&sym, self.val_ty(sc)).unwrap_or_else(|| { bug!("symbol `{}` is already defined", sym); }); + llvm::set_initializer(g, sc); unsafe { - llvm::LLVMSetInitializer(g, sc); llvm::LLVMSetGlobalConstant(g, True); llvm::LLVMSetUnnamedAddress(g, llvm::UnnamedAddr::Global); } diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index c6855dd42e531..4a5491ec7a18c 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -191,7 +191,7 @@ fn check_and_apply_linkage<'ll, 'tcx>( }) }); llvm::set_linkage(g2, llvm::Linkage::InternalLinkage); - unsafe { llvm::LLVMSetInitializer(g2, g1) }; + llvm::set_initializer(g2, g1); g2 } else if cx.tcx.sess.target.arch == "x86" && common::is_mingw_gnu_toolchain(&cx.tcx.sess.target) @@ -235,7 +235,7 @@ impl<'ll> CodegenCx<'ll, '_> { } _ => self.define_private_global(self.val_ty(cv)), }; - unsafe { llvm::LLVMSetInitializer(gv, cv) }; + llvm::set_initializer(gv, cv); set_global_alignment(self, gv, align); llvm::SetUnnamedAddress(gv, llvm::UnnamedAddr::Global); gv @@ -458,7 +458,7 @@ impl<'ll> CodegenCx<'ll, '_> { new_g }; set_global_alignment(self, g, alloc.align); - llvm::LLVMSetInitializer(g, v); + llvm::set_initializer(g, v); if self.should_assume_dso_local(g, true) { llvm::LLVMRustSetDSOLocal(g, true); diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index ba4fd75fb9418..7fe527a4c07d0 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -616,12 +616,10 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { pub(crate) fn create_used_variable_impl(&self, name: &'static CStr, values: &[&'ll Value]) { let array = self.const_array(self.type_ptr(), values); - unsafe { - let g = llvm::LLVMAddGlobal(self.llmod, self.val_ty(array), name.as_ptr()); - llvm::LLVMSetInitializer(g, array); - llvm::set_linkage(g, llvm::Linkage::AppendingLinkage); - llvm::set_section(g, c"llvm.metadata"); - } + let g = llvm::add_global(self.llmod, self.val_ty(array), name); + llvm::set_initializer(g, array); + llvm::set_linkage(g, llvm::Linkage::AppendingLinkage); + llvm::set_section(g, c"llvm.metadata"); } } impl<'ll> SimpleCx<'ll> { diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs index 2c9f1cda13a8a..54c5d445f66bd 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs @@ -73,7 +73,7 @@ pub(crate) fn get_or_insert_gdb_debug_scripts_section_global<'ll>( .define_global(section_var_name, llvm_type) .unwrap_or_else(|| bug!("symbol `{}` is already defined", section_var_name)); llvm::set_section(section_var, c".debug_gdb_scripts"); - llvm::LLVMSetInitializer(section_var, cx.const_bytes(section_contents)); + llvm::set_initializer(section_var, cx.const_bytes(section_contents)); llvm::LLVMSetGlobalConstant(section_var, llvm::True); llvm::LLVMSetUnnamedAddress(section_var, llvm::UnnamedAddr::Global); llvm::set_linkage(section_var, llvm::Linkage::LinkOnceODRLinkage); diff --git a/compiler/rustc_codegen_llvm/src/declare.rs b/compiler/rustc_codegen_llvm/src/declare.rs index bdc83267cca94..cebceef1b93f8 100644 --- a/compiler/rustc_codegen_llvm/src/declare.rs +++ b/compiler/rustc_codegen_llvm/src/declare.rs @@ -235,7 +235,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { /// name. pub(crate) fn get_defined_value(&self, name: &str) -> Option<&'ll Value> { self.get_declared_value(name).and_then(|val| { - let declaration = unsafe { llvm::LLVMIsDeclaration(val) != 0 }; + let declaration = llvm::is_declaration(val); if !declaration { Some(val) } else { None } }) } diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 3200c94d97703..8b97688590456 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -824,7 +824,7 @@ fn codegen_msvc_try<'ll>( if bx.cx.tcx.sess.target.supports_comdat() { llvm::SetUniqueComdat(bx.llmod, tydesc); } - unsafe { llvm::LLVMSetInitializer(tydesc, type_info) }; + llvm::set_initializer(tydesc, type_info); // The flag value of 8 indicates that we are catching the exception by // reference instead of by value. We can't use catch by value because diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index 4d6a76b23ea1a..441d144ce50d6 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -2359,7 +2359,7 @@ unsafe extern "C" { ); pub fn LLVMRustWriteOutputFile<'a>( T: &'a TargetMachine, - PM: &PassManager<'a>, + PM: *mut PassManager<'a>, M: &'a Module, Output: *const c_char, DwoOutput: *const c_char, diff --git a/compiler/rustc_codegen_llvm/src/llvm/mod.rs b/compiler/rustc_codegen_llvm/src/llvm/mod.rs index 707aeba22ccf7..7becba4ccd4c0 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/mod.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/mod.rs @@ -241,6 +241,10 @@ pub fn set_linkage(llglobal: &Value, linkage: Linkage) { } } +pub fn is_declaration(llglobal: &Value) -> bool { + unsafe { LLVMIsDeclaration(llglobal) == ffi::True } +} + pub fn get_visibility(llglobal: &Value) -> Visibility { unsafe { LLVMGetVisibility(llglobal) }.to_rust() }