diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index 61e165ef272a5..e5cbca01aa051 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -297,9 +297,6 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( target.expect("target for simd intrinsic"), source_info.span, ); - } else if codegen_float_intrinsic_call(fx, intrinsic, args, destination) { - let ret_block = fx.get_block(target.expect("target for float intrinsic")); - fx.bcx.ins().jump(ret_block, &[]); } else { codegen_regular_intrinsic_call( fx, @@ -315,71 +312,13 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( Ok(()) } -fn codegen_float_intrinsic_call<'tcx>( - fx: &mut FunctionCx<'_, '_, 'tcx>, - intrinsic: Symbol, - args: &[Spanned>], - ret: CPlace<'tcx>, -) -> bool { - let (name, arg_count, ty, clif_ty) = match intrinsic { - sym::copysignf16 => return false, // has a fallback - sym::copysignf32 => ("copysignf", 2, fx.tcx.types.f32, types::F32), - sym::copysignf64 => ("copysign", 2, fx.tcx.types.f64, types::F64), - sym::copysignf128 => return false, // has a fallback - - _ => return false, - }; - - if args.len() != arg_count { - bug!("wrong number of args for intrinsic {:?}", intrinsic); - } - - let (a, b, c); - let args = match args { - [x] => { - a = [codegen_operand(fx, &x.node).load_scalar(fx)]; - &a as &[_] - } - [x, y] => { - b = [ - codegen_operand(fx, &x.node).load_scalar(fx), - codegen_operand(fx, &y.node).load_scalar(fx), - ]; - &b - } - [x, y, z] => { - c = [ - codegen_operand(fx, &x.node).load_scalar(fx), - codegen_operand(fx, &y.node).load_scalar(fx), - codegen_operand(fx, &z.node).load_scalar(fx), - ]; - &c - } - _ => unreachable!(), - }; - - let layout = fx.layout_of(ty); - // FIXME(bytecodealliance/wasmtime#8312): Use native Cranelift operations - // for `f16` and `f128` once the lowerings have been implemented in Cranelift. - let val = match intrinsic { - sym::copysignf32 | sym::copysignf64 => fx.bcx.ins().fcopysign(args[0], args[1]), - - _ => { - let input_tys: Vec<_> = args.iter().map(|_| AbiParam::new(clif_ty)).collect(); - fx.lib_call(name, input_tys, vec![AbiParam::new(clif_ty)], args)[0] - } - }; - - let res = CValue::by_val(val, layout); - ret.write_cvalue(fx, res); - - true -} - -/// Used to distinguish fallbacks of float intrinsics. For some we have a codegen fallback, -/// while for others we fallback to an external libcall. -enum IntrinsicFallback { - Fallback(&'static str), +/// How a float intrinsic is lowered: either directly to Cranelift instructions, or to a call to an +/// external (libm/compiler-builtins) function. This is unrelated to the Rust fallback bodies of +/// intrinsics. +// FIXME: the `Libcall` cases could probably all use the Rust fallback bodies instead, which would +// allow removing this enum. +enum FloatIntrinsicLowering { + Libcall(&'static str), Codegen(Value), } @@ -1099,8 +1038,8 @@ fn codegen_regular_intrinsic_call<'tcx>( layout.ty ); }; + use FloatIntrinsicLowering::*; use FloatTy::*; - use IntrinsicFallback::*; let x = arg1.load_scalar(fx); let y = arg2.load_scalar(fx); let z = arg3.load_scalar(fx); @@ -1109,7 +1048,7 @@ fn codegen_regular_intrinsic_call<'tcx>( // sofware emulation, use cranelift intrinsic analogous to llvm.fmuladd.*. (sym::fma | sym::fmuladd, F32 | F64) => Codegen(fx.bcx.ins().fma(x, y, z)), - (sym::fma, F128) => Fallback("fmaf128"), + (sym::fma, F128) => Libcall("fmaf128"), (sym::fmuladd, F128) | (_, F16) => { // We use the intrinsic fallback bodies for the rest @@ -1120,7 +1059,7 @@ fn codegen_regular_intrinsic_call<'tcx>( }; let val = match res { Codegen(val) => val, - Fallback(name) => { + Libcall(name) => { let ty = fx.clif_type(layout.ty).unwrap(); let arg = AbiParam::new(ty); fx.lib_call(name, vec![arg, arg, arg], vec![arg], &[x, y, z])[0] @@ -1141,14 +1080,14 @@ fn codegen_regular_intrinsic_call<'tcx>( layout.ty ); }; + use FloatIntrinsicLowering::*; use FloatTy::*; - use IntrinsicFallback::*; let x = arg1.load_scalar(fx); let y = arg2.load_scalar(fx); let res = match (intrinsic, float_ty) { - (sym::powf, F32) => Fallback("powf"), - (sym::powf, F64) => Fallback("pow"), - (sym::powf, F128) => Fallback("powf128"), + (sym::powf, F32) => Libcall("powf"), + (sym::powf, F64) => Libcall("pow"), + (sym::powf, F128) => Libcall("powf128"), (_, F16) => { // We use the intrinsic fallback bodies for the rest @@ -1159,7 +1098,7 @@ fn codegen_regular_intrinsic_call<'tcx>( }; let val = match res { Codegen(_) => span_bug!(source_info.span, "`powf` is always lowered to a libcall"), - Fallback(name) => { + Libcall(name) => { let ty = fx.clif_type(layout.ty).unwrap(); let arg = AbiParam::new(ty); fx.lib_call(name, vec![arg, arg], vec![arg], &[x, y])[0] @@ -1169,6 +1108,65 @@ fn codegen_regular_intrinsic_call<'tcx>( ret.write_cvalue(fx, val); } + sym::copysign + | sym::minimum + | sym::maximum + | sym::minimum_number_nsz + | sym::maximum_number_nsz => { + intrinsic_args!(fx, args => (arg1, arg2); intrinsic); + let layout = arg1.layout(); + let ty::Float(float_ty) = layout.ty.kind() else { + span_bug!( + source_info.span, + "expected a float type for {:?} intrinsic, but got: {:?}", + intrinsic, + layout.ty + ); + }; + use FloatIntrinsicLowering::*; + use FloatTy::*; + let x = arg1.load_scalar(fx); + let y = arg2.load_scalar(fx); + let res = match (intrinsic, float_ty) { + (sym::copysign, F32 | F64) => Codegen(fx.bcx.ins().fcopysign(x, y)), + + (sym::minimum, F32 | F64) => Codegen(fx.bcx.ins().fmin(x, y)), + (sym::maximum, F32 | F64) => Codegen(fx.bcx.ins().fmax(x, y)), + // FIXME(bytecodealliance/wasmtime#8312): Use `fmin`/`fmax` directly for `f16` and + // `f128` once the lowerings have been implemented in Cranelift. + (sym::minimum, F128) => Codegen(codegen_f16_f128::fmin_f128(fx, x, y)), + (sym::maximum, F128) => Codegen(codegen_f16_f128::fmax_f128(fx, x, y)), + (sym::minimum, F16) => { + Codegen(codegen_f16_f128::maybe_with_f16_to_f32_pair(fx, x, y, |fx, x, y| { + fx.bcx.ins().fmin(x, y) + })) + } + (sym::maximum, F16) => { + Codegen(codegen_f16_f128::maybe_with_f16_to_f32_pair(fx, x, y, |fx, x, y| { + fx.bcx.ins().fmax(x, y) + })) + } + + (sym::minimum_number_nsz, _) => Codegen(crate::num::codegen_float_min(fx, x, y)), + (sym::maximum_number_nsz, _) => Codegen(crate::num::codegen_float_max(fx, x, y)), + + (sym::copysign, F128) | (_, F16) => { + // We use the intrinsic fallback bodies for the rest + return Err(Instance::new_raw(instance.def_id(), instance.args)); + } + + _ => unreachable!(), + }; + let val = match res { + Codegen(val) => val, + Libcall(_) => { + span_bug!(source_info.span, "no libcall lowering for {:?}", intrinsic) + } + }; + let val = CValue::by_val(val, layout); + ret.write_cvalue(fx, val); + } + sym::fabs | sym::sqrt | sym::floor @@ -1193,58 +1191,58 @@ fn codegen_regular_intrinsic_call<'tcx>( layout.ty ); }; + use FloatIntrinsicLowering::*; use FloatTy::*; - use IntrinsicFallback::*; let x = arg.load_scalar(fx); let res = match (intrinsic, float_ty) { (sym::fabs, F32 | F64) => Codegen(fx.bcx.ins().fabs(x)), (sym::sqrt, F32 | F64) => Codegen(fx.bcx.ins().sqrt(x)), - (sym::sqrt, F128) => Fallback("sqrtf128"), + (sym::sqrt, F128) => Libcall("sqrtf128"), (sym::floor, F32 | F64) => Codegen(fx.bcx.ins().floor(x)), - (sym::floor, F128) => Fallback("floorf128"), + (sym::floor, F128) => Libcall("floorf128"), (sym::ceil, F32 | F64) => Codegen(fx.bcx.ins().ceil(x)), - (sym::ceil, F128) => Fallback("ceilf128"), + (sym::ceil, F128) => Libcall("ceilf128"), (sym::trunc, F32 | F64) => Codegen(fx.bcx.ins().trunc(x)), - (sym::trunc, F128) => Fallback("truncf128"), + (sym::trunc, F128) => Libcall("truncf128"), (sym::round_ties_even, F32 | F64) => Codegen(fx.bcx.ins().nearest(x)), - (sym::round_ties_even, F128) => Fallback("rintf128"), + (sym::round_ties_even, F128) => Libcall("rintf128"), - (sym::round, F32) => Fallback("roundf"), - (sym::round, F64) => Fallback("round"), - (sym::round, F128) => Fallback("roundf128"), + (sym::round, F32) => Libcall("roundf"), + (sym::round, F64) => Libcall("round"), + (sym::round, F128) => Libcall("roundf128"), - (sym::exp, F32) => Fallback("expf"), - (sym::exp, F64) => Fallback("exp"), - (sym::exp, F128) => Fallback("expf128"), + (sym::exp, F32) => Libcall("expf"), + (sym::exp, F64) => Libcall("exp"), + (sym::exp, F128) => Libcall("expf128"), - (sym::exp2, F32) => Fallback("exp2f"), - (sym::exp2, F64) => Fallback("exp2"), - (sym::exp2, F128) => Fallback("exp2f128"), + (sym::exp2, F32) => Libcall("exp2f"), + (sym::exp2, F64) => Libcall("exp2"), + (sym::exp2, F128) => Libcall("exp2f128"), - (sym::log, F32) => Fallback("logf"), - (sym::log, F64) => Fallback("log"), - (sym::log, F128) => Fallback("logf128"), + (sym::log, F32) => Libcall("logf"), + (sym::log, F64) => Libcall("log"), + (sym::log, F128) => Libcall("logf128"), - (sym::log2, F32) => Fallback("log2f"), - (sym::log2, F64) => Fallback("log2"), - (sym::log2, F128) => Fallback("log2f128"), + (sym::log2, F32) => Libcall("log2f"), + (sym::log2, F64) => Libcall("log2"), + (sym::log2, F128) => Libcall("log2f128"), - (sym::log10, F32) => Fallback("log10f"), - (sym::log10, F64) => Fallback("log10"), - (sym::log10, F128) => Fallback("log10f128"), + (sym::log10, F32) => Libcall("log10f"), + (sym::log10, F64) => Libcall("log10"), + (sym::log10, F128) => Libcall("log10f128"), - (sym::sin, F32) => Fallback("sinf"), - (sym::sin, F64) => Fallback("sin"), - (sym::sin, F128) => Fallback("sinf128"), + (sym::sin, F32) => Libcall("sinf"), + (sym::sin, F64) => Libcall("sin"), + (sym::sin, F128) => Libcall("sinf128"), - (sym::cos, F32) => Fallback("cosf"), - (sym::cos, F64) => Fallback("cos"), - (sym::cos, F128) => Fallback("cosf128"), + (sym::cos, F32) => Libcall("cosf"), + (sym::cos, F64) => Libcall("cos"), + (sym::cos, F128) => Libcall("cosf128"), (sym::fabs, F128) | (_, F16) => { // FIXME(bytecodealliance/wasmtime#8312): Use the native operations once @@ -1257,7 +1255,7 @@ fn codegen_regular_intrinsic_call<'tcx>( }; let val = match res { Codegen(val) => val, - Fallback(name) => { + Libcall(name) => { let ty = fx.clif_type(layout.ty).unwrap(); fx.lib_call(name, vec![AbiParam::new(ty)], vec![AbiParam::new(ty)], &[x])[0] } @@ -1266,160 +1264,6 @@ fn codegen_regular_intrinsic_call<'tcx>( ret.write_cvalue(fx, val); } - sym::minimumf16 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = codegen_f16_f128::maybe_with_f16_to_f32_pair(fx, a, b, |fx, a, b| { - fx.bcx.ins().fmin(a, b) - }); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f16)); - ret.write_cvalue(fx, val); - } - sym::minimumf32 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = fx.bcx.ins().fmin(a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32)); - ret.write_cvalue(fx, val); - } - sym::minimumf64 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = fx.bcx.ins().fmin(a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64)); - ret.write_cvalue(fx, val); - } - sym::minimumf128 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - // FIXME(bytecodealliance/wasmtime#8312): Use `fmin` once Cranelift - // backend lowerings are implemented. - let val = codegen_f16_f128::fmin_f128(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f128)); - ret.write_cvalue(fx, val); - } - sym::maximumf16 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = codegen_f16_f128::maybe_with_f16_to_f32_pair(fx, a, b, |fx, a, b| { - fx.bcx.ins().fmax(a, b) - }); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f16)); - ret.write_cvalue(fx, val); - } - sym::maximumf32 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = fx.bcx.ins().fmax(a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32)); - ret.write_cvalue(fx, val); - } - sym::maximumf64 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = fx.bcx.ins().fmax(a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64)); - ret.write_cvalue(fx, val); - } - sym::maximumf128 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - // FIXME(bytecodealliance/wasmtime#8312): Use `fmax` once Cranelift - // backend lowerings are implemented. - let val = codegen_f16_f128::fmax_f128(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f128)); - ret.write_cvalue(fx, val); - } - - sym::minimum_number_nsz_f16 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_min(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f16)); - ret.write_cvalue(fx, val); - } - sym::minimum_number_nsz_f32 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_min(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32)); - ret.write_cvalue(fx, val); - } - sym::minimum_number_nsz_f64 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_min(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64)); - ret.write_cvalue(fx, val); - } - sym::minimum_number_nsz_f128 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_min(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f128)); - ret.write_cvalue(fx, val); - } - sym::maximum_number_nsz_f16 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_max(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f16)); - ret.write_cvalue(fx, val); - } - sym::maximum_number_nsz_f32 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_max(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32)); - ret.write_cvalue(fx, val); - } - sym::maximum_number_nsz_f64 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_max(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64)); - ret.write_cvalue(fx, val); - } - sym::maximum_number_nsz_f128 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_max(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f128)); - ret.write_cvalue(fx, val); - } - sym::catch_unwind => { let ret_block = fx.get_block(destination.unwrap()); diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index 5c616c60003b0..ca98ae6319b7f 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -35,38 +35,20 @@ use crate::context::CodegenCx; use crate::intrinsic::simd::generic_simd_intrinsic; use crate::type_of::LayoutGccExt; -fn float_intrinsic<'gcc, 'tcx>( +// GCC doesn't have the intrinsic we want so we use the compiler-builtins one +fn binop_libcall<'gcc, 'tcx>( cx: &CodegenCx<'gcc, 'tcx>, typ: Type<'gcc>, name: &str, -) -> Option> { - // GCC doesn't have the intrinsic we want so we use the compiler-builtins one - Some(cx.context.new_function( +) -> Function<'gcc> { + cx.context.new_function( None, FunctionType::Extern, typ, &[cx.context.new_parameter(None, typ, "a"), cx.context.new_parameter(None, typ, "b")], name, false, - )) -} - -fn get_simple_intrinsic<'gcc, 'tcx>( - cx: &CodegenCx<'gcc, 'tcx>, - name: Symbol, -) -> Option> { - let gcc_name = match name { - sym::minimumf32 => return float_intrinsic(cx, cx.type_f32(), "fminimumf"), - sym::minimumf64 => return float_intrinsic(cx, cx.type_f64(), "fminimum"), - sym::minimumf128 => return float_intrinsic(cx, cx.type_f128(), "fminimumf128"), - sym::maximumf32 => return float_intrinsic(cx, cx.type_f32(), "fmaximumf"), - sym::maximumf64 => return float_intrinsic(cx, cx.type_f64(), "fmaximum"), - sym::maximumf128 => return float_intrinsic(cx, cx.type_f128(), "fmaximumf128"), - sym::copysignf32 => "copysignf", - sym::copysignf64 => "copysign", - _ => return None, - }; - Some(cx.context.get_builtin_function(gcc_name)) + ) } fn get_simple_function_f128<'gcc, 'tcx>( @@ -76,6 +58,7 @@ fn get_simple_function_f128<'gcc, 'tcx>( ) -> Function<'gcc> { let f128_type = cx.type_f128(); let (func_name, args): (&str, &[gccjit::Type<'_>]) = match name { + sym::copysign => ("copysignf128", &[f128_type, f128_type]), sym::ceil => ("ceilf128", &[f128_type]), sym::cos => ("cosf128", &[f128_type]), sym::fabs => ("fabsf128", &[f128_type]), @@ -92,6 +75,8 @@ fn get_simple_function_f128<'gcc, 'tcx>( sym::sqrt => ("sqrtf128", &[f128_type]), sym::powf => ("powf128", &[f128_type, f128_type]), sym::fma => ("fmaf128", &[f128_type, f128_type, f128_type]), + sym::minimum => ("fminimumf128", &[f128_type, f128_type]), + sym::maximum => ("fmaximumf128", &[f128_type, f128_type]), _ => span_bug!(span, "used get_simple_function_f128 for unsupported f128 intrinsic"), }; let args: Vec<_> = args @@ -110,7 +95,7 @@ fn f16_builtin<'gcc, 'tcx>( let f32_type = cx.type_f32(); let builtin_name = match name { sym::ceil => "__builtin_ceilf", - sym::copysignf16 => "__builtin_copysignf", + sym::copysign => "__builtin_copysignf", sym::cos => "cosf", sym::exp => "expf", sym::exp2 => "exp2f", @@ -152,60 +137,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc let name_str = name.as_str(); let fn_args = instance.args; - let simple = get_simple_intrinsic(self, name); - let value = match name { - _ if let Some(func) = simple => self.cx.context.new_call( - self.location, - func, - &args.iter().map(|arg| arg.immediate()).collect::>(), - ), - // FIXME(antoyo): We can probably remove these and use the fallback intrinsic implementation. - sym::minimumf32 | sym::minimumf64 | sym::maximumf32 | sym::maximumf64 => { - let (ty, func_name) = match name { - sym::minimumf32 => (self.cx.float_type, "fminimumf"), - sym::maximumf32 => (self.cx.float_type, "fmaximumf"), - sym::minimumf64 => (self.cx.double_type, "fminimum"), - sym::maximumf64 => (self.cx.double_type, "fmaximum"), - _ => unreachable!(), - }; - let func = self.cx.context.new_function( - None, - FunctionType::Extern, - ty, - &[ - self.cx.context.new_parameter(None, ty, "a"), - self.cx.context.new_parameter(None, ty, "b"), - ], - func_name, - false, - ); - self.cx.context.new_call( - self.location, - func, - &args.iter().map(|arg| arg.immediate()).collect::>(), - ) - } - sym::copysignf16 => f16_builtin(self, name, args), - sym::copysignf128 if self.cx.supports_f128_type => { - let f128_type = self.cx.type_f128(); - let func = self.cx.context.new_function( - None, - FunctionType::Extern, - f128_type, - &[ - self.cx.context.new_parameter(None, f128_type, "a"), - self.cx.context.new_parameter(None, f128_type, "b"), - ], - "copysignf128", - false, - ); - self.cx.context.new_call( - self.location, - func, - &args.iter().map(|arg| arg.immediate()).collect::>(), - ) - } sym::is_val_statically_known => { let a = args[0].immediate(); let builtin = self.context.get_builtin_function("__builtin_constant_p"); @@ -317,7 +249,10 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc } } } - sym::fabs + sym::copysign + | sym::fabs + | sym::minimum + | sym::maximum | sym::sqrt | sym::powf | sym::fma @@ -337,13 +272,28 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc | sym::powi => 'float_op: { let ty = args[0].layout.ty; let ty::Float(float_ty) = *ty.kind() else { - span_bug!(span, "expected float type for fabs intrinsic: {:?}", ty); + span_bug!(span, "expected float type for {:?} intrinsic: {:?}", name, ty); }; use ty::FloatTy::*; let func = match (name, float_ty) { + (sym::copysign, F32) => self.context.get_builtin_function("copysignf"), + (sym::copysign, F64) => self.context.get_builtin_function("copysign"), + (sym::fabs, F32) => self.context.get_builtin_function("fabsf"), (sym::fabs, F64) => self.context.get_builtin_function("fabs"), + // FIXME(antoyo): We can probably remove these and use the fallback intrinsic implementation. + (sym::minimum, F32) => binop_libcall(self, self.type_f32(), "fminimumf"), + (sym::minimum, F64) => binop_libcall(self, self.type_f64(), "fminimum"), + (sym::maximum, F32) => binop_libcall(self, self.type_f32(), "fmaximumf"), + (sym::maximum, F64) => binop_libcall(self, self.type_f64(), "fmaximum"), + + // `f16` has no builtin for these, use the intrinsic fallback bodies instead. + (sym::minimum | sym::maximum, F16) => { + let fallback = Instance::new_raw(instance.def_id(), instance.args); + return IntrinsicResult::Fallback(fallback); + } + (sym::sqrt, F32) => self.context.get_builtin_function("sqrtf"), (sym::sqrt, F64) => self.context.get_builtin_function("sqrt"), diff --git a/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs b/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs index 3533262ee0c10..c0349b6003319 100644 --- a/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs +++ b/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs @@ -273,7 +273,7 @@ impl CodegenBackend for LlvmCodegenBackend { sym::round, sym::round_ties_even, sym::fma, - sym::copysignf16, sym::copysignf32, sym::copysignf64, sym::copysignf128, + sym::copysign, ]; will_not_use_fallback diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 84f7f3a5fde5a..12392c91ac14c 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -48,42 +48,6 @@ use crate::llvm::{self, Attribute, AttributePlace, Metadata, Type, TypeKind, Val use crate::type_of::LayoutLlvmExt; use crate::va_arg::emit_va_arg; -fn call_simple_intrinsic<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - name: Symbol, - args: &[OperandRef<'tcx, Value<'ll>>], -) -> Option> { - let llvm_version = crate::llvm_util::get_version(); - // minimum/maximum were broken for f64/f128 before - // . - // We use the fallback body there. - let fixed_minmax = llvm_version >= (23, 0, 0); - - let (base_name, type_params): (&'static str, &[Type<'ll>]) = match name { - sym::minimumf16 => ("llvm.minimum", &[bx.type_f16()]), - sym::minimumf32 => ("llvm.minimum", &[bx.type_f32()]), - sym::minimumf64 if fixed_minmax => ("llvm.minimum", &[bx.type_f64()]), - sym::minimumf128 if fixed_minmax => ("llvm.minimum", &[bx.type_f128()]), - - sym::maximumf16 => ("llvm.maximum", &[bx.type_f16()]), - sym::maximumf32 => ("llvm.maximum", &[bx.type_f32()]), - sym::maximumf64 if fixed_minmax => ("llvm.maximum", &[bx.type_f64()]), - sym::maximumf128 if fixed_minmax => ("llvm.maximum", &[bx.type_f128()]), - - sym::copysignf16 => ("llvm.copysign", &[bx.type_f16()]), - sym::copysignf32 => ("llvm.copysign", &[bx.type_f32()]), - sym::copysignf64 => ("llvm.copysign", &[bx.type_f64()]), - sym::copysignf128 => ("llvm.copysign", &[bx.type_f128()]), - - _ => return None, - }; - Some(bx.call_intrinsic( - base_name, - type_params, - &args.iter().map(|arg| arg.immediate()).collect::>(), - )) -} - impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { fn black_box(&mut self, result: PlaceRef<'tcx, Value<'ll>>, span: Span) { let result_val_span = [result.val.llval]; @@ -135,18 +99,9 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { let name = tcx.item_name(instance.def_id()); let fn_args = instance.args; - let simple = call_simple_intrinsic(self, name, args); let llval = match name { - _ if simple.is_some() => simple.unwrap(), - sym::minimum_number_nsz_f16 - | sym::minimum_number_nsz_f32 - | sym::minimum_number_nsz_f64 - | sym::minimum_number_nsz_f128 - | sym::maximum_number_nsz_f16 - | sym::maximum_number_nsz_f32 - | sym::maximum_number_nsz_f64 - | sym::maximum_number_nsz_f128 => { - let intrinsic_name = if name.as_str().starts_with("min") { + sym::minimum_number_nsz | sym::maximum_number_nsz => { + let intrinsic_name = if name == sym::minimum_number_nsz { "llvm.minimumnum" } else { "llvm.maximumnum" @@ -503,7 +458,8 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { } } - sym::fabs + sym::copysign + | sym::fabs | sym::sqrt | sym::powf | sym::fma @@ -520,7 +476,9 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { | sym::log2 | sym::sin | sym::cos - | sym::powi => { + | sym::powi + | sym::minimum + | sym::maximum => { let ty = args[0].layout.ty; let ty::Float(f) = ty.kind() else { span_bug!( @@ -532,6 +490,7 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { }; let llty = self.type_float_from_ty(*f); let llvm_name = match name { + sym::copysign => "llvm.copysign", sym::fabs => "llvm.fabs", sym::sqrt => "llvm.sqrt", sym::powf => "llvm.pow", @@ -555,6 +514,19 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { sym::cos => "llvm.cos", sym::powi => "llvm.powi", + // minimum/maximum were broken for f64/f128 before + // . + // We use the fallback body there. + sym::minimum | sym::maximum + if llvm_version < (23, 0, 0) + && matches!(f, ty::FloatTy::F64 | ty::FloatTy::F128) => + { + let fallback = ty::Instance::new_raw(instance.def_id(), instance.args); + return IntrinsicResult::Fallback(fallback); + } + sym::minimum => "llvm.minimum", + sym::maximum => "llvm.maximum", + _ => bug!(), }; @@ -1086,7 +1058,7 @@ fn can_autocast<'ll>(cx: &CodegenCx<'ll, '_>, rust_ty: Type<'ll>, llvm_ty: Type< _ if let Some((llvm_element_ty, element_count)) = cx.vector_element_type_and_length(llvm_ty) => { - if llvm_element_ty == cx.type_bf16() { + if llvm_element_ty == cx.type_f16b() { rust_ty == cx.type_vector(cx.type_i16(), element_count) } else if llvm_element_ty == cx.type_i1() { let int_width = element_count.next_power_of_two().max(8); diff --git a/compiler/rustc_codegen_llvm/src/type_.rs b/compiler/rustc_codegen_llvm/src/type_.rs index 00bfc9bd7742c..a659990c05a6d 100644 --- a/compiler/rustc_codegen_llvm/src/type_.rs +++ b/compiler/rustc_codegen_llvm/src/type_.rs @@ -168,10 +168,6 @@ impl<'ll, CX: Borrow>> GenericCx<'ll, CX> { } } - pub(crate) fn type_bf16(&self) -> Type<'ll> { - unsafe { llvm::LLVMBFloatTypeInContext(self.llcx()) } - } - pub(crate) fn type_array(&self, ty: Type<'ll>, len: u64) -> Type<'ll> { unsafe { llvm::LLVMArrayType2(ty, len) } } diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index cb98672df7838..d9278c1d97a5e 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -582,54 +582,36 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { self.write_scalar(Scalar::from_target_usize(align.bytes(), self), dest)?; } - sym::minimum_number_nsz_f16 => { - self.float_minmax_intrinsic::(args, MinMax::MinimumNumberNsz, dest)? - } - sym::minimum_number_nsz_f32 => { - self.float_minmax_intrinsic::(args, MinMax::MinimumNumberNsz, dest)? - } - sym::minimum_number_nsz_f64 => { - self.float_minmax_intrinsic::(args, MinMax::MinimumNumberNsz, dest)? - } - sym::minimum_number_nsz_f128 => { - self.float_minmax_intrinsic::(args, MinMax::MinimumNumberNsz, dest)? - } - - sym::minimumf16 => self.float_minmax_intrinsic::(args, MinMax::Minimum, dest)?, - sym::minimumf32 => { - self.float_minmax_intrinsic::(args, MinMax::Minimum, dest)? - } - sym::minimumf64 => { - self.float_minmax_intrinsic::(args, MinMax::Minimum, dest)? - } - sym::minimumf128 => self.float_minmax_intrinsic::(args, MinMax::Minimum, dest)?, - - sym::maximum_number_nsz_f16 => { - self.float_minmax_intrinsic::(args, MinMax::MaximumNumberNsz, dest)? - } - sym::maximum_number_nsz_f32 => { - self.float_minmax_intrinsic::(args, MinMax::MaximumNumberNsz, dest)? - } - sym::maximum_number_nsz_f64 => { - self.float_minmax_intrinsic::(args, MinMax::MaximumNumberNsz, dest)? - } - sym::maximum_number_nsz_f128 => { - self.float_minmax_intrinsic::(args, MinMax::MaximumNumberNsz, dest)? - } - - sym::maximumf16 => self.float_minmax_intrinsic::(args, MinMax::Maximum, dest)?, - sym::maximumf32 => { - self.float_minmax_intrinsic::(args, MinMax::Maximum, dest)? - } - sym::maximumf64 => { - self.float_minmax_intrinsic::(args, MinMax::Maximum, dest)? + sym::minimum + | sym::maximum + | sym::minimum_number_nsz + | sym::maximum_number_nsz + | sym::copysign => { + let arg1 = self.read_immediate(&args[0])?; + let arg2 = self.read_immediate(&args[1])?; + let ty::Float(float_ty) = arg1.layout.ty.kind() else { + span_bug!( + self.cur_span(), + "non-float type for float intrinsic: {}", + arg1.layout.ty, + ); + }; + let out_val = match float_ty { + FloatTy::F16 => { + self.binop_float_intrinsic::(intrinsic_name, arg1, arg2)? + } + FloatTy::F32 => { + self.binop_float_intrinsic::(intrinsic_name, arg1, arg2)? + } + FloatTy::F64 => { + self.binop_float_intrinsic::(intrinsic_name, arg1, arg2)? + } + FloatTy::F128 => { + self.binop_float_intrinsic::(intrinsic_name, arg1, arg2)? + } + }; + self.write_scalar(out_val, dest)?; } - sym::maximumf128 => self.float_minmax_intrinsic::(args, MinMax::Maximum, dest)?, - - sym::copysignf16 => self.float_copysign_intrinsic::(args, dest)?, - sym::copysignf32 => self.float_copysign_intrinsic::(args, dest)?, - sym::copysignf64 => self.float_copysign_intrinsic::(args, dest)?, - sym::copysignf128 => self.float_copysign_intrinsic::(args, dest)?, sym::fabs | sym::floor | sym::ceil | sym::trunc | sym::round | sym::round_ties_even => { let arg = self.read_immediate(&args[0])?; @@ -1197,17 +1179,34 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } } - fn float_minmax( + fn binop_float_intrinsic( &self, - a: Scalar, - b: Scalar, - op: MinMax, + name: Symbol, + arg1: ImmTy<'tcx, M::Provenance>, + arg2: ImmTy<'tcx, M::Provenance>, ) -> InterpResult<'tcx, Scalar> where F: rustc_apfloat::Float + rustc_apfloat::FloatConvert + Into>, { - let a: F = a.to_float()?; - let b: F = b.to_float()?; + let x: F = arg1.to_scalar().to_float()?; + let y: F = arg2.to_scalar().to_float()?; + match name { + // bitwise, no NaN adjustments + sym::copysign => interp_ok(x.copy_sign(y).into()), + + sym::minimum => self.float_minmax(x, y, MinMax::Minimum), + sym::maximum => self.float_minmax(x, y, MinMax::Maximum), + sym::minimum_number_nsz => self.float_minmax(x, y, MinMax::MinimumNumberNsz), + sym::maximum_number_nsz => self.float_minmax(x, y, MinMax::MaximumNumberNsz), + + _ => bug!("not a unary float intrinsic: {}", name), + } + } + + fn float_minmax(&self, a: F, b: F, op: MinMax) -> InterpResult<'tcx, Scalar> + where + F: rustc_apfloat::Float + rustc_apfloat::FloatConvert + Into>, + { let res = if matches!(op, MinMax::MinimumNumberNsz | MinMax::MaximumNumberNsz) && a == b { // They are definitely not NaN (those are never equal), but they could be `+0` and `-0`. // Let the machine decide which one to return. @@ -1225,36 +1224,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { interp_ok(res.into()) } - fn float_minmax_intrinsic( - &mut self, - args: &[OpTy<'tcx, M::Provenance>], - op: MinMax, - dest: &PlaceTy<'tcx, M::Provenance>, - ) -> InterpResult<'tcx, ()> - where - F: rustc_apfloat::Float + rustc_apfloat::FloatConvert + Into>, - { - let res = - self.float_minmax::(self.read_scalar(&args[0])?, self.read_scalar(&args[1])?, op)?; - self.write_scalar(res, dest)?; - interp_ok(()) - } - - fn float_copysign_intrinsic( - &mut self, - args: &[OpTy<'tcx, M::Provenance>], - dest: &PlaceTy<'tcx, M::Provenance>, - ) -> InterpResult<'tcx, ()> - where - F: rustc_apfloat::Float + rustc_apfloat::FloatConvert + Into>, - { - let a: F = self.read_scalar(&args[0])?.to_float()?; - let b: F = self.read_scalar(&args[1])?.to_float()?; - // bitwise, no NaN adjustments - self.write_scalar(a.copy_sign(b), dest)?; - interp_ok(()) - } - fn float_round( &mut self, x: F, diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs b/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs index 9250aed30276e..091c732af82b4 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs @@ -808,10 +808,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { let left = left.to_scalar(); let right = right.to_scalar(); interp_ok(match float_ty { - FloatTy::F16 => self.float_minmax::(left, right, op)?, - FloatTy::F32 => self.float_minmax::(left, right, op)?, - FloatTy::F64 => self.float_minmax::(left, right, op)?, - FloatTy::F128 => self.float_minmax::(left, right, op)?, + FloatTy::F16 => self.float_minmax::(left.to_float()?, right.to_float()?, op)?, + FloatTy::F32 => self.float_minmax::(left.to_float()?, right.to_float()?, op)?, + FloatTy::F64 => self.float_minmax::(left.to_float()?, right.to_float()?, op)?, + FloatTy::F128 => self.float_minmax::(left.to_float()?, right.to_float()?, op)?, }) } diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index f1919cab3957e..c059b1d1ccaa3 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -1467,7 +1467,7 @@ pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(DiagCtxtHan // (e.g. `RUST_BACKTRACE=1`) if env::var_os("RUST_BACKTRACE").is_none() { // HACK: this check is extremely dumb, but we don't really need it to be smarter since this should only happen in the test suite anyway. - let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing"); + let ui_testing = env::args_os().any(|arg| arg == "-Zui-testing"); if env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing { panic::set_backtrace_style(panic::BacktraceStyle::Short); } else { diff --git a/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs b/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs index bc1f2389cf55e..79c6336978d57 100644 --- a/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs +++ b/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs @@ -595,7 +595,11 @@ impl AnnotateSnippetEmitter { ) -> Group<'a> { let filename = sm.filename_for_diagnostics(file_name).to_string_lossy().to_string(); let mut line_tracker = vec![]; - for (i, a) in annotations.into_iter().enumerate() { + for (i, a) in annotations + .into_iter() + .filter(|a| !matches!(a.kind, AnnotationKind::Visible)) + .enumerate() + { let lo = sm.lookup_char_pos(a.span.lo()); let hi = sm.lookup_char_pos(a.span.hi()); if i == 0 || (a.label.is_some()) { diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index cbacbd138500c..9595d1cbb9428 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -90,10 +90,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi | sym::contract_check_ensures | sym::contract_check_requires | sym::contract_checks - | sym::copysignf16 - | sym::copysignf32 - | sym::copysignf64 - | sym::copysignf128 + | sym::copysign | sym::cos | sym::ctlz | sym::ctpop @@ -122,22 +119,10 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi | sym::log | sym::log2 | sym::log10 - | sym::maximum_number_nsz_f16 - | sym::maximum_number_nsz_f32 - | sym::maximum_number_nsz_f64 - | sym::maximum_number_nsz_f128 - | sym::maximumf16 - | sym::maximumf32 - | sym::maximumf64 - | sym::maximumf128 - | sym::minimum_number_nsz_f16 - | sym::minimum_number_nsz_f32 - | sym::minimum_number_nsz_f64 - | sym::minimum_number_nsz_f128 - | sym::minimumf16 - | sym::minimumf32 - | sym::minimumf64 - | sym::minimumf128 + | sym::maximum + | sym::maximum_number_nsz + | sym::minimum + | sym::minimum_number_nsz | sym::mul_with_overflow | sym::needs_drop | sym::offload @@ -449,34 +434,11 @@ pub(crate) fn check_intrinsic_type( | sym::round | sym::sqrt => (1, 0, vec![param(0)], param(0)), - sym::minimum_number_nsz_f16 => (0, 0, vec![tcx.types.f16, tcx.types.f16], tcx.types.f16), - sym::minimum_number_nsz_f32 => (0, 0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - sym::minimum_number_nsz_f64 => (0, 0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - sym::minimum_number_nsz_f128 => { - (0, 0, vec![tcx.types.f128, tcx.types.f128], tcx.types.f128) - } - - sym::minimumf16 => (0, 0, vec![tcx.types.f16, tcx.types.f16], tcx.types.f16), - sym::minimumf32 => (0, 0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - sym::minimumf64 => (0, 0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - sym::minimumf128 => (0, 0, vec![tcx.types.f128, tcx.types.f128], tcx.types.f128), - - sym::maximum_number_nsz_f16 => (0, 0, vec![tcx.types.f16, tcx.types.f16], tcx.types.f16), - sym::maximum_number_nsz_f32 => (0, 0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - sym::maximum_number_nsz_f64 => (0, 0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - sym::maximum_number_nsz_f128 => { - (0, 0, vec![tcx.types.f128, tcx.types.f128], tcx.types.f128) - } - - sym::maximumf16 => (0, 0, vec![tcx.types.f16, tcx.types.f16], tcx.types.f16), - sym::maximumf32 => (0, 0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - sym::maximumf64 => (0, 0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - sym::maximumf128 => (0, 0, vec![tcx.types.f128, tcx.types.f128], tcx.types.f128), - - sym::copysignf16 => (0, 0, vec![tcx.types.f16, tcx.types.f16], tcx.types.f16), - sym::copysignf32 => (0, 0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - sym::copysignf64 => (0, 0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - sym::copysignf128 => (0, 0, vec![tcx.types.f128, tcx.types.f128], tcx.types.f128), + sym::copysign + | sym::minimum + | sym::maximum + | sym::minimum_number_nsz + | sym::maximum_number_nsz => (1, 0, vec![param(0), param(0)], param(0)), sym::powf => (1, 0, vec![param(0), param(0)], param(0)), diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 2f67e3c017029..1d57f856687b4 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -657,7 +657,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.check_pat_ref(pat, inner, pinned, mutbl, expected, pat_info) } PatKind::Slice(before, slice, after) => { - self.check_pat_slice(pat.span, before, slice, after, expected, pat_info) + self.check_pat_slice(pat.span, pat.hir_id, before, slice, after, expected, pat_info) } } } @@ -3099,6 +3099,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn check_pat_slice( &self, span: Span, + slice_id: HirId, before: &'tcx [Pat<'tcx>], slice: Option<&'tcx Pat<'tcx>>, after: &'tcx [Pat<'tcx>], @@ -3136,7 +3137,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // The expected type must be an array or slice, but was neither, so error. _ => { let guar = expected.error_reported().err().unwrap_or_else(|| { - self.error_expected_array_or_slice(span, expected, pat_info) + self.error_expected_array_or_slice(span, slice_id, expected, pat_info) }); let err = Ty::new_error(self.tcx, guar); (err, Some(err), err) @@ -3264,6 +3265,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn error_expected_array_or_slice( &self, span: Span, + slice_id: HirId, expected_ty: Ty<'tcx>, pat_info: PatInfo<'tcx>, ) -> ErrorGuaranteed { @@ -3287,12 +3289,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (is_slice_or_array_or_vector, resolved_ty) = self.is_slice_or_array_or_vector(resolved_ty); match resolved_ty.kind() { - ty::Adt(adt_def, _) + ty::Adt(adt_def, args) if self.tcx.is_diagnostic_item(sym::Option, adt_def.did()) || self.tcx.is_diagnostic_item(sym::Result, adt_def.did()) => { - // Slicing won't work here, but `.as_deref()` might (issue #91328). - as_deref = Some(diagnostics::AsDerefSuggestion { span: span.shrink_to_hi() }); + let is_option = self.tcx.is_diagnostic_item(sym::Option, adt_def.did()); + let deref_ty = args.type_at(0).peel_refs(); + if self.can_eq(self.param_env, expected_ty.peel_refs(), deref_ty) + && self.slice_pattern_is_direct_payload(ti.hir_id, slice_id, is_option) + { + as_deref = + Some(diagnostics::AsDerefSuggestion { span: span.shrink_to_hi() }); + } } _ => (), } @@ -3311,6 +3319,77 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }) } + fn slice_pattern_is_direct_payload( + &self, + top_pat_id: HirId, + slice_id: HirId, + is_option: bool, + ) -> bool { + let Some(ctor_id) = self.next_significant_pat(slice_id, top_pat_id) else { + return false; + }; + self.hir_pat_is_some_or_ok(ctor_id, is_option) + && self.only_transparent_pats_until(ctor_id, top_pat_id) + } + + /// First ancestor pattern that is not `&`, a guard, a binding, or an or-pattern. + /// `None` when that walk reaches `top_pat_id` or leaves the pattern without one. + fn next_significant_pat(&self, start: HirId, top_pat_id: HirId) -> Option { + for (id, node) in self.tcx.hir_parent_iter(start) { + let hir::Node::Pat(pat) = node else { return None }; + if self.pat_is_transparent(pat) { + if id == top_pat_id { + return None; + } + continue; + } + return Some(id); + } + None + } + + /// `start` is `top_pat_id`, or every pattern from `start` up through `top_pat_id` + /// is `&`, a guard, a binding, or an or-pattern. + fn only_transparent_pats_until(&self, start: HirId, top_pat_id: HirId) -> bool { + if start == top_pat_id { + return true; + } + for (id, node) in self.tcx.hir_parent_iter(start) { + let hir::Node::Pat(pat) = node else { return false }; + if !self.pat_is_transparent(pat) { + return false; + } + if id == top_pat_id { + return true; + } + } + false + } + + fn pat_is_transparent(&self, pat: &Pat<'_>) -> bool { + matches!( + pat.kind, + PatKind::Ref(..) | PatKind::Guard(..) | PatKind::Binding(..) | PatKind::Or(..) + ) + } + + fn hir_pat_is_some_or_ok(&self, hir_id: HirId, is_option: bool) -> bool { + let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else { return false }; + let PatKind::TupleStruct(ref qpath, ..) = pat.kind else { return false }; + self.tuple_struct_is_some_or_ok(qpath, is_option) + } + + fn tuple_struct_is_some_or_ok(&self, qpath: &hir::QPath<'tcx>, is_option: bool) -> bool { + let lang_item = if is_option { LangItem::OptionSome } else { LangItem::ResultOk }; + let hir::QPath::Resolved(_, path) = qpath else { return false }; + let variant_id = match path.res { + Res::Def(DefKind::Ctor(..), ctor_id) => self.tcx.parent(ctor_id), + Res::Def(DefKind::Variant, variant_id) => variant_id, + _ => return false, + }; + self.tcx.is_lang_item(variant_id, lang_item) + } + fn is_slice_or_array_or_vector(&self, ty: Ty<'tcx>) -> (bool, Ty<'tcx>) { match ty.kind() { ty::Adt(adt_def, _) if self.tcx.is_diagnostic_item(sym::Vec, adt_def.did()) => { diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 3c59017c78d85..3136b9ae41447 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -2642,19 +2642,16 @@ fn truncate_place_to_len_and_update_capture_kind<'tcx>( // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so // we don't need to worry about that case here. match curr_mode { - ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) => { - for i in len..place.projections.len() { - if place.projections[i].kind == ProjectionKind::Deref + ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) + if (len..place.projections.len()).any(|i| { + place.projections[i].kind == ProjectionKind::Deref && is_mut_ref(place.ty_before_projection(i)) - { - *curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable); - break; - } - } + }) => + { + *curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable); } - ty::UpvarCapture::ByRef(..) => {} - ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {} + ty::UpvarCapture::ByRef(_) | ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {} } place.projections.truncate(len); diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index 489973000e1a1..ea2f0010742d7 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -29,6 +29,7 @@ #include "llvm/Passes/StandardInstrumentations.h" #include "llvm/Plugins/PassPlugin.h" #include "llvm/Support/CBindingWrapping.h" +#include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Program.h" #include "llvm/Support/TimeProfiler.h" @@ -62,7 +63,9 @@ using namespace llvm; +#if LLVM_VERSION_LT(24, 0) static codegen::RegisterCodeGenFlags CGF; +#endif typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef; @@ -453,6 +456,8 @@ extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) { return; Initialized = true; #if LLVM_VERSION_GE(24, 0) + for (const cl::LibraryOptions *L : codegen::getToolOptions()) + cl::addLibraryOptions(*L); char *Err; if (LLVMParseCommandLineOptionsWithError(Argc, Argv, "", &Err)) { // FIXME: Report the error via Rust's diagnostics infrastructure. diff --git a/compiler/rustc_metadata/src/diagnostics.rs b/compiler/rustc_metadata/src/diagnostics.rs index 21091ef70d3c8..2f061c6f2f92c 100644 --- a/compiler/rustc_metadata/src/diagnostics.rs +++ b/compiler/rustc_metadata/src/diagnostics.rs @@ -525,10 +525,17 @@ impl Diagnostic<'_> for CannotFindCrate { // Recommend -Zbuild-std even on stable builds for Tier 3 targets because // it's the recommended way to use the target, the user should switch to nightly. if self.is_nightly_build || !has_precompiled_std { - diag.help(msg!( - "consider building the standard library from source with \ - `cargo build -Zbuild-std`" - )); + if self.crate_name == sym::core && self.missing_core { + diag.help(msg!( + "consider building the `core` library from source with \ + `cargo build -Zbuild-std=core`" + )); + } else { + diag.help(msg!( + "consider building the standard library from source with \ + `cargo build -Zbuild-std`" + )); + } } } else if self.crate_name == self.profiler_runtime { diag.note(msg!("the compiler may have been built without the profiler runtime")); diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index f39cfacd6798c..57a5202730570 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -759,10 +759,7 @@ symbols! { copy, copy_closures, copy_nonoverlapping, - copysignf16, - copysignf32, - copysignf64, - copysignf128, + copysign, core, core_panic, core_panic_2015_macro, @@ -1314,14 +1311,8 @@ symbols! { masked, match_beginning_vert, match_default_bindings, - maximum_number_nsz_f16, - maximum_number_nsz_f32, - maximum_number_nsz_f64, - maximum_number_nsz_f128, - maximumf16, - maximumf32, - maximumf64, - maximumf128, + maximum, + maximum_number_nsz, may_dangle, may_unwind, maybe_dangling, @@ -1353,14 +1344,8 @@ symbols! { min_generic_const_args, min_specialization, min_type_alias_impl_trait, - minimum_number_nsz_f16, - minimum_number_nsz_f32, - minimum_number_nsz_f64, - minimum_number_nsz_f128, - minimumf16, - minimumf32, - minimumf64, - minimumf128, + minimum, + minimum_number_nsz, mips, mips32r6, mips64, diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 13ee44fd6bb5e..fd9f76fbeded6 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -2680,11 +2680,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { types.dedup(); let all_types_equal = types.len() == 1; - let end = if candidates.len() <= 9 || self.tcx.sess.opts.verbose { - candidates.len() - } else { - 8 - }; if candidates.len() < 5 { let spans: Vec<_> = candidates.iter().map(|&(_, def_id)| self.tcx.def_span(def_id)).collect(); @@ -2728,7 +2723,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let mut tuple_min_arity = usize::MAX; let mut tuple_max_arity = 0_usize; let mut last_arity = None; - let mut all_types_tuples_cont_arity = true; + let mut all_tuples_cont_arity = true; candidates.sort_by(|(c1, _), (c2, _)| { if let ty::Tuple(tys1) = c1.self_ty().kind() && let ty::Tuple(tys2) = c2.self_ty().kind() @@ -2738,24 +2733,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { std::cmp::Ordering::Equal } }); - let candidate_names: Vec = candidates + + let mut candidate_names: Vec = candidates .iter() .map(|(c, _)| { if all_traits_equal { - if all_types_tuples_cont_arity - && let ty::Tuple(tys) = c.self_ty().kind() - && last_arity.map_or(1, |a: usize| a.abs_diff(tys.len())) == 1 - { - last_arity = Some(tys.len()); - if tys.len() > tuple_max_arity { - tuple_max_arity = tys.len(); - } - if tys.len() < tuple_min_arity { - tuple_min_arity = tys.len(); - } - } else { - all_types_tuples_cont_arity = false; - } format!( "\n {}", self.tcx.short_string(c.self_ty(), err.long_ty_path()) @@ -2777,28 +2759,97 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }) .collect(); - let details = if all_traits_equal && all_types_tuples_cont_arity { - if tuple_min_arity == 0 { + let mut all_tuples_impl_the_same_trait = true; + let mut last_tuple_trait_ref = None; + + fn have_same_trait_path(a: &TraitRef<'_>, b: &TraitRef<'_>) -> bool { + a.print_only_trait_path().to_string() == b.print_only_trait_path().to_string() + } + // `candidates` can contain only tuples or a variety of other types that include tuples. + // Find and locates tuples in `candidates` and computes some metrics: checks if they + // are continuous by arity, if so compute the min and the max arity of these tuples and + // check if they implement all the same trait or not. + let (tuples_candidates, tuples_range) = { + let tuples_indexes: Vec = candidates + .iter() + .enumerate() + .filter_map(|(idx, (c, _))| { + if let ty::Tuple(tys) = c.self_ty().kind() { + if all_tuples_cont_arity + && last_arity.map_or(1, |a: usize| a.abs_diff(tys.len())) == 1 + { + last_arity = Some(tys.len()); + if tys.len() > tuple_max_arity { + tuple_max_arity = tys.len(); + } + if tys.len() < tuple_min_arity { + tuple_min_arity = tys.len(); + } + if all_tuples_impl_the_same_trait + && have_same_trait_path( + last_tuple_trait_ref.map_or(c, |e: &TraitRef<'_>| e), + c, + ) + { + last_tuple_trait_ref = Some(c); + } else { + all_tuples_impl_the_same_trait = false; + } + } else { + all_tuples_cont_arity = false; + } + Some(idx) + } else { + None + } + }) + .collect(); + let (start, end) = ( + tuples_indexes.first().map_or_default(|idx| *idx), + tuples_indexes.last().map_or_default(|idx| *idx + 1), + ); + (&candidates[start..end], start..end) + }; + + // When all the types contained in `candidates` are tuples that are contiguous by arity + // and implement the same trait, or when there exists a subset of tuples in `candidates` + // that are contiguous by arity and implement the same trait, then the list of tuples can + // be factorized from `candidates_names`. + if !tuples_candidates.is_empty() + && all_tuples_cont_arity + && (all_traits_equal || all_tuples_impl_the_same_trait) + { + let details = if tuple_min_arity == 0 { format!("up to tuples of arity {tuple_max_arity}") + } else if !all_traits_equal { + format!("for tuples of arity {tuple_min_arity} to {tuple_max_arity}") } else { format!( "for tuples of arity {tuple_min_arity} up to and including {tuple_max_arity}" ) - } - } else { - String::new() - }; - let (candidate_names, end) = if all_traits_equal && all_types_tuples_cont_arity { - ( - vec![ - // (T₁, T₂, …, Tₙ) - format!("\n (T\u{2081}, T\u{2082}, …, T\u{2099}) {details}"), - ], - 1, - ) + }; + let impl_trait = if all_traits_equal { + String::new() + } else { + let c = tuples_candidates[0].0; + format!( + " implements `{}`", + self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path()) + ) + }; + let simplified_output = [ + // (T₁, T₂, …, Tₙ) + format!("\n `(T\u{2081}, T\u{2082}, …, T\u{2099})` {details}{impl_trait}"), + ]; + candidate_names.splice(tuples_range, simplified_output); + } + + let end = if candidate_names.len() <= 9 || self.tcx.sess.opts.verbose { + candidate_names.len() } else { - (candidate_names, end) + 8 }; + let msg = if all_types_equal { format!( "`{}` implements trait `{}`", diff --git a/compiler/rustc_type_ir/src/relate/solver_relating.rs b/compiler/rustc_type_ir/src/relate/solver_relating.rs index 3a7056234553b..e411d79e44dd4 100644 --- a/compiler/rustc_type_ir/src/relate/solver_relating.rs +++ b/compiler/rustc_type_ir/src/relate/solver_relating.rs @@ -2,6 +2,7 @@ use tracing::{debug, instrument}; use self::combine::{PredicateEmittingRelation, super_combine_consts, super_combine_tys}; use crate::data_structures::DelayedSet; +use crate::region_constraint::{LeafRegionConstraint, NoSpan, RegionConstraint}; use crate::relate::combine::combine_ty_args; pub use crate::relate::*; use crate::solve::{Goal, VisibleForLeakCheck}; @@ -239,14 +240,42 @@ where #[instrument(skip(self), level = "trace")] fn regions(&mut self, a: Region, b: Region) -> RelateResult> { - match self.ambient_variance { - // Subtype(&'a u8, &'b u8) => Outlives('a: 'b) => SubRegion('b, 'a) - ty::Covariant => self.infcx.sub_regions(b, a, VisibleForLeakCheck::Yes, self.span), - // Suptype(&'a u8, &'b u8) => Outlives('b: 'a) => SubRegion('a, 'b) - ty::Contravariant => self.infcx.sub_regions(a, b, VisibleForLeakCheck::Yes, self.span), - ty::Invariant => self.infcx.equate_regions(a, b, VisibleForLeakCheck::Yes, self.span), - ty::Bivariant => { - unreachable!("Expected bivariance to be handled in relate_with_variance") + if self.cx().assumptions_on_binders() { + let region_outlives = |a, b| { + RegionConstraint::new_leaf(LeafRegionConstraint::RegionOutlives(a, b, NoSpan)) + }; + + match self.ambient_variance { + ty::Bivariant => { + unreachable!("Expected bivariance to be handled in relate_with_variance") + } + _ if a == b => return Ok(a), + ty::Covariant => { + self.infcx.register_solver_region_constraint(region_outlives(a, b), self.span) + } + ty::Contravariant => { + self.infcx.register_solver_region_constraint(region_outlives(b, a), self.span) + } + ty::Invariant => { + self.infcx.equate_regions(a, b, VisibleForLeakCheck::Yes, self.span); + self.infcx.register_solver_region_constraint(region_outlives(a, b), self.span); + self.infcx.register_solver_region_constraint(region_outlives(b, a), self.span); + } + } + } else { + match self.ambient_variance { + // Subtype(&'a u8, &'b u8) => Outlives('a: 'b) => SubRegion('b, 'a) + ty::Covariant => self.infcx.sub_regions(b, a, VisibleForLeakCheck::Yes, self.span), + // Suptype(&'a u8, &'b u8) => Outlives('b: 'a) => SubRegion('a, 'b) + ty::Contravariant => { + self.infcx.sub_regions(a, b, VisibleForLeakCheck::Yes, self.span) + } + ty::Invariant => { + self.infcx.equate_regions(a, b, VisibleForLeakCheck::Yes, self.span) + } + ty::Bivariant => { + unreachable!("Expected bivariance to be handled in relate_with_variance") + } } } diff --git a/library/core/src/intrinsics/bounds.rs b/library/core/src/intrinsics/bounds.rs index 87d00ece91bc0..1a7f5d5e8c5af 100644 --- a/library/core/src/intrinsics/bounds.rs +++ b/library/core/src/intrinsics/bounds.rs @@ -45,67 +45,48 @@ impl ChangePointee for *const T { /// # Safety /// Must actually *be* such a type. pub unsafe trait FloatPrimitive: - Sized + Copy + core::ops::Mul + core::ops::Add + Sized + Copy + PartialOrd + core::ops::Mul + core::ops::Add { - type UInt: const core::ops::BitOr - + const core::ops::BitAnd - + const core::ops::Not; + type UInt: core::ops::BitOr + + core::ops::BitAnd + + core::ops::Not; const SIGN_MASK: Self::UInt; fn to_bits(self) -> Self::UInt; fn from_bits(bits: Self::UInt) -> Self; + fn is_nan(self) -> bool; + fn is_sign_positive(self) -> bool; + fn is_sign_negative(self) -> bool; } -unsafe impl FloatPrimitive for f16 { - type UInt = u16; - const SIGN_MASK: Self::UInt = f16::SIGN_MASK; - #[inline] - fn to_bits(self) -> Self::UInt { - f16::to_bits(self) - } - #[inline] - fn from_bits(bits: Self::UInt) -> Self { - f16::from_bits(bits) - } -} - -unsafe impl FloatPrimitive for f32 { - type UInt = u32; - const SIGN_MASK: Self::UInt = f32::SIGN_MASK; - #[inline] - fn to_bits(self) -> Self::UInt { - f32::to_bits(self) - } - #[inline] - fn from_bits(bits: Self::UInt) -> Self { - f32::from_bits(bits) - } -} - -unsafe impl FloatPrimitive for f64 { - type UInt = u64; - const SIGN_MASK: Self::UInt = f64::SIGN_MASK; - #[inline] - fn to_bits(self) -> Self::UInt { - f64::to_bits(self) - } - #[inline] - fn from_bits(bits: Self::UInt) -> Self { - f64::from_bits(bits) - } -} - -unsafe impl FloatPrimitive for f128 { - type UInt = u128; - const SIGN_MASK: Self::UInt = f128::SIGN_MASK; - #[inline] - fn to_bits(self) -> Self::UInt { - f128::to_bits(self) - } - #[inline] - fn from_bits(bits: Self::UInt) -> Self { - f128::from_bits(bits) - } -} +macro_rules! impl_float_primitive { + ($($float:ident => $bits:ident),+) => {$( + unsafe impl FloatPrimitive for $float { + type UInt = $bits; + const SIGN_MASK: Self::UInt = $float::SIGN_MASK; + #[inline] + fn to_bits(self) -> Self::UInt { + $float::to_bits(self) + } + #[inline] + fn from_bits(bits: Self::UInt) -> Self { + $float::from_bits(bits) + } + #[inline] + fn is_nan(self) -> bool { + $float::is_nan(self) + } + #[inline] + fn is_sign_positive(self) -> bool { + $float::is_sign_positive(self) + } + #[inline] + fn is_sign_negative(self) -> bool { + $float::is_sign_negative(self) + } + } + )+}; +} +impl_float_primitive!(f16 => u16, f32 => u32, f64 => u64, f128 => u128); /// Built-in integer types (i8, i16, .., i128, isize, u8, u16, .., u128, usize). /// diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 5427990ec3d06..0a170fae1e186 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -3043,7 +3043,7 @@ pub const unsafe fn copy(src: *const T, dst: *mut T, count: usize); #[rustc_intrinsic] pub const unsafe fn write_bytes(dst: *mut T, val: u8, count: usize); -/// Returns the minimum of two `f16` values, ignoring NaN. +/// Returns the minimum of two floating-point values, ignoring NaN. /// /// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed /// zeros deterministically. In particular: @@ -3056,60 +3056,13 @@ pub const unsafe fn write_bytes(dst: *mut T, val: u8, count: usize); /// Therefore, implementations must not require the user to uphold /// any safety invariants. /// -/// The stabilized version of this intrinsic is [`f16::min`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn minimum_number_nsz_f16(x: f16, y: f16) -> f16 { - if x.is_nan() || y <= x { - y - } else { - // Either y > x or y is a NaN. - x - } -} - -/// Returns the minimum of two `f32` values, ignoring NaN. -/// -/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed -/// zeros deterministically. In particular: -/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If -/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` -/// and `-0.0`), either input may be returned non-deterministically. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -/// -/// The stabilized version of this intrinsic is [`f32::min`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn minimum_number_nsz_f32(x: f32, y: f32) -> f32 { - if x.is_nan() || y <= x { - y - } else { - // Either y > x or y is a NaN. - x - } -} - -/// Returns the minimum of two `f64` values, ignoring NaN. -/// -/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed -/// zeros deterministically. In particular: -/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If -/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` -/// and `-0.0`), either input may be returned non-deterministically. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -/// -/// The stabilized version of this intrinsic is [`f64::min`]. +/// The stabilized versions of this intrinsic are available on the float primitives via the +/// `min` method. For example, [`f32::min`]. #[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] -pub const fn minimum_number_nsz_f64(x: f64, y: f64) -> f64 { +#[rustc_do_not_const_check] +pub const fn minimum_number_nsz(x: T, y: T) -> T { if x.is_nan() || y <= x { y } else { @@ -3118,9 +3071,9 @@ pub const fn minimum_number_nsz_f64(x: f64, y: f64) -> f64 { } } -/// Returns the minimum of two `f128` values, ignoring NaN. +/// Returns the maximum of two floating-point values, ignoring NaN. /// -/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed +/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed /// zeros deterministically. In particular: /// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If /// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` @@ -3131,94 +3084,22 @@ pub const fn minimum_number_nsz_f64(x: f64, y: f64) -> f64 { /// Therefore, implementations must not require the user to uphold /// any safety invariants. /// -/// The stabilized version of this intrinsic is [`f128::min`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn minimum_number_nsz_f128(x: f128, y: f128) -> f128 { - if x.is_nan() || y <= x { - y - } else { - // Either y > x or y is a NaN. - x - } -} - -/// Returns the minimum of two `f16` values, propagating NaN. -/// -/// This behaves like IEEE 754-2019 minimum. In particular: -/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. -/// For this operation, -0.0 is considered to be strictly less than +0.0. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn minimumf16(x: f16, y: f16) -> f16 { - if x < y { - x - } else if y < x { - y - } else if x == y { - if x.is_sign_negative() && y.is_sign_positive() { x } else { y } - } else { - // At least one input is NaN. Use `+` to perform NaN propagation and quieting. - x + y - } -} - -/// Returns the minimum of two `f32` values, propagating NaN. -/// -/// This behaves like IEEE 754-2019 minimum. In particular: -/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. -/// For this operation, -0.0 is considered to be strictly less than +0.0. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. +/// The stabilized versions of this intrinsic are available on the float primitives via the +/// `max` method. For example, [`f32::max`]. #[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] -pub const fn minimumf32(x: f32, y: f32) -> f32 { - if x < y { - x - } else if y < x { +#[rustc_do_not_const_check] +pub const fn maximum_number_nsz(x: T, y: T) -> T { + if x.is_nan() || y >= x { y - } else if x == y { - if x.is_sign_negative() && y.is_sign_positive() { x } else { y } } else { - // At least one input is NaN. Use `+` to perform NaN propagation and quieting. - x + y - } -} - -/// Returns the minimum of two `f64` values, propagating NaN. -/// -/// This behaves like IEEE 754-2019 minimum. In particular: -/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. -/// For this operation, -0.0 is considered to be strictly less than +0.0. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn minimumf64(x: f64, y: f64) -> f64 { - if x < y { + // Either y < x or y is a NaN. x - } else if y < x { - y - } else if x == y { - if x.is_sign_negative() && y.is_sign_positive() { x } else { y } - } else { - // At least one input is NaN. Use `+` to perform NaN propagation and quieting. - x + y } } -/// Returns the minimum of two `f128` values, propagating NaN. +/// Returns the minimum of two floating-point values, propagating NaN. /// /// This behaves like IEEE 754-2019 minimum. In particular: /// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. @@ -3229,8 +3110,10 @@ pub const fn minimumf64(x: f64, y: f64) -> f64 { /// Therefore, implementations must not require the user to uphold /// any safety invariants. #[rustc_nounwind] +#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] -pub const fn minimumf128(x: f128, y: f128) -> f128 { +#[rustc_do_not_const_check] +pub const fn minimum(x: T, y: T) -> T { if x < y { x } else if y < x { @@ -3243,179 +3126,7 @@ pub const fn minimumf128(x: f128, y: f128) -> f128 { } } -/// Returns the maximum of two `f16` values, ignoring NaN. -/// -/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed -/// zeros deterministically. In particular: -/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If -/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` -/// and `-0.0`), either input may be returned non-deterministically. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -/// -/// The stabilized version of this intrinsic is [`f16::max`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximum_number_nsz_f16(x: f16, y: f16) -> f16 { - if x.is_nan() || y >= x { - y - } else { - // Either y < x or y is a NaN. - x - } -} - -/// Returns the maximum of two `f32` values, ignoring NaN. -/// -/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed -/// zeros deterministically. In particular: -/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If -/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` -/// and `-0.0`), either input may be returned non-deterministically. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -/// -/// The stabilized version of this intrinsic is [`f32::max`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximum_number_nsz_f32(x: f32, y: f32) -> f32 { - if x.is_nan() || y >= x { - y - } else { - // Either y < x or y is a NaN. - x - } -} - -/// Returns the maximum of two `f64` values, ignoring NaN. -/// -/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed -/// zeros deterministically. In particular: -/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If -/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` -/// and `-0.0`), either input may be returned non-deterministically. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -/// -/// The stabilized version of this intrinsic is [`f64::max`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximum_number_nsz_f64(x: f64, y: f64) -> f64 { - if x.is_nan() || y >= x { - y - } else { - // Either y < x or y is a NaN. - x - } -} - -/// Returns the maximum of two `f128` values, ignoring NaN. -/// -/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed -/// zeros deterministically. In particular: -/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If -/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` -/// and `-0.0`), either input may be returned non-deterministically. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -/// -/// The stabilized version of this intrinsic is [`f128::max`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximum_number_nsz_f128(x: f128, y: f128) -> f128 { - if x.is_nan() || y >= x { - y - } else { - // Either y < x or y is a NaN. - x - } -} - -/// Returns the maximum of two `f16` values, propagating NaN. -/// -/// This behaves like IEEE 754-2019 maximum. In particular: -/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. -/// For this operation, -0.0 is considered to be strictly less than +0.0. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximumf16(x: f16, y: f16) -> f16 { - if x > y { - x - } else if y > x { - y - } else if x == y { - if x.is_sign_positive() && y.is_sign_negative() { x } else { y } - } else { - x + y - } -} - -/// Returns the maximum of two `f32` values, propagating NaN. -/// -/// This behaves like IEEE 754-2019 maximum. In particular: -/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. -/// For this operation, -0.0 is considered to be strictly less than +0.0. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximumf32(x: f32, y: f32) -> f32 { - if x > y { - x - } else if y > x { - y - } else if x == y { - if x.is_sign_positive() && y.is_sign_negative() { x } else { y } - } else { - x + y - } -} - -/// Returns the maximum of two `f64` values, propagating NaN. -/// -/// This behaves like IEEE 754-2019 maximum. In particular: -/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. -/// For this operation, -0.0 is considered to be strictly less than +0.0. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximumf64(x: f64, y: f64) -> f64 { - if x > y { - x - } else if y > x { - y - } else if x == y { - if x.is_sign_positive() && y.is_sign_negative() { x } else { y } - } else { - x + y - } -} - -/// Returns the maximum of two `f128` values, propagating NaN. +/// Returns the maximum of two floating-point values, propagating NaN. /// /// This behaves like IEEE 754-2019 maximum. In particular: /// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. @@ -3426,8 +3137,10 @@ pub const fn maximumf64(x: f64, y: f64) -> f64 { /// Therefore, implementations must not require the user to uphold /// any safety invariants. #[rustc_nounwind] +#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] -pub const fn maximumf128(x: f128, y: f128) -> f128 { +#[rustc_do_not_const_check] +pub const fn maximum(x: T, y: T) -> T { if x > y { x } else if y > x { @@ -3435,6 +3148,7 @@ pub const fn maximumf128(x: f128, y: f128) -> f128 { } else if x == y { if x.is_sign_positive() && y.is_sign_negative() { x } else { y } } else { + // At least one input is NaN. Use `+` to perform NaN propagation and quieting. x + y } } @@ -3452,47 +3166,18 @@ pub const fn fabs(x: T) -> T { T::from_bits(x.to_bits() & !T::SIGN_MASK) } -/// Copies the sign from `y` to `x` for `f16` values. -/// -/// The stabilized version of this intrinsic is -/// [`f16::copysign`](../../std/primitive.f16.html#method.copysign) -#[inline] -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn copysignf16(x: f16, y: f16) -> f16 { - f16::from_bits((x.to_bits() & !f16::SIGN_MASK) | (y.to_bits() & f16::SIGN_MASK)) -} - -/// Copies the sign from `y` to `x` for `f32` values. -/// -/// The stabilized version of this intrinsic is -/// [`f32::copysign`](../../std/primitive.f32.html#method.copysign) -#[inline] -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn copysignf32(x: f32, y: f32) -> f32 { - f32::from_bits((x.to_bits() & !f32::SIGN_MASK) | (y.to_bits() & f32::SIGN_MASK)) -} -/// Copies the sign from `y` to `x` for `f64` values. +/// Copies the sign from `y` to `x` for floating-point values. /// -/// The stabilized version of this intrinsic is -/// [`f64::copysign`](../../std/primitive.f64.html#method.copysign) -#[inline] -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn copysignf64(x: f64, y: f64) -> f64 { - f64::from_bits((x.to_bits() & !f64::SIGN_MASK) | (y.to_bits() & f64::SIGN_MASK)) -} - -/// Copies the sign from `y` to `x` for `f128` values. -/// -/// The stabilized version of this intrinsic is -/// [`f128::copysign`](../../std/primitive.f128.html#method.copysign) +/// The stabilized versions of this intrinsic are available on the float +/// primitives via the `copysign` method. For example, [`f32::copysign`]. #[inline] #[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] -pub const fn copysignf128(x: f128, y: f128) -> f128 { - f128::from_bits((x.to_bits() & !f128::SIGN_MASK) | (y.to_bits() & f128::SIGN_MASK)) +#[rustc_do_not_const_check] +#[miri::intrinsic_fallback_is_spec] +pub const fn copysign(x: T, y: T) -> T { + T::from_bits((x.to_bits() & !T::SIGN_MASK) | (y.to_bits() & T::SIGN_MASK)) } /// Generates the LLVM body for the automatic differentiation of `f` using Enzyme, diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs index 74328cfdcb39f..6b1622b21773f 100644 --- a/library/core/src/num/f128.rs +++ b/library/core/src/num/f128.rs @@ -620,7 +620,7 @@ impl f128 { #[rustc_const_unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn max(self, other: f128) -> f128 { - intrinsics::maximum_number_nsz_f128(self, other) + intrinsics::maximum_number_nsz(self, other) } /// Returns the minimum of the two numbers, ignoring NaN. @@ -651,7 +651,7 @@ impl f128 { #[rustc_const_unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn min(self, other: f128) -> f128 { - intrinsics::minimum_number_nsz_f128(self, other) + intrinsics::minimum_number_nsz(self, other) } /// Returns the maximum of the two numbers, propagating NaN. @@ -680,10 +680,11 @@ impl f128 { /// ``` #[inline] #[unstable(feature = "f128", issue = "116909")] + #[rustc_const_unstable(feature = "f128", issue = "116909")] // #[unstable(feature = "float_minimum_maximum", issue = "91079")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn maximum(self, other: f128) -> f128 { - intrinsics::maximumf128(self, other) + intrinsics::maximum(self, other) } /// Returns the minimum of the two numbers, propagating NaN. @@ -712,10 +713,11 @@ impl f128 { /// ``` #[inline] #[unstable(feature = "f128", issue = "116909")] + #[rustc_const_unstable(feature = "f128", issue = "116909")] // #[unstable(feature = "float_minimum_maximum", issue = "91079")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn minimum(self, other: f128) -> f128 { - intrinsics::minimumf128(self, other) + intrinsics::minimum(self, other) } /// Calculates the midpoint (average) between `self` and `rhs`. @@ -1441,7 +1443,7 @@ impl f128 { #[rustc_const_unstable(feature = "f128", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn copysign(self, sign: f128) -> f128 { - intrinsics::copysignf128(self, sign) + intrinsics::copysign(self, sign) } /// Float addition that allows optimizations based on algebraic rules. diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs index 023e6c56471ce..32a37b6329dc2 100644 --- a/library/core/src/num/f16.rs +++ b/library/core/src/num/f16.rs @@ -614,7 +614,7 @@ impl f16 { #[rustc_const_unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn max(self, other: f16) -> f16 { - intrinsics::maximum_number_nsz_f16(self, other) + intrinsics::maximum_number_nsz(self, other) } /// Returns the minimum of the two numbers, ignoring NaN. @@ -645,7 +645,7 @@ impl f16 { #[rustc_const_unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn min(self, other: f16) -> f16 { - intrinsics::minimum_number_nsz_f16(self, other) + intrinsics::minimum_number_nsz(self, other) } /// Returns the maximum of the two numbers, propagating NaN. @@ -674,10 +674,11 @@ impl f16 { /// ``` #[inline] #[unstable(feature = "f16", issue = "116909")] + #[rustc_const_unstable(feature = "f16", issue = "116909")] // #[unstable(feature = "float_minimum_maximum", issue = "91079")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn maximum(self, other: f16) -> f16 { - intrinsics::maximumf16(self, other) + intrinsics::maximum(self, other) } /// Returns the minimum of the two numbers, propagating NaN. @@ -706,10 +707,11 @@ impl f16 { /// ``` #[inline] #[unstable(feature = "f16", issue = "116909")] + #[rustc_const_unstable(feature = "f16", issue = "116909")] // #[unstable(feature = "float_minimum_maximum", issue = "91079")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn minimum(self, other: f16) -> f16 { - intrinsics::minimumf16(self, other) + intrinsics::minimum(self, other) } /// Calculates the midpoint (average) between `self` and `rhs`. @@ -1425,7 +1427,7 @@ impl f16 { #[rustc_const_unstable(feature = "f16", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn copysign(self, sign: f16) -> f16 { - intrinsics::copysignf16(self, sign) + intrinsics::copysign(self, sign) } /// Float addition that allows optimizations based on algebraic rules. diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs index 43f543c911ede..722c3c32976a4 100644 --- a/library/core/src/num/f32.rs +++ b/library/core/src/num/f32.rs @@ -832,7 +832,7 @@ impl f32 { #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] #[inline] pub const fn max(self, other: f32) -> f32 { - intrinsics::maximum_number_nsz_f32(self, other) + intrinsics::maximum_number_nsz(self, other) } /// Returns the minimum of the two numbers, ignoring NaN. @@ -859,7 +859,7 @@ impl f32 { #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] #[inline] pub const fn min(self, other: f32) -> f32 { - intrinsics::minimum_number_nsz_f32(self, other) + intrinsics::minimum_number_nsz(self, other) } /// Returns the maximum of the two numbers, propagating NaN. @@ -884,9 +884,10 @@ impl f32 { /// ``` #[must_use = "this returns the result of the comparison, without modifying either input"] #[unstable(feature = "float_minimum_maximum", issue = "91079")] + #[rustc_const_unstable(feature = "float_minimum_maximum", issue = "91079")] #[inline] pub const fn maximum(self, other: f32) -> f32 { - intrinsics::maximumf32(self, other) + intrinsics::maximum(self, other) } /// Returns the minimum of the two numbers, propagating NaN. @@ -911,9 +912,10 @@ impl f32 { /// ``` #[must_use = "this returns the result of the comparison, without modifying either input"] #[unstable(feature = "float_minimum_maximum", issue = "91079")] + #[rustc_const_unstable(feature = "float_minimum_maximum", issue = "91079")] #[inline] pub const fn minimum(self, other: f32) -> f32 { - intrinsics::minimumf32(self, other) + intrinsics::minimum(self, other) } /// Calculates the midpoint (average) between `self` and `rhs`. @@ -1598,7 +1600,7 @@ impl f32 { #[stable(feature = "copysign", since = "1.35.0")] #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] pub const fn copysign(self, sign: f32) -> f32 { - intrinsics::copysignf32(self, sign) + intrinsics::copysign(self, sign) } /// Float addition that allows optimizations based on algebraic rules. diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs index 41a615613377a..af7217d7d3293 100644 --- a/library/core/src/num/f64.rs +++ b/library/core/src/num/f64.rs @@ -833,7 +833,7 @@ impl f64 { #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] #[inline] pub const fn max(self, other: f64) -> f64 { - intrinsics::maximum_number_nsz_f64(self, other) + intrinsics::maximum_number_nsz(self, other) } /// Returns the minimum of the two numbers, ignoring NaN. @@ -860,7 +860,7 @@ impl f64 { #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] #[inline] pub const fn min(self, other: f64) -> f64 { - intrinsics::minimum_number_nsz_f64(self, other) + intrinsics::minimum_number_nsz(self, other) } /// Returns the maximum of the two numbers, propagating NaN. @@ -885,9 +885,10 @@ impl f64 { /// ``` #[must_use = "this returns the result of the comparison, without modifying either input"] #[unstable(feature = "float_minimum_maximum", issue = "91079")] + #[rustc_const_unstable(feature = "float_minimum_maximum", issue = "91079")] #[inline] pub const fn maximum(self, other: f64) -> f64 { - intrinsics::maximumf64(self, other) + intrinsics::maximum(self, other) } /// Returns the minimum of the two numbers, propagating NaN. @@ -912,9 +913,10 @@ impl f64 { /// ``` #[must_use = "this returns the result of the comparison, without modifying either input"] #[unstable(feature = "float_minimum_maximum", issue = "91079")] + #[rustc_const_unstable(feature = "float_minimum_maximum", issue = "91079")] #[inline] pub const fn minimum(self, other: f64) -> f64 { - intrinsics::minimumf64(self, other) + intrinsics::minimum(self, other) } /// Calculates the midpoint (average) between `self` and `rhs`. @@ -1577,7 +1579,7 @@ impl f64 { #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] #[inline] pub const fn copysign(self, sign: f64) -> f64 { - intrinsics::copysignf64(self, sign) + intrinsics::copysign(self, sign) } /// Float addition that allows optimizations based on algebraic rules. diff --git a/library/core/src/ptr/docs/is_null.md b/library/core/src/ptr/docs/is_null.md index 7368ab9b57630..074ecde056221 100644 --- a/library/core/src/ptr/docs/is_null.md +++ b/library/core/src/ptr/docs/is_null.md @@ -1,10 +1,12 @@ Returns `true` if the pointer is null. -Note that unsized types have many possible null pointers, as only the -raw data pointer is considered, not their length, vtable, etc. +Note that, for [wide] pointers, only the address of the pointee is considered, +ignoring the metadata (such as a slice's length or a trait object's vtable). Therefore, two pointers that are null may still not compare equal to each other. +[wide]: core::ptr#thin-and-wide-pointers + # Panics during const evaluation If this method is used during const evaluation, and `self` is a pointer diff --git a/library/core/src/ptr/metadata.rs b/library/core/src/ptr/metadata.rs index 1eeadf1217b5f..1a0e71dc349ca 100644 --- a/library/core/src/ptr/metadata.rs +++ b/library/core/src/ptr/metadata.rs @@ -101,7 +101,7 @@ pub const fn metadata(ptr: *const T) -> ::Metadat ptr_metadata(ptr) } -/// Forms a (possibly-wide) raw pointer from a data pointer and metadata. +/// Forms a (possibly-[wide]) raw pointer from a data pointer and metadata. /// /// This function is safe but the returned pointer is not necessarily safe to dereference. /// For slices, see the documentation of [`slice::from_raw_parts`] for safety requirements. @@ -111,6 +111,7 @@ pub const fn metadata(ptr: *const T) -> ::Metadat /// a thin pointer can always be obtained by casting `*const T` to `*const ()`. /// /// [`slice::from_raw_parts`]: crate::slice::from_raw_parts +/// [wide]: core::ptr#thin-and-wide-pointers #[unstable(feature = "ptr_metadata", issue = "81513")] #[inline] pub const fn from_raw_parts( diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 99aa9cf5ab741..443b518284e87 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -166,6 +166,20 @@ //! //! [`null()`]: null //! +//! # Thin and wide pointers +//! +//! Some pointers can also carry additional metadata alongside the address of the pointee. These are called +//! **wide pointers** (or **fat pointers**). +//! Pointers that only store the address of the pointee are instead called **thin pointers**, every +//! pointer to a sized type is guaranteed to be thin. +//! +//! Currently, wide pointers are twice as big as the size of a thin pointer, +//! however, this could be changed in the future. +//! +//! Wide pointers are commonly used when working with [`DSTs`]. +//! +//! [`DSTs`]: https://doc.rust-lang.org/reference/dynamically-sized-types.html +//! //! # Provenance //! //! Pointers are not *simply* an "integer" or "address". For instance, it's uncontroversial @@ -2503,7 +2517,7 @@ pub fn eq(a: *const T, b: *const T) -> bool { } /// Compares the *addresses* of the two pointers for equality, -/// ignoring any metadata in fat pointers. +/// ignoring any metadata in [wide](core::ptr#thin-and-wide-pointers) pointers. /// /// If the arguments are thin pointers of the same type, /// then this is the same as [`eq`]. diff --git a/library/coretests/benches/ascii.rs b/library/coretests/benches/ascii.rs index 64bdc7fed118f..940ec0f75892d 100644 --- a/library/coretests/benches/ascii.rs +++ b/library/coretests/benches/ascii.rs @@ -50,7 +50,7 @@ macro_rules! benches { fn $name(bencher: &mut Bencher) { bencher.bytes = $input.len() as u64; bencher.iter(|| { - let mut vec = $input.as_bytes().to_vec(); + let mut vec = black_box($input).as_bytes().to_vec(); { let $arg = &mut vec[..]; black_box($body); diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index ab2df83e4b975..d75107616a283 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -1150,9 +1150,9 @@ impl File { self.inner.file_attr().map(Metadata) } - /// Creates a new `File` instance that shares the same underlying file handle - /// as the existing `File` instance. Reads, writes, and seeks will affect - /// both `File` instances simultaneously. + /// Creates a new `File` instance with a different OS handle referring to + /// the same underlying system resource as the existing `File` instance. + /// Reads, writes, and seeks will affect both `File` instances simultaneously. /// /// # Examples /// diff --git a/library/std/src/net/udp.rs b/library/std/src/net/udp.rs index 914c400fb05f1..1cbc07f4183de 100644 --- a/library/std/src/net/udp.rs +++ b/library/std/src/net/udp.rs @@ -155,7 +155,14 @@ impl UdpSocket { /// /// The function must be called with valid byte array `buf` of sufficient size to /// hold the message bytes. If a message is too long to fit in the supplied buffer, - /// excess bytes may be discarded. + /// only the bytes that fit are copied into `buf`; the excess bytes are not returned + /// by this call. The datagram itself is left in the queue in full, so a later call + /// to [`UdpSocket::recv_from`] with a large enough buffer still receives the whole + /// message. + /// + /// Whether peeking with a too-small buffer succeeds with a truncated length or + /// fails is platform-specific. For example, Windows returns an error + /// (`WSAEMSGSIZE`) in this case. /// /// Successive calls return the same data. This is accomplished by passing /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call. @@ -823,7 +830,14 @@ impl UdpSocket { /// /// The function must be called with valid byte array `buf` of sufficient size to /// hold the message bytes. If a message is too long to fit in the supplied buffer, - /// excess bytes may be discarded. + /// only the bytes that fit are copied into `buf`; the excess bytes are not returned + /// by this call. The datagram itself is left in the queue in full, so a later call + /// to [`UdpSocket::recv`] with a large enough buffer still receives the whole + /// message. + /// + /// Whether peeking with a too-small buffer succeeds with a truncated length or + /// fails is platform-specific. For example, Windows returns an error + /// (`WSAEMSGSIZE`) in this case. /// /// Successive calls return the same data. This is accomplished by passing /// `MSG_PEEK` as a flag to the underlying `recv` system call. diff --git a/library/std/src/os/unix/net/datagram.rs b/library/std/src/os/unix/net/datagram.rs index 901263a7aa123..ce5654b5576c7 100644 --- a/library/std/src/os/unix/net/datagram.rs +++ b/library/std/src/os/unix/net/datagram.rs @@ -965,7 +965,10 @@ impl UnixDatagram { /// /// The function must be called with valid byte array `buf` of sufficient size to /// hold the message bytes. If a message is too long to fit in the supplied buffer, - /// excess bytes may be discarded. + /// only the bytes that fit are copied into `buf`; the excess bytes are not returned + /// by this call. The datagram itself is left in the queue in full, so a later call + /// to [`UnixDatagram::recv_from`] with a large enough buffer still receives the + /// whole message. /// /// Successive calls return the same data. This is accomplished by passing /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call. diff --git a/library/std/src/sys/fs/windows.rs b/library/std/src/sys/fs/windows.rs index 77311d233fc74..a7802c1e8bf4c 100644 --- a/library/std/src/sys/fs/windows.rs +++ b/library/std/src/sys/fs/windows.rs @@ -279,12 +279,12 @@ impl OpenOptions { match (self.read, self.write, self.append) { (_, false, false) if self.truncate || self.create || self.create_new => { - Err(io::Error::new( + Err(io::const_error!( io::ErrorKind::InvalidInput, "creating or truncating a file requires write or append access", )) } - (_, _, true) if self.truncate && !self.create_new => Err(io::Error::new( + (_, _, true) if self.truncate && !self.create_new => Err(io::const_error!( io::ErrorKind::InvalidInput, "append and truncate cannot both be enabled", )), @@ -293,7 +293,7 @@ impl OpenOptions { (true, true, false) => Ok(c::GENERIC_READ | c::GENERIC_WRITE), (false, _, true) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA), (true, _, true) => Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA)), - (false, false, false) => Err(io::Error::new( + (false, false, false) => Err(io::const_error!( io::ErrorKind::InvalidInput, "must specify at least one of read, write, or append access", )), diff --git a/library/std/tests/pipe_subprocess.rs b/library/std/tests/pipe_subprocess.rs index 35ad327ef4f48..5289c819835e3 100644 --- a/library/std/tests/pipe_subprocess.rs +++ b/library/std/tests/pipe_subprocess.rs @@ -1,49 +1,80 @@ -fn main() { +#![feature(test)] + +use std::io::{Read, pipe}; +use std::process::ExitCode; +use std::{env, process}; + +// We invoke the test harness manually so that the same binary can also serve as the child +// process that sits on the other end of the pipe. +extern crate test; + +static TESTS: &[&test::TestDescAndFn] = &[&test::TestDescAndFn { + testfn: test::TestFn::StaticTestFn(pipe_subprocess), + desc: test::TestDesc { + name: test::StaticTestName("pipe_subprocess"), + ignore: false, + ignore_message: None, + source_file: file!(), + start_line: 0, + start_col: 0, + end_line: 0, + end_col: 0, + compile_fail: false, + no_run: false, + should_panic: test::ShouldPanic::No, + test_type: test::TestType::IntegrationTest, + }, +}]; + +fn parent() { + let me = env::current_exe().unwrap(); + // If a custom `runner` is set up for the current target, we'll be + // executing `./runner ./test`, not just `./test`. For such a case, + // use the same arguments for child to avoid executing `runner` + // without an actual executable. + let args = env::args(); + + let (rx, tx) = pipe().unwrap(); + assert!( + process::Command::new(me) + .args(args) + .env("I_AM_THE_CHILD", "1") + .stdout(tx) + .status() + .unwrap() + .success() + ); + + let mut s = String::new(); + (&rx).read_to_string(&mut s).unwrap(); + drop(rx); + assert_eq!(s, "Heloo,\n"); + + println!("Test pipe_subprocess.rs success"); +} + +fn child() { + println!("Heloo,"); +} + +fn pipe_subprocess() -> Result<(), String> { // No `Command` on Miri, emscripten or L4Re - #[cfg(all( + if cfg!(all( not(skip_unsupported_miri_tests), any(unix, windows), not(any(target_os = "emscripten", target_os = "l4re")) - ))] - { - use std::io::{Read, pipe}; - use std::{env, process}; - - if env::var("I_AM_THE_CHILD").is_ok() { - child(); - } else { - parent(); - } - - fn parent() { - let me = env::current_exe().unwrap(); - // If a custom `runner` is set up for the current target, we'll be - // executing `./runner ./test`, not just `./test`. For such a case, - // use the same arguments for child to avoid executing `runner` - // without an actual executable. - let args = env::args(); - - let (rx, tx) = pipe().unwrap(); - assert!( - process::Command::new(me) - .args(args) - .env("I_AM_THE_CHILD", "1") - .stdout(tx) - .status() - .unwrap() - .success() - ); - - let mut s = String::new(); - (&rx).read_to_string(&mut s).unwrap(); - drop(rx); - assert_eq!(s, "Heloo,\n"); - - println!("Test pipe_subprocess.rs success"); - } - - fn child() { - println!("Heloo,"); - } + )) { + parent(); + } + Ok(()) +} + +fn main() -> ExitCode { + if env::var("I_AM_THE_CHILD").is_ok() { + child(); + ExitCode::SUCCESS + } else { + // Go via libtest runner so test filtering and nextest work properly. + test::test_main_env_args(TESTS) } } diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index fcec091fed1c7..ae6f5f1c9bbd3 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -194,12 +194,16 @@ def verify(path, expected, verbose): return verified -def unpack(tarball, tarball_suffix, dst, verbose=0, match=None): +def unpack(tarball, tarball_suffix, dst, verbose=0, match=None, directories_only=False): """Unpack the given tarball file""" - eprint("extracting", tarball) + if not directories_only: + eprint("extracting", tarball) fname = os.path.basename(tarball).replace(tarball_suffix, "") with contextlib.closing(tarfile.open(tarball)) as tar: - for member in tar.getnames(): + for member_info in tar: + if directories_only and not member_info.isdir(): + break + member = member_info.name if "/" not in member: continue name = member.replace(fname + "/", "", 1) @@ -210,7 +214,7 @@ def unpack(tarball, tarball_suffix, dst, verbose=0, match=None): dst_path = os.path.join(dst, name) if verbose > 0: eprint(" extracting", member) - tar.extract(member, dst) + tar.extract(member_info, dst) src_path = os.path.join(dst, member) if os.path.isdir(src_path) and os.path.exists(dst_path): continue @@ -535,13 +539,14 @@ def download_component(download_info): ) -def unpack_component(download_info): +def unpack_component(download_info, directories_only=False): unpack( download_info.tarball_path, download_info.tarball_suffix, download_info.bin_root, match=download_info.pattern, verbose=download_info.verbose, + directories_only=directories_only, ) @@ -696,6 +701,11 @@ def download_toolchain(self): for download_info in tarballs_download_info: download_component(download_info) + # rust-installer writes all directories before files. Move them serially + # so parallel extraction cannot race when creating shared directories. + for download_info in tarballs_download_info: + unpack_component(download_info, directories_only=True) + # Unpack the tarballs in parallel. # In Python 2.7, Pool cannot be used as a context manager. pool_size = min(len(tarballs_download_info), get_cpus()) diff --git a/src/doc/rustdoc/src/what-is-rustdoc.md b/src/doc/rustdoc/src/what-is-rustdoc.md index cb4ec51caf208..fd1cb53063dbb 100644 --- a/src/doc/rustdoc/src/what-is-rustdoc.md +++ b/src/doc/rustdoc/src/what-is-rustdoc.md @@ -158,7 +158,18 @@ $ rustdoc README.md You will find an HTML file in `docs/doc/README.html` generated from its Markdown contents. -Cargo currently does not understand standalone Markdown files, unfortunately. +Cargo currently does not understand standalone Markdown files, unfortunately, +but doc comments can copy the contents of external files by using the `include_str!` macro +and `#[doc]` attribute. + +for example: + +```rust +#![doc = include_str!("../README.md")] +``` + +This will copy the contents of `README.md` in the doc comment. +Check out the [`#[doc]` attribute chapter](write-documentation/the-doc-attribute.md) ## Summary diff --git a/src/tools/clippy/clippy_utils/src/sym.rs b/src/tools/clippy/clippy_utils/src/sym.rs index 3b5ddbbaf6420..79ebe78ceb764 100644 --- a/src/tools/clippy/clippy_utils/src/sym.rs +++ b/src/tools/clippy/clippy_utils/src/sym.rs @@ -438,7 +438,6 @@ generate! { max_by, max_by_key, max_value, - maximum, may_panic, mem_align_of, mem_replace, @@ -448,7 +447,6 @@ generate! { min_by, min_by_key, min_value, - minimum, mode, module_name_repetitions, msrv, diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure/analysis.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure/analysis.rs index a2767fcfa7494..491a1b526f6be 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure/analysis.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure/analysis.rs @@ -1456,19 +1456,16 @@ fn truncate_place_to_len_and_update_capture_kind( // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so // we don't need to worry about that case here. match info.capture_kind { - UpvarCapture::ByRef(BorrowKind::Mutable) => { - for i in len..place.projections.len() { - if place.projections[i].kind == ProjectionKind::Deref + UpvarCapture::ByRef(BorrowKind::Mutable) + if (len..place.projections.len()).any(|i| { + place.projections[i].kind == ProjectionKind::Deref && is_mut_ref(place.ty_before_projection(i)) - { - info.capture_kind = UpvarCapture::ByRef(BorrowKind::UniqueImmutable); - break; - } - } + }) => + { + info.capture_kind = UpvarCapture::ByRef(BorrowKind::UniqueImmutable); } - UpvarCapture::ByRef(..) => {} - UpvarCapture::ByValue | UpvarCapture::ByUse => {} + UpvarCapture::ByRef(_) | UpvarCapture::ByValue | UpvarCapture::ByUse => {} } // Now fix the sources, to point at the smaller place. diff --git a/src/tools/rust-installer/src/tarballer.rs b/src/tools/rust-installer/src/tarballer.rs index 854bb85f2c526..f999be962f3d1 100644 --- a/src/tools/rust-installer/src/tarballer.rs +++ b/src/tools/rust-installer/src/tarballer.rs @@ -67,6 +67,8 @@ impl Tarballer { // Write the tar into both encoded files. We write all directories // first, so files may be directly created. (See rust-lang/rustup.rs#1092.) + // Bootstrap also relies on this ordering. It prepares directories up to the + // first non-directory entry before extracting toolchain components in parallel. let buf = BufWriter::with_capacity(1024 * 1024, encoder); let mut builder = Builder::new(buf); // Make uid, gid and mtime deterministic to improve reproducibility diff --git a/tests/codegen-llvm/force-intrinsic-fallback.rs b/tests/codegen-llvm/force-intrinsic-fallback.rs index 3a934b27f828e..a43cfbda244d8 100644 --- a/tests/codegen-llvm/force-intrinsic-fallback.rs +++ b/tests/codegen-llvm/force-intrinsic-fallback.rs @@ -10,15 +10,15 @@ // With the flag, the fallback body is called instead. #[no_mangle] -pub fn call_minimumf32(x: f32, y: f32) -> f32 { - // CHECK-LABEL: @call_minimumf32 +pub fn call_minimum_f32(x: f32, y: f32) -> f32 { + // CHECK-LABEL: @call_minimum_f32 // NORMAL: call float @llvm.minimum.f32 - // NORMAL-NOT: minimumf32 + // NORMAL-NOT: intrinsics{{.*}}minimum // FALLBACK-NOT: @llvm.minimum - // FALLBACK: call {{.*}}minimumf32 - core::intrinsics::minimumf32(x, y) + // FALLBACK: call {{.*}}intrinsics{{.*}}minimum + core::intrinsics::minimum(x, y) } // Codegen backends can return a list of `replaced_intrinsics`, for which codegen of the fallback is diff --git a/tests/run-make/non-unicode-argument/rmake.rs b/tests/run-make/non-unicode-argument/rmake.rs new file mode 100644 index 0000000000000..43064daa79b43 --- /dev/null +++ b/tests/run-make/non-unicode-argument/rmake.rs @@ -0,0 +1,25 @@ +// Regression test for https://github.com/rust-lang/rust/issues/164585 + +use run_make_support::rustc; + +fn main() { + #[cfg(unix)] + let non_unicode: &std::ffi::OsStr = std::os::unix::ffi::OsStrExt::from_bytes(&[0xFF]); + #[cfg(windows)] + let non_unicode: std::ffi::OsString = std::os::windows::ffi::OsStringExt::from_wide(&[0xD800]); + + rustc() + .env_remove("RUST_BACKTRACE") + .arg(&non_unicode) + .run_fail() + .assert_exit_code(1) + .assert_stderr_contains("is not valid Unicode") + .assert_stderr_not_contains("panicked at"); + + rustc() + .env("RUST_BACKTRACE", "0") + .arg(&non_unicode) + .run_fail() + .assert_exit_code(1) + .assert_stderr_contains("is not valid Unicode"); +} diff --git a/tests/ui/assumptions_on_binders/placeholder-assumptions-issue-157840.rs b/tests/ui/assumptions_on_binders/placeholder-assumptions-issue-157840.rs index b3bc4d6fae25f..a18aade6f54e1 100644 --- a/tests/ui/assumptions_on_binders/placeholder-assumptions-issue-157840.rs +++ b/tests/ui/assumptions_on_binders/placeholder-assumptions-issue-157840.rs @@ -10,7 +10,7 @@ fn foo<'a, T>() where T: Proj<'a, Assoc = fn(::Assoc)>, (): Trait<>::Assoc>, - //~^ ERROR overflow evaluating the requirement `(): Trait<>::Assoc>` + //~^ ERROR the trait bound `(): Trait fn(>::Assoc))>` is not satisfied { } diff --git a/tests/ui/assumptions_on_binders/placeholder-assumptions-issue-157840.stderr b/tests/ui/assumptions_on_binders/placeholder-assumptions-issue-157840.stderr index 9d1c8c4a10d02..3ebb61b92c5ad 100644 --- a/tests/ui/assumptions_on_binders/placeholder-assumptions-issue-157840.stderr +++ b/tests/ui/assumptions_on_binders/placeholder-assumptions-issue-157840.stderr @@ -1,9 +1,15 @@ -error[E0275]: overflow evaluating the requirement `(): Trait<>::Assoc>` +error[E0277]: the trait bound `(): Trait fn(>::Assoc))>` is not satisfied --> $DIR/placeholder-assumptions-issue-157840.rs:12:9 | LL | (): Trait<>::Assoc>, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Trait fn(>::Assoc))>` is not implemented for `()` + | +help: this trait has no implementations, consider adding one + --> $DIR/placeholder-assumptions-issue-157840.rs:3:1 + | +LL | trait Trait {} + | ^^^^^^^^^^^^^^ error: aborting due to 1 previous error -For more information about this error, try `rustc --explain E0275`. +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/assumptions_on_binders/principal-upcast-region-eq-issue-157859.rs b/tests/ui/assumptions_on_binders/principal-upcast-region-eq-issue-157859.rs new file mode 100644 index 0000000000000..cb48a64506744 --- /dev/null +++ b/tests/ui/assumptions_on_binders/principal-upcast-region-eq-issue-157859.rs @@ -0,0 +1,19 @@ +//@ compile-flags: -Zassumptions-on-binders -Znext-solver=globally + +trait Super { + fn a(&self) { + let a: &dyn Sub = &(); + let b: &dyn Super fn(&'a ())> = a; + //~^ ERROR the trait bound `dyn Sub: Unsize fn(&'a ())>>` is not satisfied + } +} + +impl Super for () {} + +trait Sub: Super {} + +impl Sub for () {} + +fn main() { + let a: &dyn Sub = &(); +} diff --git a/tests/ui/assumptions_on_binders/principal-upcast-region-eq-issue-157859.stderr b/tests/ui/assumptions_on_binders/principal-upcast-region-eq-issue-157859.stderr new file mode 100644 index 0000000000000..f999bdd677c5a --- /dev/null +++ b/tests/ui/assumptions_on_binders/principal-upcast-region-eq-issue-157859.stderr @@ -0,0 +1,12 @@ +error[E0277]: the trait bound `dyn Sub: Unsize fn(&'a ())>>` is not satisfied + --> $DIR/principal-upcast-region-eq-issue-157859.rs:6:49 + | +LL | let b: &dyn Super fn(&'a ())> = a; + | ^ the nightly-only, unstable trait `Unsize fn(&'a ())>>` is not implemented for `dyn Sub` + | + = note: all implementations of `Unsize` are provided automatically by the compiler, see for more information + = note: required for the cast from `&dyn Sub` to `&dyn Super fn(&'a ())>` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/assumptions_on_binders/relating-region-equality.rs b/tests/ui/assumptions_on_binders/relating-region-equality.rs new file mode 100644 index 0000000000000..8d70fd762bda0 --- /dev/null +++ b/tests/ui/assumptions_on_binders/relating-region-equality.rs @@ -0,0 +1,73 @@ +//@ check-pass +//@ compile-flags: -Zassumptions-on-binders -Znext-solver=globally + +#![feature(test_binder_constraints, non_lifetime_binders)] +#![expect(incomplete_features)] + +trait Same {} +impl Same for T {} + +trait Trait<'a, 'b> { + type Assoc; +} + +struct Carrier(T); +trait Require<'a, 'b, 'c, T> {} + +impl<'a, 'b, 'c, T> Require<'a, 'b, 'c, T> for Carrier +where + T: Trait<'a, 'b>, + >::Assoc: 'c, +{ +} + +core::test_binder_constraints! { + impl<'a: 'b, 'b: 'a> { + forall<> { + predicates &'a (): Same<&'b ()> + } expect { + 'b: 'a, + 'a: 'b, + } + } +} + +core::test_binder_constraints! { + impl<'c, T> + where + for<'a, 'b> T: Trait<'a, 'b>, + { + forall<'a> + where + for<'b> >::Assoc: 'c, + { + forall<'b> { + predicates Carrier: Require<'a, 'b, 'c, T> + } expect { + for<'b> >::Assoc: 'c + } + } expect {} + } +} + +core::test_binder_constraints! { + impl<'c, T> + where + for<'a, 'b> T: Trait<'a, 'b>, + { + forall<'a> + where + for<'b> >::Assoc: 'c, + { + forall<'b> { + exists { + predicates Carrier: Require<'a, 'b, 'c, T> + } + } expect { + for<'b> >::Assoc: 'c + } + } expect {} + } +} + +fn main() {} diff --git a/tests/ui/assumptions_on_binders/relating-region-variance-constraints.rs b/tests/ui/assumptions_on_binders/relating-region-variance-constraints.rs new file mode 100644 index 0000000000000..59b9e00100f2c --- /dev/null +++ b/tests/ui/assumptions_on_binders/relating-region-variance-constraints.rs @@ -0,0 +1,41 @@ +//@ check-pass +//@ compile-flags: -Zassumptions-on-binders -Znext-solver=globally + +#![feature(test_binder_constraints)] + +core::test_binder_constraints! { + impl<'a: 'b, 'b> { + forall<> { + 'a: 'b + } expect { + 'a: 'b + } + } +} + +core::test_binder_constraints! { + impl<'a, 'b: 'a> { + forall<> { + 'b: 'a + } expect { + 'b: 'a + } + } +} + +core::test_binder_constraints! { + impl<'a: 'b, 'b> { + forall<'c> where 'c: 'b { + forall<'d> where 'd: 'c { + 'd: 'b + } expect { + or { + 'c: 'b, + 'c: 'static, + } + } + } expect {} + } +} + +fn main() {} diff --git a/tests/ui/assumptions_on_binders/relating-region-variance-fail.abby.stderr b/tests/ui/assumptions_on_binders/relating-region-variance-fail.abby.stderr new file mode 100644 index 0000000000000..8b3c10d5c25fe --- /dev/null +++ b/tests/ui/assumptions_on_binders/relating-region-variance-fail.abby.stderr @@ -0,0 +1,51 @@ +error: lifetime may not live long enough + --> $DIR/relating-region-variance-fail.rs:8:5 + | +LL | fn covariant<'a: 'b, 'b>(x: &'b ()) -> &'a () { + | -- -- lifetime `'b` defined here + | | + | lifetime `'a` defined here +LL | x + | ^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b` + | + = help: consider adding the following bound: `'b: 'a` + +error: lifetime may not live long enough + --> $DIR/relating-region-variance-fail.rs:13:5 + | +LL | fn contravariant<'a: 'b, 'b>(x: fn(&'a ())) -> fn(&'b ()) { + | -- -- lifetime `'b` defined here + | | + | lifetime `'a` defined here +LL | x + | ^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b` + | + = help: consider adding the following bound: `'b: 'a` + +error: lifetime may not live long enough + --> $DIR/relating-region-variance-fail.rs:18:5 + | +LL | fn invariant<'a: 'b, 'b>(x: Cell<&'a ()>) -> Cell<&'b ()> { + | -- -- lifetime `'b` defined here + | | + | lifetime `'a` defined here +LL | x + | ^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b` + | + = help: consider adding the following bound: `'b: 'a` + = note: requirement occurs because of the type `Cell<&()>`, which makes the generic argument `&()` invariant + = note: the struct `Cell` is invariant over the parameter `T` + = help: see for more information about variance + +error[E0308]: mismatched types + --> $DIR/relating-region-variance-fail.rs:23:5 + | +LL | x + | ^ one type is more general than the other + | + = note: expected fn pointer `for<'a> fn(&'a ())` + found fn pointer `fn(&())` + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/assumptions_on_binders/relating-region-variance-fail.normal.stderr b/tests/ui/assumptions_on_binders/relating-region-variance-fail.normal.stderr new file mode 100644 index 0000000000000..cf675df2e9878 --- /dev/null +++ b/tests/ui/assumptions_on_binders/relating-region-variance-fail.normal.stderr @@ -0,0 +1,53 @@ +error[E0308]: mismatched types + --> $DIR/relating-region-variance-fail.rs:23:5 + | +LL | fn higher_ranked(x: fn(&'static ())) -> for<'a> fn(&'a ()) { + | ------------------ expected `for<'a> fn(&'a ())` because of return type +LL | x + | ^ one type is more general than the other + | + = note: expected fn pointer `for<'a> fn(&'a ())` + found fn pointer `fn(&'static ())` + +error: lifetime may not live long enough + --> $DIR/relating-region-variance-fail.rs:8:5 + | +LL | fn covariant<'a: 'b, 'b>(x: &'b ()) -> &'a () { + | -- -- lifetime `'b` defined here + | | + | lifetime `'a` defined here +LL | x + | ^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b` + | + = help: consider adding the following bound: `'b: 'a` + +error: lifetime may not live long enough + --> $DIR/relating-region-variance-fail.rs:13:5 + | +LL | fn contravariant<'a: 'b, 'b>(x: fn(&'a ())) -> fn(&'b ()) { + | -- -- lifetime `'b` defined here + | | + | lifetime `'a` defined here +LL | x + | ^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b` + | + = help: consider adding the following bound: `'b: 'a` + +error: lifetime may not live long enough + --> $DIR/relating-region-variance-fail.rs:18:5 + | +LL | fn invariant<'a: 'b, 'b>(x: Cell<&'a ()>) -> Cell<&'b ()> { + | -- -- lifetime `'b` defined here + | | + | lifetime `'a` defined here +LL | x + | ^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b` + | + = help: consider adding the following bound: `'b: 'a` + = note: requirement occurs because of the type `Cell<&()>`, which makes the generic argument `&()` invariant + = note: the struct `Cell` is invariant over the parameter `T` + = help: see for more information about variance + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/assumptions_on_binders/relating-region-variance-fail.rs b/tests/ui/assumptions_on_binders/relating-region-variance-fail.rs new file mode 100644 index 0000000000000..f348119aa0910 --- /dev/null +++ b/tests/ui/assumptions_on_binders/relating-region-variance-fail.rs @@ -0,0 +1,27 @@ +//@ revisions: normal abby +//@ compile-flags: -Znext-solver=globally +//@ [abby] compile-flags: -Zassumptions-on-binders + +use std::cell::Cell; + +fn covariant<'a: 'b, 'b>(x: &'b ()) -> &'a () { + x + //~^ ERROR lifetime may not live long enough +} + +fn contravariant<'a: 'b, 'b>(x: fn(&'a ())) -> fn(&'b ()) { + x + //~^ ERROR lifetime may not live long enough +} + +fn invariant<'a: 'b, 'b>(x: Cell<&'a ()>) -> Cell<&'b ()> { + x + //~^ ERROR lifetime may not live long enough +} + +fn higher_ranked(x: fn(&'static ())) -> for<'a> fn(&'a ()) { + x + //~^ ERROR mismatched types +} + +fn main() {} diff --git a/tests/ui/assumptions_on_binders/relating-region-variance.rs b/tests/ui/assumptions_on_binders/relating-region-variance.rs new file mode 100644 index 0000000000000..4dcb0e807d760 --- /dev/null +++ b/tests/ui/assumptions_on_binders/relating-region-variance.rs @@ -0,0 +1,28 @@ +//@ revisions: normal abby +//@ check-pass +//@ compile-flags: -Znext-solver=globally +//@ [abby] compile-flags: -Zassumptions-on-binders + +use std::cell::Cell; + +fn covariant<'a: 'b, 'b>(x: &'a ()) -> &'b () { + x +} + +fn contravariant<'a: 'b, 'b>(x: fn(&'b ())) -> fn(&'a ()) { + x +} + +fn invariant<'a: 'b, 'b: 'a>(x: Cell<&'a ()>) -> Cell<&'b ()> { + x +} + +fn nested<'a: 'b, 'b>(x: for<'c> fn(&'b &'c ())) -> for<'c> fn(&'a &'c ()) { + x +} + +fn higher_ranked(x: for<'a> fn(&'a ())) -> fn(&'static ()) { + x +} + +fn main() {} diff --git a/tests/ui/assumptions_on_binders/trait-upcast-projection-region-eq.rs b/tests/ui/assumptions_on_binders/trait-upcast-projection-region-eq.rs new file mode 100644 index 0000000000000..0cad2b0658edd --- /dev/null +++ b/tests/ui/assumptions_on_binders/trait-upcast-projection-region-eq.rs @@ -0,0 +1,23 @@ +//@ compile-flags: -Zassumptions-on-binders -Znext-solver=globally + +trait Super { + type Assoc; + + fn a(&self) { + let a: &dyn Sub = &(); + let b: &dyn Super fn(&'a ())> = a; + //~^ ERROR the trait bound `dyn Sub: Unsize fn(&'a ())>>` is not satisfied + } +} + +impl Super for () { + type Assoc = fn(&'static ()); +} + +trait Sub: Super {} + +impl Sub for () {} + +fn main() { + let a: &dyn Sub = &(); +} diff --git a/tests/ui/assumptions_on_binders/trait-upcast-projection-region-eq.stderr b/tests/ui/assumptions_on_binders/trait-upcast-projection-region-eq.stderr new file mode 100644 index 0000000000000..86dfbcb537e11 --- /dev/null +++ b/tests/ui/assumptions_on_binders/trait-upcast-projection-region-eq.stderr @@ -0,0 +1,12 @@ +error[E0277]: the trait bound `dyn Sub: Unsize fn(&'a ())>>` is not satisfied + --> $DIR/trait-upcast-projection-region-eq.rs:8:57 + | +LL | let b: &dyn Super fn(&'a ())> = a; + | ^ the nightly-only, unstable trait `Unsize fn(&'a ())>>` is not implemented for `dyn Sub` + | + = note: all implementations of `Unsize` are provided automatically by the compiler, see for more information + = note: required for the cast from `&dyn Sub` to `&dyn Super fn(&'a ())>` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/consts/const-float-intrinsics.rs b/tests/ui/consts/const-float-intrinsics.rs index d0678f3a7985a..56c47e8c5791a 100644 --- a/tests/ui/consts/const-float-intrinsics.rs +++ b/tests/ui/consts/const-float-intrinsics.rs @@ -1,16 +1,27 @@ //@ check-pass // Check that the float intrinsics carrying `#[rustc_do_not_const_check]` can actually be called in -// a const context, for every float width. Their fallback bodies call into `libm`, but const-eval -// overrides them. +// a const context, for every float width. Their bodies are never const-checked and never run by +// const-eval, which has to implement each of these intrinsics itself. #![feature(core_intrinsics, f16, f128)] -use std::intrinsics::{ceil, floor, fma, fmuladd, round, round_ties_even, trunc}; +use std::intrinsics::{ + ceil, copysign, fabs, floor, fma, fmuladd, maximum, maximum_number_nsz, minimum, + minimum_number_nsz, round, round_ties_even, trunc, +}; macro_rules! check { ($ty:ident) => { const _: () = { + assert!(fabs(-2.5 as $ty) == 2.5); + assert!(copysign(2.5 as $ty, -1.0) == -2.5); + + assert!(minimum(1.0 as $ty, 2.0) == 1.0); + assert!(maximum(1.0 as $ty, 2.0) == 2.0); + assert!(minimum_number_nsz($ty::NAN, 2.0) == 2.0); + assert!(maximum_number_nsz($ty::NAN, 2.0) == 2.0); + assert!(floor(-2.5 as $ty) == -3.0); assert!(ceil(-2.5 as $ty) == -2.0); assert!(trunc(-2.5 as $ty) == -2.0); diff --git a/tests/ui/coroutine/resume-arg-outlives-2.stderr b/tests/ui/coroutine/resume-arg-outlives-2.stderr index 49d3fee47fa9d..52a071821b638 100644 --- a/tests/ui/coroutine/resume-arg-outlives-2.stderr +++ b/tests/ui/coroutine/resume-arg-outlives-2.stderr @@ -18,7 +18,6 @@ LL | | }) | note: `'static` lifetime requirement from `spawn` introduced here --> $SRC_DIR/std/src/thread/functions.rs:LL:COL - ::: $SRC_DIR/std/src/thread/functions.rs:LL:COL | = note: lifetime requirement introduced here ::: $SRC_DIR/std/src/thread/functions.rs:LL:COL diff --git a/tests/ui/crate-loading/missing-std-tier-3.rs b/tests/ui/crate-loading/missing-std-tier-3.rs index 74c7db3db0abf..195ab1bf50c05 100644 --- a/tests/ui/crate-loading/missing-std-tier-3.rs +++ b/tests/ui/crate-loading/missing-std-tier-3.rs @@ -10,5 +10,5 @@ extern crate core; //~^ ERROR can't find crate for `core` //~| NOTE can't find crate //~| NOTE target may not be installed -//~| HELP consider building the standard library from source with `cargo build -Zbuild-std` +//~| HELP consider building the `core` library from source with `cargo build -Zbuild-std=core` fn main() {} diff --git a/tests/ui/crate-loading/missing-std-tier-3.stderr b/tests/ui/crate-loading/missing-std-tier-3.stderr index 197feeccd9c5e..50a4110c7f8d6 100644 --- a/tests/ui/crate-loading/missing-std-tier-3.stderr +++ b/tests/ui/crate-loading/missing-std-tier-3.stderr @@ -5,7 +5,7 @@ LL | extern crate core; | ^^^^^^^^^^^^^^^^^^ can't find crate | = note: the `m68k-unknown-linux-gnu` target may not be installed - = help: consider building the standard library from source with `cargo build -Zbuild-std` + = help: consider building the `core` library from source with `cargo build -Zbuild-std=core` error: aborting due to 1 previous error diff --git a/tests/ui/crate-loading/missing-std.rs b/tests/ui/crate-loading/missing-std.rs index 0fb45b4cfe987..2c1cd63de8e36 100644 --- a/tests/ui/crate-loading/missing-std.rs +++ b/tests/ui/crate-loading/missing-std.rs @@ -8,6 +8,6 @@ extern crate core; //~^ ERROR can't find crate for `core` //~| NOTE can't find crate //~| NOTE target may not be installed -//~| HELP consider building the standard library from source with `cargo build -Zbuild-std` +//~| HELP consider building the `core` library from source with `cargo build -Zbuild-std=core` //~| HELP consider downloading the target with `rustup target add x86_64-unknown-uefi` fn main() {} diff --git a/tests/ui/crate-loading/missing-std.stderr b/tests/ui/crate-loading/missing-std.stderr index 67ed73a2ec6f6..59908ee0505c3 100644 --- a/tests/ui/crate-loading/missing-std.stderr +++ b/tests/ui/crate-loading/missing-std.stderr @@ -6,7 +6,7 @@ LL | extern crate core; | = note: the `x86_64-unknown-uefi` target may not be installed = help: consider downloading the target with `rustup target add x86_64-unknown-uefi` - = help: consider building the standard library from source with `cargo build -Zbuild-std` + = help: consider building the `core` library from source with `cargo build -Zbuild-std=core` error: aborting due to 1 previous error diff --git a/tests/ui/crate-loading/missing-target-no-std-error.stderr b/tests/ui/crate-loading/missing-target-no-std-error.stderr index 11c856f844fc8..779991be8fc89 100644 --- a/tests/ui/crate-loading/missing-target-no-std-error.stderr +++ b/tests/ui/crate-loading/missing-target-no-std-error.stderr @@ -2,7 +2,7 @@ error[E0463]: can't find crate for `core` | = note: the `thumbv7em-none-eabihf` target may not be installed = help: consider downloading the target with `rustup target add thumbv7em-none-eabihf` - = help: consider building the standard library from source with `cargo build -Zbuild-std` + = help: consider building the `core` library from source with `cargo build -Zbuild-std=core` error[E0463]: can't find crate for `cortex_m` --> $DIR/missing-target-no-std-error.rs:12:1 diff --git a/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-1.stderr b/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-1.stderr index 6e0de1071e721..73e1578242675 100644 --- a/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-1.stderr +++ b/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-1.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u8; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of ` as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-2.stderr b/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-2.stderr index 212320a60a1db..4ce1e2e407e9d 100644 --- a/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-2.stderr +++ b/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-2.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u8; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of ` as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/intrinsics/bad-intrinsic-monomorphization-bounds.stderr b/tests/ui/intrinsics/bad-intrinsic-monomorphization-bounds.stderr index 148e6ea1e6aca..37a10e8fe35d1 100644 --- a/tests/ui/intrinsics/bad-intrinsic-monomorphization-bounds.stderr +++ b/tests/ui/intrinsics/bad-intrinsic-monomorphization-bounds.stderr @@ -14,19 +14,20 @@ LL | pub struct Foo(i64); | ^^^^^^^^^^^^^^ help: the following other types implement trait `intrinsics::bounds::FloatPrimitive` --> $SRC_DIR/core/src/intrinsics/bounds.rs:LL:COL + | + = note: `f128` | = note: `f16` - ::: $SRC_DIR/core/src/intrinsics/bounds.rs:LL:COL | = note: `f32` - ::: $SRC_DIR/core/src/intrinsics/bounds.rs:LL:COL | = note: `f64` ::: $SRC_DIR/core/src/intrinsics/bounds.rs:LL:COL | - = note: `f128` + = note: in this macro invocation note: required by a bound in `fadd_fast` --> $SRC_DIR/core/src/intrinsics/mod.rs:LL:COL + = note: this error originates in the macro `impl_float_primitive` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/layout/invalid-unsized-in-always-sized-tail.stderr b/tests/ui/layout/invalid-unsized-in-always-sized-tail.stderr index dbb861d4a3bed..b08e37dbd7472 100644 --- a/tests/ui/layout/invalid-unsized-in-always-sized-tail.stderr +++ b/tests/ui/layout/invalid-unsized-in-always-sized-tail.stderr @@ -20,7 +20,6 @@ LL | struct MySlice(T); error[E0080]: the type `MySlice<[bool]>` has an unknown layout --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of `::ALIGN` failed here diff --git a/tests/ui/layout/too-big-no-dce.stderr b/tests/ui/layout/too-big-no-dce.stderr index 5533602d3f393..a4b01dda0a444 100644 --- a/tests/ui/layout/too-big-no-dce.stderr +++ b/tests/ui/layout/too-big-no-dce.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u32; NUMBER]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of `<[u32; NUMBER] as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/limits/issue-17913.32bit.stderr b/tests/ui/limits/issue-17913.32bit.stderr index 8b109ad703c75..6ddde4b891836 100644 --- a/tests/ui/limits/issue-17913.32bit.stderr +++ b/tests/ui/limits/issue-17913.32bit.stderr @@ -3,7 +3,6 @@ error: values of the type `[&usize; usize::MAX]` are too big for the target arch error[E0080]: values of the type `[&usize; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of `<[&usize; usize::MAX] as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/limits/issue-17913.64bit.stderr b/tests/ui/limits/issue-17913.64bit.stderr index 8ffa2c1966966..d35d697d5f3f3 100644 --- a/tests/ui/limits/issue-17913.64bit.stderr +++ b/tests/ui/limits/issue-17913.64bit.stderr @@ -3,7 +3,6 @@ error: values of the type `[&usize; usize::MAX]` are too big for the target arch error[E0080]: values of the type `[&usize; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of `<[&usize; usize::MAX] as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/limits/issue-55878.stderr b/tests/ui/limits/issue-55878.stderr index acae67709e6b1..994e43854f825 100644 --- a/tests/ui/limits/issue-55878.stderr +++ b/tests/ui/limits/issue-55878.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u8; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of `<[u8; usize::MAX] as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/limits/issue-75158-64.stderr b/tests/ui/limits/issue-75158-64.stderr index 6832f04caaac4..bab0e1b777c28 100644 --- a/tests/ui/limits/issue-75158-64.stderr +++ b/tests/ui/limits/issue-75158-64.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u8; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of ` as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/limits/vtable-try-as-dyn.full-debuginfo.stderr b/tests/ui/limits/vtable-try-as-dyn.full-debuginfo.stderr index 16e4572c83e5b..c6a53d4face4f 100644 --- a/tests/ui/limits/vtable-try-as-dyn.full-debuginfo.stderr +++ b/tests/ui/limits/vtable-try-as-dyn.full-debuginfo.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u8; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/any.rs:LL:COL - ::: $SRC_DIR/core/src/any.rs:LL:COL | = note: evaluation of `std::any::try_as_dyn::<'_, [u8; usize::MAX], dyn Trait>::{constant#0}` failed inside this call note: inside `TypeId::trait_info_of::<'_, dyn Trait>` diff --git a/tests/ui/limits/vtable-try-as-dyn.no-debuginfo.stderr b/tests/ui/limits/vtable-try-as-dyn.no-debuginfo.stderr index 16e4572c83e5b..c6a53d4face4f 100644 --- a/tests/ui/limits/vtable-try-as-dyn.no-debuginfo.stderr +++ b/tests/ui/limits/vtable-try-as-dyn.no-debuginfo.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u8; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/any.rs:LL:COL - ::: $SRC_DIR/core/src/any.rs:LL:COL | = note: evaluation of `std::any::try_as_dyn::<'_, [u8; usize::MAX], dyn Trait>::{constant#0}` failed inside this call note: inside `TypeId::trait_info_of::<'_, dyn Trait>` diff --git a/tests/ui/nll/ice-106874.stderr b/tests/ui/nll/ice-106874.stderr index 0b756a1795f8a..80381324b95bb 100644 --- a/tests/ui/nll/ice-106874.stderr +++ b/tests/ui/nll/ice-106874.stderr @@ -81,7 +81,6 @@ LL | A(B(C::new(D::new(move |st| f(st))))) | note: closure with signature `fn(&'2 mut V)` must implement `FnOnce<(&'1 mut V,)>`, for any lifetime `'1`... --> $SRC_DIR/alloc/src/rcs/rc.rs:LL:COL - ::: $SRC_DIR/alloc/src/rcs/rc.rs:LL:COL | = note: required by this bound in `Rc` = note: ...but it actually implements `FnOnce<(&'2 mut V,)>`, for some specific lifetime `'2` @@ -98,7 +97,6 @@ LL | A(B(C::new(D::new(move |st| f(st))))) | note: closure with signature `fn(&'2 mut V)` must implement `Fn<(&'1 mut V,)>`, for any lifetime `'1`... --> $SRC_DIR/alloc/src/rcs/rc.rs:LL:COL - ::: $SRC_DIR/alloc/src/rcs/rc.rs:LL:COL | = note: required by this bound in `Rc` = note: ...but it actually implements `Fn<(&'2 mut V,)>`, for some specific lifetime `'2` diff --git a/tests/ui/pin-ergonomics/pinned-drop-check.stderr b/tests/ui/pin-ergonomics/pinned-drop-check.stderr index 2a10ef06dcdbf..9fa39382abeca 100644 --- a/tests/ui/pin-ergonomics/pinned-drop-check.stderr +++ b/tests/ui/pin-ergonomics/pinned-drop-check.stderr @@ -8,7 +8,6 @@ LL | fn pin_drop(&pin mut self) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ duplicate definition | --> $SRC_DIR/core/src/ops/drop.rs:LL:COL - ::: $SRC_DIR/core/src/ops/drop.rs:LL:COL | = note: item in trait @@ -22,7 +21,6 @@ LL | fn pin_drop(&pin mut self) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ duplicate definition | --> $SRC_DIR/core/src/ops/drop.rs:LL:COL - ::: $SRC_DIR/core/src/ops/drop.rs:LL:COL | = note: item in trait diff --git a/tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.rs b/tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.rs new file mode 100644 index 0000000000000..e26ab7f62a2ba --- /dev/null +++ b/tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.rs @@ -0,0 +1,21 @@ +fn testing_mytrait(_: T) where T: MyTrait {} + +trait MyTrait {} + +impl MyTrait for Vec where T: MyTrait {} +impl MyTrait for &T where T: MyTrait {} +impl MyTrait for [T] where T: MyTrait {} +impl MyTrait for [T;2] where T: MyTrait {} + +impl MyTrait for (T1,) where T1: MyTrait {} +impl MyTrait for (T1, T2) where T1: MyTrait {} +impl MyTrait for (T1, T2, T3) where T1: MyTrait {} +impl MyTrait for (T1, T2, T3, T4) where T1: MyTrait {} +impl MyTrait for (T1, T2, T3, T4, T5) where T1: MyTrait {} + +struct Foo; + +fn main() { + testing_mytrait(Foo); + //~^ ERROR the trait bound `Foo: MyTrait` is not satisfied [E0277] +} diff --git a/tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.stderr b/tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.stderr new file mode 100644 index 0000000000000..366e204948974 --- /dev/null +++ b/tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `Foo: MyTrait` is not satisfied + --> $DIR/multiple_tuples_implement_different_trait_continuous_arities.rs:19:21 + | +LL | testing_mytrait(Foo); + | --------------- ^^^ unsatisfied trait bound + | | + | required by a bound introduced by this call + | +help: the trait `MyTrait` is not implemented for `Foo` + --> $DIR/multiple_tuples_implement_different_trait_continuous_arities.rs:16:1 + | +LL | struct Foo; + | ^^^^^^^^^^ + = help: the following other types implement trait `MyTrait`: + `&T` implements `MyTrait` + `(T₁, T₂, …, Tₙ)` for tuples of arity 1 to 5 implements `MyTrait` + `Vec` implements `MyTrait` + `[T; 2]` implements `MyTrait` + `[T]` implements `MyTrait` +note: required by a bound in `testing_mytrait` + --> $DIR/multiple_tuples_implement_different_trait_continuous_arities.rs:1:38 + | +LL | fn testing_mytrait(_: T) where T: MyTrait {} + | ^^^^^^^^^^^ required by this bound in `testing_mytrait` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/suggestions/multiple_tuples_implement_same_trait_continuous_arities.stderr b/tests/ui/suggestions/multiple_tuples_implement_same_trait_continuous_arities.stderr index fb9bb2642971a..3f30990827527 100644 --- a/tests/ui/suggestions/multiple_tuples_implement_same_trait_continuous_arities.stderr +++ b/tests/ui/suggestions/multiple_tuples_implement_same_trait_continuous_arities.stderr @@ -7,7 +7,7 @@ LL | testing_debug((1, Foo)); | required by a bound introduced by this call | = help: the following other types implement trait `Debug`: - (T₁, T₂, …, Tₙ) up to tuples of arity 12 + `(T₁, T₂, …, Tₙ)` up to tuples of arity 12 and 5 others = note: required for `({integer}, Foo)` to implement `Debug` note: required by a bound in `testing_debug` @@ -30,7 +30,7 @@ LL | testing_mytrait((1, Foo)); | required by a bound introduced by this call | = help: the following other types implement trait `MyTrait`: - (T₁, T₂, …, Tₙ) for tuples of arity 1 up to and including 5 + `(T₁, T₂, …, Tₙ)` for tuples of arity 1 up to and including 5 note: required by a bound in `testing_mytrait` --> $DIR/multiple_tuples_implement_same_trait_continuous_arities.rs:4:23 | diff --git a/tests/ui/typeck/no-as-deref-suggestion-on-err-slice.rs b/tests/ui/typeck/no-as-deref-suggestion-on-err-slice.rs new file mode 100644 index 0000000000000..4f0c0c1847fd0 --- /dev/null +++ b/tests/ui/typeck/no-as-deref-suggestion-on-err-slice.rs @@ -0,0 +1,65 @@ +// Regression test for https://github.com/rust-lang/rust/issues/165365 + +use std::ops::Deref; + +enum E { + A { x: u8 }, +} + +fn err_vec(err: Result<(), Vec>) { + match err { + Err([E::A { .. }]) => {} + //~^ ERROR: expected an array or slice + _ => {} + } +} + +fn err_vec_when_ok_derefs(err: Result>) { + match err { + Err([1]) => {} + //~^ ERROR: expected an array or slice + _ => {} + } +} + +fn err_same_type(err: Result, Vec>) { + match err { + Err([]) => {} + //~^ ERROR: expected an array or slice + _ => {} + } +} + +fn ok_same_type(err: Result, Vec>) { + match err { + //~^ HELP: consider using `as_deref` here + Ok([]) => {} + //~^ ERROR: expected an array or slice + _ => {} + } +} + +enum Contrived<'a> { + Layer(&'a Contrived<'a>), + Value(Vec), +} + +impl Deref for Contrived<'_> { + type Target = [E]; + fn deref(&self) -> &[E] { + match self { + Contrived::Layer(peeled) => peeled.deref(), + Contrived::Value(value) => value.deref(), + } + } +} + +fn contrived(opt: Option>) { + match opt { + Some(Contrived::Layer([])) => {} + //~^ ERROR: expected an array or slice + _ => {} + } +} + +fn main() {} diff --git a/tests/ui/typeck/no-as-deref-suggestion-on-err-slice.stderr b/tests/ui/typeck/no-as-deref-suggestion-on-err-slice.stderr new file mode 100644 index 0000000000000..9d01216afb432 --- /dev/null +++ b/tests/ui/typeck/no-as-deref-suggestion-on-err-slice.stderr @@ -0,0 +1,38 @@ +error[E0529]: expected an array or slice, found `Vec` + --> $DIR/no-as-deref-suggestion-on-err-slice.rs:11:13 + | +LL | Err([E::A { .. }]) => {} + | ^^^^^^^^^^^^^ pattern cannot match with input type `Vec` + +error[E0529]: expected an array or slice, found `Vec` + --> $DIR/no-as-deref-suggestion-on-err-slice.rs:19:13 + | +LL | Err([1]) => {} + | ^^^ pattern cannot match with input type `Vec` + +error[E0529]: expected an array or slice, found `Vec` + --> $DIR/no-as-deref-suggestion-on-err-slice.rs:27:13 + | +LL | Err([]) => {} + | ^^ pattern cannot match with input type `Vec` + +error[E0529]: expected an array or slice, found `Vec` + --> $DIR/no-as-deref-suggestion-on-err-slice.rs:36:12 + | +LL | Ok([]) => {} + | ^^ pattern cannot match with input type `Vec` + | +help: consider using `as_deref` here + | +LL | match err.as_deref() { + | +++++++++++ + +error[E0529]: expected an array or slice, found `Contrived<'_>` + --> $DIR/no-as-deref-suggestion-on-err-slice.rs:59:31 + | +LL | Some(Contrived::Layer([])) => {} + | ^^ pattern cannot match with input type `Contrived<'_>` + +error: aborting due to 5 previous errors + +For more information about this error, try `rustc --explain E0529`.