diff --git a/compiler/rustc_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index 8510b54aa6446..4274c21ffd26f 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -372,14 +372,20 @@ impl<'sess> AttributeParser<'sess> { let inner_span = lower_span(n.item.span); let accepter = ATTRIBUTE_PARSERS.accepters.get(parts.as_slice()); + + self.check_attribute_safety( + &attr_path, + inner_span, + n.item.unsafety, + if let Some(accept) = accepter { + accept.safety + } else { + AttributeSafety::Normal + }, + &mut emit_lint, + ); + if let Some(accept) = accepter { - self.check_attribute_safety( - &attr_path, - inner_span, - n.item.unsafety, - accept.safety, - &mut emit_lint, - ); self.check_attribute_stability(&attr_path, attr_span, accept.stability); if let [part] = parts.as_slice() { debug_assert!(BUILTIN_ATTRIBUTE_SET.contains(part)); @@ -491,14 +497,6 @@ impl<'sess> AttributeParser<'sess> { span: attr_span, }; - self.check_attribute_safety( - &attr_path, - inner_span, - n.item.unsafety, - AttributeSafety::Normal, - &mut emit_lint, - ); - if !matches!(self.should_emit, ShouldEmit::Nothing) && Target::from_ast_target(&ast_target) == Target::Crate { diff --git a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs index f1f281b5509cd..2bd58ce8620a1 100644 --- a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs +++ b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs @@ -33,7 +33,6 @@ pub(crate) fn expand( return vec![orig_item]; }; - // Generate a bunch of new items using the AllocFnFactory let span = ecx.with_def_site_ctxt(item.span); // Generate item statements for the allocator methods. @@ -42,7 +41,7 @@ pub(crate) fn expand( // Generate anonymous constant serving as container for the allocator methods. let const_item = ecx.item_const_underscore(span, ecx.block(span, stmts)); let const_item = if is_stmt { - Annotatable::Stmt(Box::new(ecx.stmt_item(span, const_item))) + Annotatable::Stmt(ecx.stmt_item(span, const_item)) } else { Annotatable::Item(const_item) }; diff --git a/compiler/rustc_builtin_macros/src/autodiff.rs b/compiler/rustc_builtin_macros/src/autodiff.rs index cc79eb29b68ab..da53a770cdc1a 100644 --- a/compiler/rustc_builtin_macros/src/autodiff.rs +++ b/compiler/rustc_builtin_macros/src/autodiff.rs @@ -14,8 +14,8 @@ mod llvm_enzyme { use rustc_ast::tokenstream::*; use rustc_ast::visit::AssocCtxt::*; use rustc_ast::{ - self as ast, FnRetTy, FnSig, GenericArg, GenericParamKind, Generics, ItemKind, - MetaItemInner, PatKind, TyKind, Visibility, + self as ast, FnRetTy, FnSig, GenericParamKind, Generics, ItemKind, MetaItemInner, PatKind, + TyKind, Visibility, }; use rustc_attr_ir::RustcAutodiff; use rustc_expand::base::{Annotatable, ExtCtxt}; @@ -24,6 +24,7 @@ mod llvm_enzyme { use tracing::{debug, trace}; use crate::diagnostics; + use crate::util::generic_param_to_arg; pub(crate) fn outer_normal_attr( kind: &Box, @@ -449,7 +450,7 @@ mod llvm_enzyme { Annotatable::Stmt(_) => { let mut d_fn = ecx.item(span, d_attrs, ItemKind::Fn(d_fn)); d_fn.vis = vis; - Annotatable::Stmt(Box::new(ecx.stmt_item(span, d_fn))) + Annotatable::Stmt(ecx.stmt_item(span, d_fn)) } _ => { unreachable!("item kind checked previously") @@ -577,16 +578,8 @@ mod llvm_enzyme { .params .iter() .filter_map(|p| match &p.kind { - GenericParamKind::Type { .. } => { - let path = ast::Path::from_ident(p.ident); - let ty = ecx.ty_path(path); - Some(GenericArg::Type(ty)) - } - GenericParamKind::Const { .. } => { - let anon_const = ecx.const_ident(span, p.ident); - Some(GenericArg::Const(anon_const)) - } GenericParamKind::Lifetime => None, + _ => Some(generic_param_to_arg(ecx, p, span)), }) .collect::>(); diff --git a/compiler/rustc_builtin_macros/src/cfg_eval.rs b/compiler/rustc_builtin_macros/src/cfg_eval.rs index 210b9ee895c0f..00c8dd52da6a2 100644 --- a/compiler/rustc_builtin_macros/src/cfg_eval.rs +++ b/compiler/rustc_builtin_macros/src/cfg_eval.rs @@ -126,7 +126,7 @@ impl CfgEval<'_> { Annotatable::Stmt(_) => { let stmt = parser.parse_stmt_without_recovery(false, ForceCollect::Yes, false)?; - self.flat_map_stmt(stmt).pop().map(|stmt| Annotatable::Stmt(Box::new(stmt))) + self.flat_map_stmt(stmt).pop().map(Annotatable::Stmt) } Annotatable::Expr(_) => { let mut expr = parser.parse_expr_force_collect()?; diff --git a/compiler/rustc_builtin_macros/src/cfg_select.rs b/compiler/rustc_builtin_macros/src/cfg_select.rs index 69c3802ceafae..1c33f9d95c99d 100644 --- a/compiler/rustc_builtin_macros/src/cfg_select.rs +++ b/compiler/rustc_builtin_macros/src/cfg_select.rs @@ -29,11 +29,7 @@ fn tts_to_mac_result<'cx, 'sess>( tts: TokenStream, span: Span, ) -> Box { - match ExpandResult::from_tts(ecx, tts, site_span, span, Ident::with_dummy_span(sym::cfg_select)) - { - ExpandResult::Ready(x) => x, - _ => unreachable!("from_tts always returns Ready"), - } + ExpandResult::from_tts(ecx, tts, site_span, span, Ident::with_dummy_span(sym::cfg_select)) } macro_rules! forward_to_parser_any_macro { diff --git a/compiler/rustc_builtin_macros/src/deriving/clone.rs b/compiler/rustc_builtin_macros/src/deriving/clone.rs index 669b89801ee45..19992c2b69481 100644 --- a/compiler/rustc_builtin_macros/src/deriving/clone.rs +++ b/compiler/rustc_builtin_macros/src/deriving/clone.rs @@ -28,7 +28,7 @@ pub(crate) fn expand_derive_clone( // enough. Whether Clone is implemented for fields is irrelevant so we // don't assert it.) let bounds; - let body: MethodBodyFunc<'_>; + let body; let is_simple; match &item.kind { ItemKind::Struct(_, Generics { params, .. }, _) @@ -42,16 +42,22 @@ pub(crate) fn expand_derive_clone( .any(|param| matches!(param.kind, ast::GenericParamKind::Type { .. })) { is_simple = true; - body = Box::new(|c, s, sub| clone_simple_body(c, s, sub, false)); + body = MethodBody::Directly(clone_simple_body(cx, span, item, false)); } else { is_simple = false; - body = Box::new(|c, s, sub| clone_body(c, s, sub, item.kind.ident().unwrap())); + body = MethodBody::SubstructureFunc { + body_func: Box::new(|c, s, sub| { + clone_body(c, s, sub, item.kind.ident().unwrap()) + }), + strategy: FieldlessVariantsStrategy::Default, + has_other_selflike_arg: false, + }; } } ItemKind::Union(..) => { bounds = smallvec![path_std!(cx, span, marker::Copy)]; is_simple = true; - body = Box::new(|c, s, sub| clone_simple_body(c, s, sub, true)); + body = MethodBody::Directly(clone_simple_body(cx, span, item, true)); } _ => cx.dcx().span_bug(span, "`derive(Clone)` on wrong item kind"), } @@ -86,28 +92,25 @@ pub(crate) fn expand_derive_clone( methods: smallvec![MethodDef { name: sym::clone, generics: cx.empty_generics(span), - explicit_self: true, - nonself_args: SmallVec::new(), - has_other_selflike_arg: false, + args: thin_vec![cx.param_self_ref(span)], ret_ty: cx.ty_self(span), attributes: thin_vec![ cx.generated_attr(span, ast::GeneratedAttr::Inline), cx.generated_attr(span, ast::GeneratedAttr::RustcTrivialFieldReads) ], - fieldless_variants_strategy: FieldlessVariantsStrategy::Default, body, }], is_const, .. }; - trait_def.expand_ext(cx, item, push, is_simple) + trait_def.expand(cx, item, push); } fn clone_simple_body( cx: &ExtCtxt<'_>, trait_span: Span, - substr: Substructure<'_>, + item: &ast::Item, is_union: bool, ) -> BlockOrExpr { let mut stmts = ThinVec::new(); @@ -148,16 +151,16 @@ fn clone_simple_body( &[sym::clone, sym::AssertParamIsCopy], ); } else { - match substr { - StaticStruct(vdata, ..) => { + match &item.kind { + ast::ItemKind::Struct(.., vdata) => { process_variant(vdata); } - StaticEnum(enum_def, ..) => { + ast::ItemKind::Enum(.., enum_def) => { for variant in &enum_def.variants { process_variant(&variant.data); } } - _ => cx.dcx().span_bug(trait_span, "unexpected substructure in simple `derive(Clone)`"), + _ => unreachable!(), } } BlockOrExpr::new_mixed(stmts, Some(cx.expr_deref(trait_span, cx.expr_self(trait_span)))) @@ -169,7 +172,7 @@ fn clone_body( substr: Substructure<'_>, type_ident: Ident, ) -> BlockOrExpr { - let subcall = |field: FieldInfo| { + let subcall = |field: FieldInfo<'_>| { let args = thin_vec![field.self_expr]; cx.expr_call_global( field.span, @@ -201,7 +204,7 @@ fn clone_body( VariantData::Struct { .. } => { let fields = all_fields .into_iter() - .map(|field| cx.field_imm(field.span, field.name.unwrap(), subcall(field))) + .map(|field| cx.field_imm(field.span, field.def.ident.unwrap(), subcall(field))) .collect::>(); cx.expr_struct(trait_span, ctor_path, fields) diff --git a/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs b/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs index 6a7ecba0d1bf9..53d37503dca29 100644 --- a/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs +++ b/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs @@ -15,6 +15,7 @@ use thin_vec::{ThinVec, thin_vec}; use crate::deriving::generic::*; use crate::deriving::path_std; use crate::diagnostics; +use crate::util::generic_param_to_arg; pub(crate) fn expand_derive_coerce_pointee( cx: &ExtCtxt<'_>, diff --git a/compiler/rustc_builtin_macros/src/deriving/debug.rs b/compiler/rustc_builtin_macros/src/deriving/debug.rs index b372874fc5814..6ea38b38782fd 100644 --- a/compiler/rustc_builtin_macros/src/deriving/debug.rs +++ b/compiler/rustc_builtin_macros/src/deriving/debug.rs @@ -22,12 +22,7 @@ pub(crate) fn expand_derive_debug( ast::Mutability::Mut, ); - let all_fieldless = match &item.kind { - ast::ItemKind::Enum(_, _, def) => { - def.variants.len() > 1 && def.variants.iter().all(|v| v.data.fields().is_empty()) - } - _ => false, - }; + let ident = item.kind.ident().unwrap(); let trait_def = TraitDef { span, @@ -38,26 +33,35 @@ pub(crate) fn expand_derive_debug( methods: smallvec![MethodDef { name: sym::fmt, generics: cx.empty_generics(span), - explicit_self: true, - nonself_args: smallvec![(sym::f, fmtr)], - has_other_selflike_arg: false, + args: thin_vec![cx.param_self_ref(span), cx.param(span, sym::f, fmtr)], ret_ty: cx.ty_path(path_std!(cx, span, fmt::Result)), attributes: thin_vec![ cx.generated_attr(span, ast::GeneratedAttr::Inline), cx.generated_attr(span, ast::GeneratedAttr::RustcTrivialFieldReads) ], - fieldless_variants_strategy: FieldlessVariantsStrategy::Default, - body: Box::new(|cx, span, substr| debug_body( - cx, - span, - substr, - item.kind.ident().unwrap() - )), + body: match &item.kind { + _ if cx.sess.opts.unstable_opts.fmt_debug == FmtDebug::None => { + MethodBody::Directly(BlockOrExpr::new_expr( + cx.expr_ok(span, cx.expr_tuple(span, ThinVec::new())), + )) + } + ast::ItemKind::Enum(_, _, def) + if def.variants.len() > 1 + && def.variants.iter().all(|v| v.data.fields().is_empty()) => + { + MethodBody::Directly(debug_fieldless_enum(cx, span, def, ident)) + } + _ => MethodBody::SubstructureFunc { + body_func: Box::new(|cx, span, substr| debug_body(cx, span, substr, ident)), + strategy: FieldlessVariantsStrategy::Default, + has_other_selflike_arg: false, + }, + }, }], is_const, .. }; - trait_def.expand_ext(cx, item, push, all_fieldless); + trait_def.expand(cx, item, push); } fn debug_body( @@ -67,14 +71,10 @@ fn debug_body( type_ident: Ident, ) -> BlockOrExpr { let fmt_detail = cx.sess.opts.unstable_opts.fmt_debug; - if fmt_detail == FmtDebug::None { - return BlockOrExpr::new_expr(cx.expr_ok(span, cx.expr_tuple(span, ThinVec::new()))); - } let (ident, vdata, fields) = match substr { Struct(vdata, fields) => (type_ident, vdata, fields), EnumMatching(v, fields) => (v.ident, &v.data, fields), - StaticEnum(enum_def) => return debug_fieldless_enum(cx, span, enum_def, type_ident), _ => cx.dcx().span_bug(span, "unexpected substructure in `derive(Debug)`"), }; @@ -104,7 +104,7 @@ fn debug_body( const CUTOFF: usize = 5; let len = fields.len(); - let expr_for_field = |field: FieldInfo, index: usize| -> Box { + let expr_for_field = |field: FieldInfo<'_>, index: usize| -> Box { if index < len - 1 { field.self_expr } else { @@ -125,15 +125,15 @@ fn debug_body( let fn_path_debug = cx.std_path(span, &[sym::fmt, sym::Formatter, Symbol::intern(&debug)]); let mut args = ThinVec::with_capacity(2 + fields.len()); - args.extend([fmt]); + args.push(fmt); if is_struct { let mut names = String::new(); - names.push_str(ident.name.as_str()); + names.push_str(ident.as_str()); for field in fields.iter() { names.push(' '); - names.push_str(field.name.unwrap().name.as_str()); + names.push_str(field.def.ident.unwrap().as_str()); } let name_expr = cx.expr_str(span, Symbol::intern(&names)); @@ -152,68 +152,34 @@ fn debug_body( // Enough fields that we must use the any-length method. let mut names = String::new(); if is_struct { - names.push_str(ident.name.as_str()); + names.push_str(ident.as_str()); } let mut value_exprs = ThinVec::with_capacity(fields.len()); for (i, field) in fields.into_iter().enumerate() { if is_struct { names.push(' '); - names.push_str(field.name.unwrap().name.as_str()); + names.push_str(field.def.ident.unwrap().name.as_str()); } let field = expr_for_field(field, i); value_exprs.push(field); } - // `let names: &'static _ = "StructName field1 field2"` - let names_let = is_struct.then(|| { - let lt_static = Some(cx.lifetime_static(span)); - let ty_static_ref = cx.ty_ref(span, cx.ty_infer(span), lt_static, ast::Mutability::Not); - let names_expr = cx.expr_str(span, Symbol::intern(&names)); - cx.stmt_let_ty(span, false, sym::names, Some(ty_static_ref), names_expr) - }); - - // `let values: &[&dyn Debug] = &[&&self.field1, &&self.field2];` - let path_debug = cx.std_path(span, &[sym::fmt, sym::Debug]); - let ty_dyn_debug = cx.ty( - span, - ast::TyKind::TraitObject( - thin_vec![cx.trait_bound(path_debug, false)], - ast::TraitObjectSyntax::Dyn, - ), - ); - let ty_slice = cx.ty( - span, - ast::TyKind::Slice(cx.ty_ref(span, ty_dyn_debug, None, ast::Mutability::Not)), - ); - let values_let = cx.stmt_let_ty( - span, - false, - sym::values, - Some(cx.ty_ref(span, ty_slice, None, ast::Mutability::Not)), - cx.expr_array_ref(span, value_exprs), - ); - - // `fmt::Formatter::debug_struct_fields_finish(fmt, names, values)` + // `fmt::Formatter::debug_struct_fields_finish(fmt, "StructName field1 field2", &[&&self.field1, &&self.field2])` or + // `fmt::Formatter::debug_struct_fields_finish(fmt, "StructName", &[&&self.field1, &&self.field2])` let sym_debug = sym::debug_struct_fields_finish; let fn_path_debug_internal = cx.std_path(span, &[sym::fmt, sym::Formatter, sym_debug]); let args = thin_vec![ fmt, - if is_struct { cx.expr_name(span, sym::names) } else { expr_name() }, - cx.expr_name(span, sym::values) + if is_struct { cx.expr_str(span, Symbol::intern(&names)) } else { expr_name() }, + cx.expr_array_ref(span, value_exprs), ]; let expr = cx.expr_call_global(span, fn_path_debug_internal, args); - let stmts = if is_struct { - thin_vec![names_let.unwrap(), values_let] - } else { - thin_vec![values_let] - }; - - BlockOrExpr::new_mixed(stmts, Some(expr)) + BlockOrExpr::new_expr(expr) } } @@ -319,8 +285,7 @@ fn debug_fieldless_enum_concat_str( .map(|(i, v)| { let name_offset = concatenated_names.len(); - let name = v.ident.name.as_str(); - concatenated_names.push_str(name); + concatenated_names.push_str(v.ident.as_str()); let is_last = i == def.variants.len() - 1; if !is_last { diff --git a/compiler/rustc_builtin_macros/src/deriving/default.rs b/compiler/rustc_builtin_macros/src/deriving/default.rs index 6aa45b9d41126..6c6e01abc6a75 100644 --- a/compiler/rustc_builtin_macros/src/deriving/default.rs +++ b/compiler/rustc_builtin_macros/src/deriving/default.rs @@ -1,7 +1,7 @@ use core::ops::ControlFlow; use rustc_ast::visit::{Visitor, WalkItemKind, visit_opt}; -use rustc_ast::{self as ast, EnumDef, VariantData, attr}; +use rustc_ast::{self as ast, EnumDef, ItemKind, VariantData, attr}; use rustc_expand::base::{DummyResult, ExtCtxt}; use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym}; use smallvec::SmallVec; @@ -29,26 +29,20 @@ pub(crate) fn expand_derive_default( methods: smallvec![MethodDef { name: kw::Default, generics: cx.empty_generics(span), - explicit_self: false, - nonself_args: SmallVec::new(), - has_other_selflike_arg: false, + args: ThinVec::new(), ret_ty: cx.ty_self(span), attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)], - fieldless_variants_strategy: FieldlessVariantsStrategy::Default, - body: Box::new(|cx, trait_span, substr| { - match substr { - StaticStruct(variant_data) => default_struct_body( - cx, - trait_span, - variant_data, - // We cannot use `Self` here, see https://github.com/rust-lang/rust/issues/163800 - item.kind.ident().unwrap(), - ), - StaticEnum(enum_def) => default_enum_body(cx, trait_span, enum_def, item.span), - _ => cx - .dcx() - .span_bug(trait_span, "unexpected substructure in `derive(Default)`"), - } + body: MethodBody::Directly(match &item.kind { + ItemKind::Struct(ident, _, variant_data) + | ItemKind::Union(ident, _, variant_data) => default_struct_body( + cx, + span, + variant_data, + // We cannot use `Self` here, see https://github.com/rust-lang/rust/issues/163800 + *ident, + ), + ItemKind::Enum(_, _, enum_def) => default_enum_body(cx, span, enum_def, item.span), + _ => unreachable!(), }), }], is_const, diff --git a/compiler/rustc_builtin_macros/src/deriving/eq.rs b/compiler/rustc_builtin_macros/src/deriving/eq.rs index ff11d3e3110f4..6bb0bfb590bbb 100644 --- a/compiler/rustc_builtin_macros/src/deriving/eq.rs +++ b/compiler/rustc_builtin_macros/src/deriving/eq.rs @@ -25,9 +25,7 @@ pub(crate) fn expand_derive_eq( methods: smallvec![MethodDef { name: sym::assert_fields_are_eq, generics: cx.empty_generics(span), - explicit_self: true, - nonself_args: smallvec![], - has_other_selflike_arg: false, + args: thin_vec![cx.param_self_ref(span)], ret_ty: cx.ty_unit(span), attributes: thin_vec![ // This method will never be called, so doing codegen etc. for it is unnecessary. @@ -36,20 +34,15 @@ pub(crate) fn expand_derive_eq( cx.generated_attr(span, ast::GeneratedAttr::DocHidden), cx.generated_attr(span, ast::GeneratedAttr::CoverageOff), ], - fieldless_variants_strategy: FieldlessVariantsStrategy::Unify, - body: Box::new(assert_fields_eq_body), + body: MethodBody::Directly(assert_fields_eq_body(cx, item)), }], is_const, .. }; - trait_def.expand_ext(cx, item, push, true) + trait_def.expand(cx, item, push); } -fn assert_fields_eq_body( - cx: &ExtCtxt<'_>, - trait_span: Span, - substr: Substructure<'_>, -) -> BlockOrExpr { +fn assert_fields_eq_body(cx: &ExtCtxt<'_>, item: &ast::Item) -> BlockOrExpr { let mut stmts = ThinVec::new(); let mut seen_type_names = FxHashSet::default(); let mut process_variant = |variant: &ast::VariantData| { @@ -74,16 +67,16 @@ fn assert_fields_eq_body( } }; - match substr { - StaticStruct(vdata, ..) => { + match &item.kind { + ast::ItemKind::Struct(.., vdata) | ast::ItemKind::Union(.., vdata) => { process_variant(vdata); } - StaticEnum(enum_def, ..) => { + ast::ItemKind::Enum(.., enum_def) => { for variant in &enum_def.variants { process_variant(&variant.data); } } - _ => cx.dcx().span_bug(trait_span, "unexpected substructure in `derive(Eq)`"), + _ => unreachable!(), } BlockOrExpr::new_stmts(stmts) } diff --git a/compiler/rustc_builtin_macros/src/deriving/from.rs b/compiler/rustc_builtin_macros/src/deriving/from.rs index 52455971fb7af..84bc3a19b954f 100644 --- a/compiler/rustc_builtin_macros/src/deriving/from.rs +++ b/compiler/rustc_builtin_macros/src/deriving/from.rs @@ -27,7 +27,7 @@ pub(crate) fn expand_derive_from( let field = match &item.kind { ItemKind::Struct(_, _, data) => { if let [field] = data.fields() { - Ok(field.clone()) + Ok((field.clone(), data)) } else { let guar = cx.dcx().emit_err(diagnostics::DeriveFromWrongFieldCount { span: err_span(), @@ -47,7 +47,7 @@ pub(crate) fn expand_derive_from( }; let from_type = match field { - Ok(ref field) => field.ty.clone(), + Ok((ref field, _)) => field.ty.clone(), Err(guar) => cx.ty(span, ast::TyKind::Err(guar)), }; @@ -77,23 +77,13 @@ pub(crate) fn expand_derive_from( methods: smallvec![MethodDef { name: sym::from, generics: cx.empty_generics(span), - explicit_self: false, - nonself_args: smallvec![(sym::value, from_type)], - has_other_selflike_arg: false, + args: thin_vec![cx.param(span, sym::value, from_type)], ret_ty: cx.ty_self(span), attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)], - fieldless_variants_strategy: FieldlessVariantsStrategy::Default, - body: Box::new(|cx, span, substructure| { - let field = match field { - Ok(ref field) => field, - Err(guar) => { - return BlockOrExpr::new_expr(DummyResult::raw_expr(span, Some(guar))); - } - }; - - let self_kw = Ident::new(kw::SelfUpper, span); - let expr: Box = match substructure { - StaticStruct(variant) => match variant { + body: MethodBody::Directly(BlockOrExpr::new_expr(match field { + Ok((field, variant)) => { + let self_kw = Ident::new(kw::SelfUpper, span); + match variant { // Self { field: value } VariantData::Struct { .. } => cx.expr_struct_ident( span, @@ -113,11 +103,10 @@ pub(crate) fn expand_derive_from( variant => { cx.dcx().bug(format!("Invalid derive(From) ADT variant: {variant:?}")); } - }, - _ => cx.dcx().bug("Invalid derive(From) ADT input"), - }; - BlockOrExpr::new_expr(expr) - }), + } + } + Err(guar) => DummyResult::raw_expr(span, Some(guar)), + })), }], is_const, .. diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index 216abecf194cb..df90000337a71 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -1,159 +1,8 @@ -//! Some code that abstracts away much of the boilerplate of writing -//! `derive` instances for traits. Among other things it manages getting -//! access to the fields of the 4 different sorts of structs and enum -//! variants, as well as creating the method and impl ast instances. -//! -//! Supported features (fairly exhaustive): -//! -//! - Methods taking any number of parameters of any type and returning -//! any type. -//! - Generating `impl`s for types with type parameters and lifetimes -//! (e.g., `Option`), the parameters are automatically given the -//! current trait as a bound. (This includes separate type parameters -//! and lifetimes for methods.) -//! - Additional bounds on the type parameters (`TraitDef.additional_bounds`) -//! -//! The most important thing for implementors is the `Substructure` objects. -//! The latter groups 5 possibilities of the arguments: -//! -//! - `Struct`, when `Self` is a struct (including tuple structs, e.g -//! `struct T(i32, char)`). -//! - `EnumMatching`, when `Self` is an enum and all the arguments are the -//! same variant of the enum (e.g., `Some(1)`, `Some(3)` and `Some(4)`) -//! - `EnumDiscr` when `Self` is an enum, for comparing the enum discriminants. -//! - `StaticEnum` and `StaticStruct` for static methods, where the type -//! being derived upon is either an enum or struct respectively. (Any -//! argument with type Self is just grouped among the non-self -//! arguments.) -//! -//! In the first two cases, the values from the corresponding fields in -//! all the arguments are grouped together. -//! -//! The non-static cases have `Option` in several places associated -//! with field `expr`s. This represents the name of the field it is -//! associated with. It is only not `None` when the associated field has -//! an identifier in the source code. For example, the `x`s in the -//! following snippet -//! -//! ```rust -//! struct A { -//! x: i32, -//! } -//! -//! struct B(i32); -//! -//! enum C { -//! C0(i32), -//! C1 { x: i32 } -//! } -//! ``` -//! -//! The `i32`s in `B` and `C0` don't have an identifier, so the -//! `Option`s would be `None` for them. -//! -//! # Examples -//! -//! The following simplified `PartialEq` is used for in-code examples: -//! -//! ```rust -//! trait PartialEq { -//! fn eq(&self, other: &Self) -> bool; -//! } -//! -//! impl PartialEq for i32 { -//! fn eq(&self, other: &i32) -> bool { -//! *self == *other -//! } -//! } -//! ``` -//! -//! Some examples of the values of `Substructure` follow, using the -//! above `PartialEq`, `A`, `B` and `C`. -//! -//! ## Structs -//! -//! When generating the `expr` for the `A` impl, the `Substructure` is -//! -//! ```text -//! Struct(vec![FieldInfo { -//! span: , -//! name: Some(), -//! self_expr: , -//! other_selflike_expr: Some(), -//! }]) -//! ``` -//! -//! For the `B` impl, called with `B(a)` and `B(b)`, -//! -//! ```text -//! Struct(vec![FieldInfo { -//! span: , -//! name: None, -//! self_expr: , -//! other_selflike_expr: Some(), -//! }]) -//! ``` -//! -//! ## Enums -//! -//! When generating the `expr` for a call with `self == C0(a)` and `other -//! == C0(b)`, the Substructure is -//! -//! ```text -//! EnumMatching( -//! , -//! vec![FieldInfo { -//! span: , -//! name: None, -//! self_expr: , -//! other_selflike_expr: Some(), -//! }], -//! ) -//! ``` -//! -//! For `C1 {x}` and `C1 {x}`, -//! -//! ```text -//! EnumMatching( -//! , -//! vec![FieldInfo { -//! span: , -//! name: Some(), -//! self_expr: , -//! other_selflike_expr: Some(), -//! }], -//! ) -//! ``` -//! -//! For the discriminants, -//! -//! ```text -//! EnumDiscr() -//! ``` -//! -//! Note that this setup doesn't allow for the brute-force "match every variant -//! against every other variant" approach, which is bad because it produces a -//! quadratic amount of code (see #15375). -//! -//! ## Static -//! -//! A static method on the types above would result in, -//! -//! ```text -//! StaticStruct() -//! -//! StaticStruct() -//! -//! StaticEnum() -//! ``` - use std::ops::Not; pub(crate) use Substructure::*; pub(crate) use rustc_ast as ast; -use rustc_ast::{ - EnumDef, Expr, GenericArg, GenericParam, GenericParamKind, Generics, Safety, VariantData, -}; +use rustc_ast::{EnumDef, Expr, GenericParamKind, Generics, Param, Safety, VariantData}; use rustc_attr_ir::{Attribute, AttributeKind, ReprPacked}; use rustc_attr_parsing::AttributeParser; use rustc_expand::base::ExtCtxt; @@ -161,6 +10,7 @@ use rustc_span::{Ident, Span, Symbol, kw, sym}; pub(crate) use smallvec::{SmallVec, smallvec}; use thin_vec::{ThinVec, thin_vec}; +use crate::util::generic_param_to_arg; use crate::{deriving, diagnostics}; pub(crate) struct TraitDef<'a> { @@ -200,23 +50,14 @@ pub(crate) struct MethodDef<'a> { /// List of generics, e.g., `R: rand::Rng` pub generics: Generics, - /// Is there is a `&self` argument? If not, it is a static function. - pub explicit_self: bool, - - /// Arguments other than the self argument. - pub nonself_args: SmallVec<[(Symbol, Box); 1]>, - - /// Whether this method has another arg of type `&self`. - pub has_other_selflike_arg: bool, + pub args: ThinVec, /// Returns type pub ret_ty: Box, pub attributes: ast::AttrVec, - pub fieldless_variants_strategy: FieldlessVariantsStrategy, - - pub body: MethodBodyFunc<'a>, + pub body: MethodBody<'a>, } /// How to handle fieldless enum variants. @@ -232,46 +73,44 @@ pub(crate) enum FieldlessVariantsStrategy { } /// Summary of the relevant parts of a struct/enum field. -pub(crate) struct FieldInfo { +pub(crate) struct FieldInfo<'a> { pub span: Span, - /// None for tuple structs/normal enum variants, Some for normal - /// structs/struct enum variants. - pub name: Option, /// The expression corresponding to this field of `self` /// (specifically, a reference to it). pub self_expr: Box, /// The expression corresponding to a reference to this field in /// the other selflike argument. pub other_selflike_expr: Option>, - pub maybe_scalar: bool, + pub def: &'a ast::FieldDef, } -/// A summary of the possible sets of fields. -/// If the trait supports unions, they are treated like structs here. +/// A helper that makes the code for several derive macros easier to write +/// as they all have a similar base structure. pub(crate) enum Substructure<'a> { - /// A non-static method where `Self` is a struct. - Struct(&'a ast::VariantData, Vec), + /// A non-static method where `Self` is a struct, including tuple structs. + Struct(&'a ast::VariantData, Vec>), - /// Matching variants of the enum: ast::Variant, - /// fields: the field name is only non-`None` in the case of a struct - /// variant. - EnumMatching(&'a ast::Variant, Vec), + /// Matching variants of the enum: ast::Variant, fields. + /// Created when `Self` is an enum and all the arguments are the + /// same variant of the enum. + EnumMatching(&'a ast::Variant, Vec>), /// The discriminant of an enum. The field is the expression to combine the /// discriminant expression with; it will be `None` if no match is necessary. EnumDiscr(Option>), - - /// A static method where `Self` is a struct. - StaticStruct(&'a ast::VariantData), - - /// A static method where `Self` is an enum. - StaticEnum(&'a ast::EnumDef), } -/// Combine the values of all the fields together. The last argument is -/// all the fields of all the structures. -pub(crate) type MethodBodyFunc<'a> = - Box, Span, Substructure<'_>) -> BlockOrExpr + 'a>; +pub(crate) enum MethodBody<'a> { + /// See the documentation on [`Substructure`] for when this is used. + SubstructureFunc { + body_func: Box, Span, Substructure<'_>) -> BlockOrExpr + 'a>, + strategy: FieldlessVariantsStrategy, + has_other_selflike_arg: bool, + }, + /// The common case. + /// If you are adding a new macro, you most likely want to use this. + Directly(BlockOrExpr), +} struct TypeParameter { bound_generic_params: ThinVec, @@ -325,6 +164,10 @@ impl BlockOrExpr { cx.expr_block(self.into_block(cx, span)) } } + + fn take(&mut self) -> BlockOrExpr { + std::mem::replace(self, BlockOrExpr::new_stmts(ThinVec::new())) + } } /// This method helps to extract all the type parameters referenced from a @@ -402,16 +245,6 @@ impl<'a> TraitDef<'a> { cx: &ExtCtxt<'_>, item: &'a ast::Item, push: &mut dyn FnMut(Box), - ) { - self.expand_ext(cx, item, push, false); - } - - pub(crate) fn expand_ext( - self, - cx: &ExtCtxt<'_>, - item: &'a ast::Item, - push: &mut dyn FnMut(Box), - from_scratch: bool, ) { let span = self.span; let is_packed = matches!( @@ -432,9 +265,9 @@ impl<'a> TraitDef<'a> { methods = self .methods .into_iter() - .filter_map(|method_def| { - let body = if from_scratch || method_def.is_static() { - method_def.call_substructure_method(cx, span, StaticStruct(struct_def)) + .filter_map(|mut method_def| { + let body = if let MethodBody::Directly(body) = &mut method_def.body { + body.take() } else { method_def.expand_struct_method_body(cx, span, struct_def, is_packed) }; @@ -457,9 +290,9 @@ impl<'a> TraitDef<'a> { methods = self .methods .into_iter() - .filter_map(|method_def| { - let body = if from_scratch || method_def.is_static() { - method_def.call_substructure_method(cx, span, StaticEnum(enum_def)) + .filter_map(|mut method_def| { + let body = if let MethodBody::Directly(body) = &mut method_def.body { + body.take() } else { method_def.expand_enum_method_body(cx, span, enum_def) }; @@ -659,19 +492,6 @@ impl<'a> TraitDef<'a> { } impl<'a> MethodDef<'a> { - fn call_substructure_method( - &self, - cx: &ExtCtxt<'_>, - span: Span, - fields: Substructure<'_>, - ) -> BlockOrExpr { - (self.body)(cx, span, fields) - } - - fn is_static(&self) -> bool { - !self.explicit_self - } - fn create_method( self, cx: &ExtCtxt<'_>, @@ -683,17 +503,6 @@ impl<'a> MethodDef<'a> { return None; } - let self_arg = self.explicit_self.then(|| { - let infer_ty = cx.ty(span, ast::TyKind::ImplicitSelf); - let ty = cx.ty_ref(span, infer_ty, None, ast::Mutability::Not); - (kw::SelfLower, ty) - }); - let args = self_arg - .into_iter() - .chain(self.nonself_args) - .map(|(name, ty)| cx.param(span, name, ty)) - .collect(); - let ret_type = if self.ret_ty.kind.is_unit() { ast::FnRetTy::Default(span) } else { @@ -701,7 +510,7 @@ impl<'a> MethodDef<'a> { }; let method_ident = Ident::new(self.name, span); - let fn_decl = cx.fn_decl(args, ret_type); + let fn_decl = cx.fn_decl(self.args, ret_type); let body_block = body.into_block(cx, span); let trait_lo_sp = span.shrink_to_lo(); @@ -766,6 +575,10 @@ impl<'a> MethodDef<'a> { struct_def: &'b VariantData, is_packed: bool, ) -> BlockOrExpr { + let MethodBody::SubstructureFunc { body_func, has_other_selflike_arg, .. } = &self.body + else { + unreachable!() + }; let selflike_fields = struct_def .fields() .iter() @@ -799,19 +612,13 @@ impl<'a> MethodDef<'a> { }; let self_expr = expr_for_selflike_arg(cx.expr_self(span)); - let other_selflike_expr = self - .has_other_selflike_arg - .then(|| expr_for_selflike_arg(cx.expr_name(span, self.nonself_args[0].0))); - FieldInfo { - span: field_span, - name: struct_field.ident, - self_expr, - other_selflike_expr, - maybe_scalar: struct_field.ty.peel_refs().kind.maybe_scalar(), - } + let other_selflike_expr = has_other_selflike_arg + .then(|| expr_for_selflike_arg(cx.expr_name(span, sym::other))); + FieldInfo { span: field_span, self_expr, other_selflike_expr, def: struct_field } }) .collect(); - self.call_substructure_method(cx, span, Struct(struct_def, selflike_fields)) + + body_func(cx, span, Struct(struct_def, selflike_fields)) } /// ``` @@ -855,45 +662,45 @@ impl<'a> MethodDef<'a> { ) -> BlockOrExpr { let variants = &enum_def.variants; - // For zero-variant enum, this function body is unreachable. Generate - // `match *self {}`. This produces machine code identical to `unsafe { - // core::intrinsics::unreachable() }` while being safe and stable. - if variants.is_empty() { - let match_arg = cx.expr_deref(span, cx.expr_self(span)); - let expr = cx.expr_match(span, match_arg, ThinVec::new()); - return BlockOrExpr::new_expr(expr); - } - // There are some special cases involving fieldless enums where no // match is necessary. let all_fieldless = variants.iter().all(|v| v.data.fields().is_empty()); - if all_fieldless { - if variants.len() > 1 { - match self.fieldless_variants_strategy { - FieldlessVariantsStrategy::Unify => { - // If the type is fieldless and the trait uses the discriminant and - // there are multiple variants, we need just an operation on - // the discriminant(s). - return self.call_substructure_method(cx, span, EnumDiscr(None)); - } - FieldlessVariantsStrategy::Default => (), - } - } else if let [variant] = variants.as_slice() { + let MethodBody::SubstructureFunc { body_func, strategy, has_other_selflike_arg } = + &self.body + else { + unreachable!() + }; + // Traits that unify fieldless variants always use the discriminant(s). + let unify_fieldless_variants = *strategy == FieldlessVariantsStrategy::Unify; + + match variants.as_slice() { + [] => { + // For zero-variant enum, this function body is unreachable. Generate + // `match *self {}`. This produces machine code identical to `unsafe { + // core::intrinsics::unreachable() }` while being safe and stable. + let match_arg = cx.expr_deref(span, cx.expr_self(span)); + let expr = cx.expr_match(span, match_arg, ThinVec::new()); + return BlockOrExpr::new_expr(expr); + } + [variant] if all_fieldless => { // If there is a single variant, we don't need an operation on // the discriminant(s). Just use the most degenerate result. - return self.call_substructure_method(cx, span, EnumMatching(variant, Vec::new())); + return body_func(cx, span, EnumMatching(variant, Vec::new())); } + _ if all_fieldless && unify_fieldless_variants => { + // If the type is fieldless and the trait uses the discriminant and + // there are multiple variants, we need just an operation on + // the discriminant(s). + return body_func(cx, span, EnumDiscr(None)); + } + _ => (), } - // Traits that unify fieldless variants always use the discriminant(s). - let unify_fieldless_variants = - self.fieldless_variants_strategy == FieldlessVariantsStrategy::Unify; - // These arms are of the form: // (Variant1, Variant1) => Body1 // (Variant2, Variant2) => Body2 // ... - // where each tuple has length 2 if `self.has_other_selflike_arg` and 1 otherwise + // where each tuple has length 2 if `has_other_selflike_arg` and 1 otherwise let mut match_arms: ThinVec = variants .iter() .filter(|&v| !(unify_fieldless_variants && v.data.fields().is_empty())) @@ -939,7 +746,7 @@ impl<'a> MethodDef<'a> { }; // `(VariantK, VariantK)` or just `VariantK`. - let single_pat = if self.has_other_selflike_arg { + let single_pat = if *has_other_selflike_arg { cx.pat_tuple(span, thin_vec![pat_for_field("__self"), pat_for_field("__arg1"),]) } else { pat_for_field("__self") @@ -959,14 +766,8 @@ impl<'a> MethodDef<'a> { let self_expr = expr_for_field("__self"); let other_selflike_expr = - self.has_other_selflike_arg.then(|| expr_for_field("__arg1")); - FieldInfo { - span, - name: struct_field.ident, - self_expr, - other_selflike_expr, - maybe_scalar: struct_field.ty.peel_refs().kind.maybe_scalar(), - } + has_other_selflike_arg.then(|| expr_for_field("__arg1")); + FieldInfo { span, self_expr, other_selflike_expr, def: struct_field } }) .collect(); // For the BodyK, we need to delegate to our caller, @@ -977,9 +778,8 @@ impl<'a> MethodDef<'a> { // expressions for referencing every field of every // Self arg, assuming all are instances of VariantK. // Build up code associated with such a case. - let arm_expr = self - .call_substructure_method(cx, span, EnumMatching(variant, fields)) - .into_expr(cx, span); + let arm_expr = + body_func(cx, span, EnumMatching(variant, fields)).into_expr(cx, span); cx.arm(span, single_pat, arm_expr) }) @@ -990,12 +790,9 @@ impl<'a> MethodDef<'a> { let default = match first_fieldless { Some(v) if unify_fieldless_variants => { // We need a default case that handles all the fieldless variants. - Some( - self.call_substructure_method(cx, span, EnumMatching(v, Vec::new())) - .into_expr(cx, span), - ) + Some(body_func(cx, span, EnumMatching(v, Vec::new())).into_expr(cx, span)) } - _ if variants.len() > 1 && self.has_other_selflike_arg => { + _ if variants.len() > 1 && *has_other_selflike_arg => { // Because we know that all the arguments will match if we reach // the match expression we add the unreachable intrinsic as the // result of the default which should help llvm in optimizing it. @@ -1017,8 +814,8 @@ impl<'a> MethodDef<'a> { // } let self_expr = cx.expr_self(span); - let match_arg = if self.has_other_selflike_arg { - cx.expr_tuple(span, thin_vec![self_expr, cx.expr_name(span, self.nonself_args[0].0)]) + let match_arg = if *has_other_selflike_arg { + cx.expr_tuple(span, thin_vec![self_expr, cx.expr_name(span, sym::other)]) } else { self_expr }; @@ -1029,21 +826,13 @@ impl<'a> MethodDef<'a> { // is enough. if unify_fieldless_variants && variants.len() > 1 { // Combine a discriminant check with the match. - self.call_substructure_method(cx, span, EnumDiscr(Some(match_expr))) + body_func(cx, span, EnumDiscr(Some(match_expr))) } else { BlockOrExpr::new_expr(match_expr) } } } -pub(crate) fn generic_param_to_arg(cx: &ExtCtxt<'_>, p: &GenericParam, span: Span) -> GenericArg { - match p.kind { - GenericParamKind::Lifetime => GenericArg::Lifetime(cx.lifetime(span, p.ident)), - GenericParamKind::Type { .. } => GenericArg::Type(cx.ty_ident(span, p.ident)), - GenericParamKind::Const { .. } => GenericArg::Const(cx.const_ident(span, p.ident)), - } -} - pub(crate) fn generics_without_defaults(g: &Generics) -> Generics { Generics { params: g diff --git a/compiler/rustc_builtin_macros/src/deriving/hash.rs b/compiler/rustc_builtin_macros/src/deriving/hash.rs index b88176edd785a..18315b0015ed7 100644 --- a/compiler/rustc_builtin_macros/src/deriving/hash.rs +++ b/compiler/rustc_builtin_macros/src/deriving/hash.rs @@ -37,13 +37,17 @@ pub(crate) fn expand_derive_hash( methods: smallvec![MethodDef { name: sym::hash, generics, - explicit_self: true, - nonself_args: smallvec![(sym::state, cx.ty_ref(span, arg, None, Mutability::Mut))], - has_other_selflike_arg: false, + args: thin_vec![ + cx.param_self_ref(span), + cx.param(span, sym::state, cx.ty_ref(span, arg, None, Mutability::Mut)) + ], ret_ty: cx.ty_unit(span), attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)], - fieldless_variants_strategy: FieldlessVariantsStrategy::Unify, - body: Box::new(hash_body), + body: MethodBody::SubstructureFunc { + body_func: Box::new(hash_body), + strategy: FieldlessVariantsStrategy::Unify, + has_other_selflike_arg: false, + }, }], is_const, .. @@ -72,6 +76,5 @@ fn hash_body(cx: &ExtCtxt<'_>, span: Span, substr: Substructure<'_>) -> BlockOrE )]; BlockOrExpr::new_mixed(stmts, match_expr) } - _ => cx.dcx().span_bug(span, "unexpected substructure in `derive(Hash)`"), } } diff --git a/compiler/rustc_builtin_macros/src/deriving/mod.rs b/compiler/rustc_builtin_macros/src/deriving/mod.rs index 31875f702818c..4e862f7fb528e 100644 --- a/compiler/rustc_builtin_macros/src/deriving/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/mod.rs @@ -55,7 +55,7 @@ impl MultiItemModifier for BuiltinDerive { ecx, span, &item, - &mut |a| items.push(Annotatable::Stmt(Box::new(ecx.stmt_item(span, a)))), + &mut |a| items.push(Annotatable::Stmt(ecx.stmt_item(span, a))), is_derive_const, ); } else { diff --git a/compiler/rustc_builtin_macros/src/deriving/ord.rs b/compiler/rustc_builtin_macros/src/deriving/ord.rs index 7d3248c92c32b..e9efec79abe56 100644 --- a/compiler/rustc_builtin_macros/src/deriving/ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/ord.rs @@ -24,23 +24,27 @@ pub(crate) fn expand_derive_ord( methods: smallvec![MethodDef { name: sym::cmp, generics: cx.empty_generics(span), - explicit_self: true, - nonself_args: smallvec![(sym::other, cx.ty_self_ref(span))], - has_other_selflike_arg: true, + args: thin_vec![ + cx.param_self_ref(span), + cx.param(span, sym::other, cx.ty_self_ref(span)) + ], ret_ty: cx.ty_path(path_std!(cx, span, cmp::Ordering)), attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)], - fieldless_variants_strategy: FieldlessVariantsStrategy::Unify, - body: Box::new(|cx, span, substr| { - // Builds: - // - // match ::core::cmp::Ord::cmp(&self.x, &other.x) { - // ::std::cmp::Ordering::Equal => - // ::core::cmp::Ord::cmp(&self.y, &other.y), - // cmp => cmp, - // } - let expr = cmp_body(cx, span, substr, discr_then_data, OrdlikeDerive::Ord); - BlockOrExpr::new_expr(expr) - }), + body: MethodBody::SubstructureFunc { + body_func: Box::new(|cx, span, substr| { + // Builds: + // + // match ::core::cmp::Ord::cmp(&self.x, &other.x) { + // ::std::cmp::Ordering::Equal => + // ::core::cmp::Ord::cmp(&self.y, &other.y), + // cmp => cmp, + // } + let expr = cmp_body(cx, span, substr, discr_then_data, OrdlikeDerive::Ord); + BlockOrExpr::new_expr(expr) + }), + strategy: FieldlessVariantsStrategy::Unify, + has_other_selflike_arg: true, + }, }], is_const, .. diff --git a/compiler/rustc_builtin_macros/src/deriving/partial_eq.rs b/compiler/rustc_builtin_macros/src/deriving/partial_eq.rs index ea6bb72b2ea79..b81c44a36a312 100644 --- a/compiler/rustc_builtin_macros/src/deriving/partial_eq.rs +++ b/compiler/rustc_builtin_macros/src/deriving/partial_eq.rs @@ -38,13 +38,14 @@ pub(crate) fn expand_derive_partial_eq( let methods = smallvec![MethodDef { name: sym::eq, generics: cx.empty_generics(span), - explicit_self: true, - nonself_args: smallvec![(sym::other, cx.ty_self_ref(span))], - has_other_selflike_arg: true, + args: thin_vec![cx.param_self_ref(span), cx.param(span, sym::other, cx.ty_self_ref(span))], ret_ty: cx.ty_name(span, sym::bool), attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)], - fieldless_variants_strategy: FieldlessVariantsStrategy::Unify, - body: Box::new(partial_eq_body), + body: MethodBody::SubstructureFunc { + body_func: Box::new(partial_eq_body), + strategy: FieldlessVariantsStrategy::Unify, + has_other_selflike_arg: true, + }, }]; let trait_def = TraitDef { @@ -109,7 +110,7 @@ pub(crate) fn expand_derive_partial_eq( fn partial_eq_body(cx: &ExtCtxt<'_>, span: Span, substructure: Substructure<'_>) -> BlockOrExpr { BlockOrExpr::new_expr(match substructure { EnumMatching(.., fields) | Struct(.., fields) => { - let combine = move |acc, field: &FieldInfo| { + let combine = move |acc, field: &FieldInfo<'_>| { let rhs = field .other_selflike_expr .as_ref() @@ -130,12 +131,13 @@ fn partial_eq_body(cx: &ExtCtxt<'_>, span: Span, substructure: Substructure<'_>) } }; + let maybe_scalar = |field: &FieldInfo<'_>| field.def.ty.peel_refs().kind.maybe_scalar(); // First compare scalar fields, then compound fields, combining all // with logical AND. fields .iter() - .filter(|field| field.maybe_scalar) - .chain(fields.iter().filter(|field| !field.maybe_scalar)) + .filter(|field| maybe_scalar(field)) + .chain(fields.iter().filter(|field| !maybe_scalar(field))) .fold(None, combine) // If there are no fields, treat as always equal. .unwrap_or_else(|| cx.expr_bool(span, true)) @@ -151,7 +153,6 @@ fn partial_eq_body(cx: &ExtCtxt<'_>, span: Span, substructure: Substructure<'_>) // fields. cx.expr_binary(span, BinOpKind::And, lhs, match_expr) } - _ => cx.dcx().span_bug(span, "unexpected substructure in `derive(PartialEq)`"), }) } diff --git a/compiler/rustc_builtin_macros/src/deriving/partial_ord.rs b/compiler/rustc_builtin_macros/src/deriving/partial_ord.rs index 3bfc7bc05153f..46c0625072d88 100644 --- a/compiler/rustc_builtin_macros/src/deriving/partial_ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/partial_ord.rs @@ -25,10 +25,6 @@ pub(crate) fn expand_derive_partial_ord( let container_id = cx.current_expansion.id.expn_data().parent.expect_local(); let has_derive_ord = cx.resolver.has_derive_ord(container_id); - let default_body: MethodBodyFunc<'_> = - Box::new(|cx, span, substr| partial_cmp_body(cx, span, substr, discr_then_data)); - let simple_body: MethodBodyFunc<'_> = - Box::new(|cx, span, _| partial_cmp_simple_body(cx, span, cx.expr_name(span, sym::other))); let is_simple = match &item.kind { // For unit structs/zero-variant enums, the default generated code is better. ItemKind::Struct(.., ast::VariantData::Unit(..)) => false, @@ -55,13 +51,20 @@ pub(crate) fn expand_derive_partial_ord( let partial_cmp_def = MethodDef { name: sym::partial_cmp, generics: cx.empty_generics(span), - explicit_self: true, - nonself_args: smallvec![(sym::other, cx.ty_self_ref(span))], - has_other_selflike_arg: true, + args: thin_vec![cx.param_self_ref(span), cx.param(span, sym::other, cx.ty_self_ref(span))], ret_ty, attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)], - fieldless_variants_strategy: FieldlessVariantsStrategy::Unify, - body: if is_simple { simple_body } else { default_body }, + body: if is_simple { + MethodBody::Directly(partial_cmp_simple_body(cx, span, cx.expr_name(span, sym::other))) + } else { + MethodBody::SubstructureFunc { + body_func: Box::new(|cx, span, substr| { + partial_cmp_body(cx, span, substr, discr_then_data) + }), + strategy: FieldlessVariantsStrategy::Unify, + has_other_selflike_arg: true, + } + }, }; let trait_def = TraitDef { @@ -74,7 +77,7 @@ pub(crate) fn expand_derive_partial_ord( is_const, .. }; - trait_def.expand_ext(cx, item, push, is_simple) + trait_def.expand(cx, item, push); } pub(crate) fn discr_data_order(item: &ast::Item) -> bool { @@ -208,7 +211,7 @@ pub(crate) fn cmp_body( match substructure { EnumMatching(.., all_fields) | Struct(_, all_fields) => { - let op = |old, field: FieldInfo| { + let op = |old, field: FieldInfo<'_>| { // The basic case: a field expression for one or more selflike args. E.g. // for `Ord::cmp` this is something like `Ord::cmp(&self.x, &other.x)`. let other_expr = @@ -242,6 +245,5 @@ pub(crate) fn cmp_body( discr_check_expr } } - _ => cx.dcx().span_bug(span, "unexpected substructure in `derive`"), } } diff --git a/compiler/rustc_builtin_macros/src/deriving/reborrow.rs b/compiler/rustc_builtin_macros/src/deriving/reborrow.rs index 4ae79420f26c6..af091db2163da 100644 --- a/compiler/rustc_builtin_macros/src/deriving/reborrow.rs +++ b/compiler/rustc_builtin_macros/src/deriving/reborrow.rs @@ -9,6 +9,7 @@ use rustc_span::{Ident, Span, Symbol, sym}; use thin_vec::ThinVec; use crate::deriving::generic::*; +use crate::util::generic_param_to_arg; pub(crate) fn expand_derive_reborrow( cx: &ExtCtxt<'_>, diff --git a/compiler/rustc_builtin_macros/src/global_allocator.rs b/compiler/rustc_builtin_macros/src/global_allocator.rs index 960cf3e2caddf..8cbd4df5b0f18 100644 --- a/compiler/rustc_builtin_macros/src/global_allocator.rs +++ b/compiler/rustc_builtin_macros/src/global_allocator.rs @@ -2,8 +2,8 @@ use rustc_ast::expand::allocator::{ ALLOCATOR_METHODS, AllocatorMethod, AllocatorMethodInput, AllocatorTy, global_fn_name, }; use rustc_ast::{ - self as ast, AttrVec, Expr, FnHeader, FnSig, Generics, ItemKind, Mutability, Param, Safety, - Stmt, StmtKind, Ty, + self as ast, Expr, FnHeader, FnSig, Generics, ItemKind, Mutability, Param, Safety, Stmt, + StmtKind, Ty, }; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::{Ident, Span, Symbol, sym}; @@ -45,17 +45,18 @@ pub(crate) fn expand( return vec![orig_item]; } - // Generate a bunch of new items using the AllocFnFactory let span = ecx.with_def_site_ctxt(item.span); - let f = AllocFnFactory { span, ty_span, global: ident, cx: ecx }; // Generate item statements for the allocator methods. - let stmts = ALLOCATOR_METHODS.iter().map(|method| f.allocator_fn(method)).collect(); + let stmts = ALLOCATOR_METHODS + .iter() + .map(|method| allocator_fn(ecx, span, ty_span, ident, method)) + .collect(); // Generate anonymous constant serving as container for the allocator methods. let const_item = ecx.item_const_underscore(span, ecx.block(span, stmts)); let const_item = if is_stmt { - Annotatable::Stmt(Box::new(ecx.stmt_item(span, const_item))) + Annotatable::Stmt(ecx.stmt_item(span, const_item)) } else { Annotatable::Item(const_item) }; @@ -64,124 +65,108 @@ pub(crate) fn expand( vec![orig_item, const_item] } -struct AllocFnFactory<'a, 'b> { +fn allocator_fn( + cx: &ExtCtxt<'_>, span: Span, ty_span: Span, global: Ident, - cx: &'a ExtCtxt<'b>, + method: &AllocatorMethod, +) -> Stmt { + let mut abi_args = ThinVec::new(); + let args = method.inputs.iter().map(|input| arg_ty(cx, span, input, &mut abi_args)).collect(); + let result = call_allocator(cx, ty_span, global, method.name, args); + let output_ty = match method.output { + AllocatorTy::ResultPtr => ptr_u8(cx, span), + AllocatorTy::Unit => cx.ty_unit(span), + AllocatorTy::Layout | AllocatorTy::Never | AllocatorTy::Usize | AllocatorTy::Ptr => { + panic!("can't convert `AllocatorTy` to an output") + } + }; + let decl = cx.fn_decl(abi_args, ast::FnRetTy::Ty(output_ty)); + let header = FnHeader { safety: Safety::Unsafe(span), ..FnHeader::default() }; + let sig = FnSig { decl, header, span }; + let body = Some(cx.block_expr(result)); + let kind = ItemKind::Fn(cx.item_fn( + sig, + Ident::from_str_and_span(&global_fn_name(method.name), span), + Generics::default(), + body, + )); + let alloc_attr = match method.name { + sym::alloc => sym::rustc_allocator, + sym::dealloc => sym::rustc_deallocator, + sym::realloc => sym::rustc_reallocator, + sym::alloc_zeroed => sym::rustc_allocator_zeroed, + _ => unreachable!("Unknown allocator method!"), + }; + let attrs = thin_vec![ + cx.attr_word(sym::rustc_std_internal_symbol, span), + cx.attr_word(alloc_attr, span) + ]; + let item = cx.item(span, attrs, kind); + cx.stmt_item(ty_span, item) } -impl AllocFnFactory<'_, '_> { - fn allocator_fn(&self, method: &AllocatorMethod) -> Stmt { - let mut abi_args = ThinVec::new(); - let args = method.inputs.iter().map(|input| self.arg_ty(input, &mut abi_args)).collect(); - let result = self.call_allocator(method.name, args); - let output_ty = self.ret_ty(&method.output); - let decl = self.cx.fn_decl(abi_args, ast::FnRetTy::Ty(output_ty)); - let header = FnHeader { safety: Safety::Unsafe(self.span), ..FnHeader::default() }; - let sig = FnSig { decl, header, span: self.span }; - let body = Some(self.cx.block_expr(result)); - let kind = ItemKind::Fn(self.cx.item_fn( - sig, - Ident::from_str_and_span(&global_fn_name(method.name), self.span), - Generics::default(), - body, - )); - let item = self.cx.item(self.span, self.attrs(method), kind); - self.cx.stmt_item(self.ty_span, item) - } - - fn call_allocator(&self, method: Symbol, mut args: ThinVec>) -> Box { - let method = self.cx.std_path(self.ty_span, &[sym::alloc, sym::GlobalAlloc, method]); - let method = self.cx.expr_path(method); - let allocator = self.cx.path_ident(self.ty_span, self.global); - let allocator = self.cx.expr_path(allocator); - let allocator = self.cx.expr_ref(self.ty_span, allocator); - args.insert(0, allocator); - - self.cx.expr_call(self.ty_span, method, args) - } - - fn attrs(&self, method: &AllocatorMethod) -> AttrVec { - let alloc_attr = match method.name { - sym::alloc => sym::rustc_allocator, - sym::dealloc => sym::rustc_deallocator, - sym::realloc => sym::rustc_reallocator, - sym::alloc_zeroed => sym::rustc_allocator_zeroed, - _ => unreachable!("Unknown allocator method!"), - }; - thin_vec![ - self.cx.attr_word(sym::rustc_std_internal_symbol, self.span), - self.cx.attr_word(alloc_attr, self.span) - ] - } +fn call_allocator( + cx: &ExtCtxt<'_>, + ty_span: Span, + global: Ident, + method: Symbol, + mut args: ThinVec>, +) -> Box { + let method = cx.std_path(ty_span, &[sym::alloc, sym::GlobalAlloc, method]); + let method = cx.expr_path(method); + let allocator = cx.path_ident(ty_span, global); + let allocator = cx.expr_path(allocator); + let allocator = cx.expr_ref(ty_span, allocator); + args.insert(0, allocator); + + cx.expr_call(ty_span, method, args) +} - fn arg_ty(&self, input: &AllocatorMethodInput, args: &mut ThinVec) -> Box { - match input.ty { - AllocatorTy::Layout => { - // If an allocator method is ever introduced having multiple - // Layout arguments, these argument names need to be - // disambiguated somehow. Currently the generated code would - // fail to compile with "identifier is bound more than once in - // this parameter list". - - let ty_usize = self.usize(); - args.push(self.cx.param(self.span, sym::size, ty_usize)); - let ty_align = self.ptr_alignment(); - args.push(self.cx.param(self.span, sym::align, ty_align)); - - let layout_new = self.cx.std_path( - self.span, - &[sym::alloc, sym::Layout, sym::from_size_alignment_unchecked], - ); - let layout_new = self.cx.expr_path(layout_new); - let size = self.cx.expr_name(self.span, sym::size); - let align = self.cx.expr_name(self.span, sym::align); - let layout = self.cx.expr_call(self.span, layout_new, thin_vec![size, align]); - layout - } - - AllocatorTy::Ptr => { - let name = Symbol::intern(input.name); - args.push(self.cx.param(self.span, name, self.ptr_u8())); - self.cx.expr_name(self.span, name) - } - - AllocatorTy::Usize => { - let name = Symbol::intern(input.name); - args.push(self.cx.param(self.span, name, self.usize())); - self.cx.expr_name(self.span, name) - } - - AllocatorTy::Never | AllocatorTy::ResultPtr | AllocatorTy::Unit => { - panic!("can't convert AllocatorTy to an argument") - } +fn arg_ty( + cx: &ExtCtxt<'_>, + span: Span, + input: &AllocatorMethodInput, + args: &mut ThinVec, +) -> Box { + match input.ty { + AllocatorTy::Layout => { + // If an allocator method is ever introduced having multiple + // Layout arguments, these argument names need to be + // disambiguated somehow. Currently the generated code would + // fail to compile with "identifier is bound more than once in + // this parameter list". + + let ty_usize = cx.ty_name(span, sym::usize); + args.push(cx.param(span, sym::size, ty_usize)); + let ty_align = cx.ty_path(cx.std_path(span, &[sym::mem, sym::Alignment])); + args.push(cx.param(span, sym::align, ty_align)); + + let layout_new = + cx.std_path(span, &[sym::alloc, sym::Layout, sym::from_size_alignment_unchecked]); + let layout_new = cx.expr_path(layout_new); + let size = cx.expr_name(span, sym::size); + let align = cx.expr_name(span, sym::align); + cx.expr_call(span, layout_new, thin_vec![size, align]) } - } - - fn ret_ty(&self, ty: &AllocatorTy) -> Box { - match *ty { - AllocatorTy::ResultPtr => self.ptr_u8(), - - AllocatorTy::Unit => self.cx.ty_unit(self.span), - - AllocatorTy::Layout | AllocatorTy::Never | AllocatorTy::Usize | AllocatorTy::Ptr => { - panic!("can't convert `AllocatorTy` to an output") - } + AllocatorTy::Ptr => { + let name = Symbol::intern(input.name); + args.push(cx.param(span, name, ptr_u8(cx, span))); + cx.expr_name(span, name) + } + AllocatorTy::Usize => { + let name = Symbol::intern(input.name); + args.push(cx.param(span, name, cx.ty_name(span, sym::usize))); + cx.expr_name(span, name) + } + AllocatorTy::Never | AllocatorTy::ResultPtr | AllocatorTy::Unit => { + panic!("can't convert AllocatorTy to an argument") } } +} - fn usize(&self) -> Box { - self.cx.ty_name(self.span, sym::usize) - } - - fn ptr_alignment(&self) -> Box { - let path = self.cx.std_path(self.span, &[sym::mem, sym::Alignment]); - self.cx.ty_path(path) - } - - fn ptr_u8(&self) -> Box { - let ty_u8 = self.cx.ty_name(self.span, sym::u8); - self.cx.ty_ptr(self.span, ty_u8, Mutability::Mut) - } +fn ptr_u8(cx: &ExtCtxt<'_>, span: Span) -> Box { + let ty_u8 = cx.ty_name(span, sym::u8); + cx.ty_ptr(span, ty_u8, Mutability::Mut) } diff --git a/compiler/rustc_builtin_macros/src/offload.rs b/compiler/rustc_builtin_macros/src/offload.rs index e5076978f7cd1..73e407093fb80 100644 --- a/compiler/rustc_builtin_macros/src/offload.rs +++ b/compiler/rustc_builtin_macros/src/offload.rs @@ -118,9 +118,7 @@ pub(crate) fn expand_kernel( match &item { Annotatable::Item(_) => Annotatable::Item(device_item_ecx), - Annotatable::Stmt(_) => { - Annotatable::Stmt(Box::new(ecx.stmt_item(span, device_item_ecx))) - } + Annotatable::Stmt(_) => Annotatable::Stmt(ecx.stmt_item(span, device_item_ecx)), _ => { unreachable!("item kind checked previously") } @@ -180,7 +178,7 @@ pub(crate) fn expand_kernel( match &item { Annotatable::Item(_) => Annotatable::Item(host_item_ecx), - Annotatable::Stmt(_) => Annotatable::Stmt(Box::new(ecx.stmt_item(span, host_item_ecx))), + Annotatable::Stmt(_) => Annotatable::Stmt(ecx.stmt_item(span, host_item_ecx)), _ => { unreachable!("item kind checked previously") } diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs index d8608b8418a27..ed90d669371bb 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -73,7 +73,7 @@ pub(crate) fn expand_test_case( } let ret = if is_stmt { - Annotatable::Stmt(Box::new(ecx.stmt_item(item.span, item))) + Annotatable::Stmt(ecx.stmt_item(item.span, item)) } else { Annotatable::Item(item) }; @@ -121,7 +121,7 @@ pub(crate) fn expand_test_or_bench( let ast::ItemKind::Fn(fn_) = &item.kind else { not_testable_error(cx, is_bench, attr_sp, Some(&item)); return if is_stmt { - vec![Annotatable::Stmt(Box::new(cx.stmt_item(item.span, item)))] + vec![Annotatable::Stmt(cx.stmt_item(item.span, item))] } else { vec![Annotatable::Item(item)] }; @@ -155,7 +155,7 @@ pub(crate) fn expand_test_or_bench( }; if check_result.is_err() { return if is_stmt { - vec![Annotatable::Stmt(Box::new(cx.stmt_item(item.span, item)))] + vec![Annotatable::Stmt(cx.stmt_item(item.span, item))] } else { vec![Annotatable::Item(item)] }; @@ -385,11 +385,11 @@ pub(crate) fn expand_test_or_bench( if is_stmt { vec![ // Access to libtest under a hygienic name - Annotatable::Stmt(Box::new(cx.stmt_item(sp, test_extern))), + Annotatable::Stmt(cx.stmt_item(sp, test_extern)), // The generated test case - Annotatable::Stmt(Box::new(cx.stmt_item(sp, test_const))), + Annotatable::Stmt(cx.stmt_item(sp, test_const)), // The original item - Annotatable::Stmt(Box::new(cx.stmt_item(sp, item))), + Annotatable::Stmt(cx.stmt_item(sp, item)), ] } else { vec![ diff --git a/compiler/rustc_builtin_macros/src/util.rs b/compiler/rustc_builtin_macros/src/util.rs index c4c90d2cb5378..27eb63b4a07d4 100644 --- a/compiler/rustc_builtin_macros/src/util.rs +++ b/compiler/rustc_builtin_macros/src/util.rs @@ -1,5 +1,8 @@ use rustc_ast::tokenstream::TokenStream; -use rustc_ast::{self as ast, AttrStyle, Attribute, MetaItem, attr, token}; +use rustc_ast::{ + self as ast, AttrStyle, Attribute, GenericArg, GenericParam, GenericParamKind, MetaItem, attr, + token, +}; use rustc_attr_parsing::{AttributeTemplate, DuplicateAttribute, validate_attr}; use rustc_errors::{Applicability, Diag, ErrorGuaranteed}; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt}; @@ -261,3 +264,11 @@ pub(crate) fn get_exprs_from_tts( } ExpandResult::Ready(Ok(es)) } + +pub(crate) fn generic_param_to_arg(cx: &ExtCtxt<'_>, p: &GenericParam, span: Span) -> GenericArg { + match p.kind { + GenericParamKind::Lifetime => GenericArg::Lifetime(cx.lifetime(span, p.ident)), + GenericParamKind::Type { .. } => GenericArg::Type(cx.ty_ident(span, p.ident)), + GenericParamKind::Const { .. } => GenericArg::Const(cx.const_ident(span, p.ident)), + } +} diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index 350fb01df53c8..32ed80437ed95 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -22,7 +22,7 @@ use rustc_codegen_ssa::{MemFlags, RetagInfo}; use rustc_data_structures::fx::FxHashSet; #[cfg(feature = "master")] use rustc_middle::ty::layout::FnAbiOf; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf}; use rustc_middle::ty::{self, Instance, Intrinsic, Ty}; use rustc_session::config::OptLevel; use rustc_span::{Span, Symbol, bug, span_bug, sym}; @@ -511,6 +511,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc &mut self, instance: ty::Instance<'tcx>, args: &[OperandRef<'tcx, Self::Value>], + memory_return_place: Option>, is_cleanup: bool, ) -> Self::Value { let func = if let Some(&func) = self.intrinsic_instances.borrow().get(&instance) { @@ -557,7 +558,48 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc self.apply_attrs_to_cleanup_callsite(llret); } - llret + let fn_sig = match *instance.ty(self.tcx, self.typing_env()).kind() { + ty::FnDef(def_id, args) => self.tcx.instantiate_bound_regions_with_erased( + self.tcx + .fn_sig(def_id) + .instantiate(self.tcx, args.no_bound_vars().unwrap()) + .skip_norm_wip(), + ), + _ => unreachable!(), + }; + let ret_layout = self.layout_of(fn_sig.output()); + + if !ret_layout.is_zst() && ret_layout.is_aggregate() { + let fields = + rustc_codegen_ssa::mir::intrinsic_return_struct_fields(self.cx, ret_layout) + .into_iter() + .enumerate() + .map(|(i, (_, offset))| (offset, self.extract_value(llret, i as u64))) + .collect(); + let is_memory = matches!(ret_layout.backend_repr, BackendRepr::Memory { .. }); + match rustc_codegen_ssa::mir::store_intrinsic_return_struct( + self, + ret_layout, + memory_return_place, + fields, + ) { + IntrinsicResult::Operand(val) => { + assert!(!is_memory); + assert!(memory_return_place.is_none()); + OperandRef { val, layout: ret_layout, move_annotation: None } + .immediate_or_packed_pair(self) + } + IntrinsicResult::WroteIntoPlace => { + assert!(is_memory); + assert!(memory_return_place.is_some()); + // Return value won't be used. + self.const_u8(0) + } + res => bug!("Unexpected LLVM intrinsic result {res:?}"), + } + } else { + llret + } } fn abort_immediate(&mut self) { diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 2f00202146f15..ddefd07efe56b 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -20,7 +20,7 @@ use rustc_hir::def_id::LOCAL_CRATE; use rustc_lint_defs::builtin::DEPRECATED_LLVM_INTRINSIC; use rustc_middle::mir::interpret::{AllocId, Allocation, ErrorHandled, GlobalAlloc, alloc_range}; use rustc_middle::mir::{self, BinOp}; -use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf}; +use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout}; use rustc_middle::ty::offload_meta::OffloadMetadata; use rustc_middle::ty::{self, GenericArgs, Instance, Intrinsic, SimdAlign, Ty, TyCtxt}; use rustc_session::diagnostics::feature_err; @@ -799,6 +799,17 @@ impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { _ => unreachable!(), }; self.type_vector(elem_ll_ty, size) + } else if let ty::Array(elem, _) = result_layout.ty.kind() + && let ty::Uint(ty::UintTy::U8) = elem.kind() + { + // Byte arrays are used to represent iN. + assert_matches!( + result_layout.backend_repr, + BackendRepr::Memory { sized: true } + ); + self.type_ix(result_layout.size.bits()) + } else if result_layout.is_zst() { + self.type_void() } else { result_layout.llvm_type(self) }; @@ -880,7 +891,8 @@ impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { instance: ty::Instance<'tcx>, intrinsic_name: &str, args: &[OperandRef<'tcx, Value<'ll>>], - ) -> Value<'ll> { + memory_return_place: Option>>, + ) -> (IntrinsicResult<'tcx, Value<'ll>>, TyAndLayout<'tcx>) { let tcx = self.tcx(); let fn_ty = instance.ty(tcx, self.typing_env()); @@ -893,10 +905,15 @@ impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { assert!(!fn_sig.c_variadic()); let ret_layout = self.layout_of(fn_sig.output()); - let llreturn_ty = if ret_layout.is_zst() { - self.type_void() + let (llreturn_ty, return_struct_fields) = if ret_layout.is_zst() { + (self.type_void(), vec![]) + } else if ret_layout.is_aggregate() { + let fields = + rustc_codegen_ssa::mir::intrinsic_return_struct_fields(self.cx, ret_layout); + let llvm_fields = fields.iter().copied().map(|(t, _)| t).collect::>(); + (self.type_struct(&llvm_fields), fields) } else { - ret_layout.immediate_llvm_type(self) + (ret_layout.immediate_llvm_type(self), vec![]) }; let mut llargument_tys = Vec::with_capacity(fn_sig.inputs().len()); @@ -950,14 +967,44 @@ impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { ) }; - let src_ty = self.val_ty(llret); - let dest_ty = llreturn_ty; - assert!( - can_autocast(self, dest_ty, src_ty), - "Cannot match `{src_ty:?}` (expected) with `{dest_ty:?}` (found) in `{fn_ptr:?}`" - ); + if ret_layout.is_zst() { + // Match `llvm_value_to_intrinsicresult` + (IntrinsicResult::WroteIntoPlace, ret_layout) + } else if return_struct_fields.is_empty() { + let src_ty = self.val_ty(llret); + let dest_ty = llreturn_ty; + assert!( + can_autocast(self, dest_ty, src_ty), + "Cannot match `{src_ty:?}` (expected) with `{dest_ty:?}` (found) in `{fn_ptr:?}`" + ); - autocast(self, llret, src_ty, dest_ty) + ( + IntrinsicResult::Operand(OperandValue::Immediate(autocast( + self, llret, src_ty, dest_ty, + ))), + ret_layout, + ) + } else { + let fields = return_struct_fields.into_iter().enumerate().map(|(i, (dest_ty, offset))| { + let value = self.extract_value(llret, i as u64); + let src_ty = self.val_ty(value); + assert!( + can_autocast(self, dest_ty, src_ty), + "Cannot match `{src_ty:?}` (expected) with `{dest_ty:?}` (found) in `{fn_ptr:?}`" + ); + let value = autocast(self, value, src_ty, dest_ty); + (offset, value) + }).collect(); + ( + rustc_codegen_ssa::mir::store_intrinsic_return_struct( + self, + ret_layout, + memory_return_place, + fields, + ), + ret_layout, + ) + } } } @@ -983,8 +1030,7 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { name, ), Intrinsic::Backend { llvm } => { - let value = self.codegen_llvm_intrinsic_call_impl(instance, llvm.as_str(), args); - self.llvm_value_to_intrinsicresult(value, result_layout, result_place) + self.codegen_llvm_intrinsic_call_impl(instance, llvm.as_str(), args, result_place).0 } } } @@ -993,9 +1039,31 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { &mut self, instance: ty::Instance<'tcx>, args: &[OperandRef<'tcx, Self::Value>], + memory_return_place: Option>, _is_cleanup: bool, ) -> Self::Value { - self.codegen_llvm_intrinsic_call_impl(instance, self.tcx().symbol_name(instance).name, args) + let (result, ret_layout) = self.codegen_llvm_intrinsic_call_impl( + instance, + self.tcx().symbol_name(instance).name, + args, + memory_return_place, + ); + let is_memory = matches!(ret_layout.backend_repr, BackendRepr::Memory { .. }); + match result { + IntrinsicResult::Operand(val) => { + assert!(!is_memory); + assert!(memory_return_place.is_none()); + OperandRef { val, layout: ret_layout, move_annotation: None } + .immediate_or_packed_pair(self) + } + IntrinsicResult::WroteIntoPlace => { + assert!(is_memory); + assert!(memory_return_place.is_some() || ret_layout.is_zst()); + // Return value won't be used. + self.const_u8(0) + } + res => bug!("Unexpected LLVM intrinsic result {res:?}"), + } } fn abort_immediate(&mut self) { @@ -1081,23 +1149,6 @@ fn can_autocast<'ll>(cx: &CodegenCx<'ll, '_>, rust_ty: Type<'ll>, llvm_ty: Type< } match cx.type_kind(llvm_ty) { - // Some LLVM intrinsics return **non-packed** structs, but they can't be mimicked from Rust - // due to auto field-alignment in non-packed structs (packed structs are represented in LLVM - // as, well, packed structs, so they won't match with those either) - TypeKind::Struct if cx.type_kind(rust_ty) == TypeKind::Struct => { - let rust_element_tys = cx.struct_element_types(rust_ty); - let llvm_element_tys = cx.struct_element_types(llvm_ty); - - if rust_element_tys.len() != llvm_element_tys.len() { - return false; - } - - iter::zip(rust_element_tys, llvm_element_tys).all( - |(rust_element_ty, llvm_element_ty)| { - can_autocast(cx, rust_element_ty, llvm_element_ty) - }, - ) - } _ if let Some((llvm_element_ty, element_count)) = cx.vector_element_type_and_length(llvm_ty) => { @@ -1141,19 +1192,6 @@ fn autocast<'ll>( return val; } match (bx.type_kind(src_ty), bx.type_kind(dest_ty)) { - // re-pack structs - (TypeKind::Struct, TypeKind::Struct) => { - let mut ret = bx.const_poison(dest_ty); - for (idx, (src_element_ty, dest_element_ty)) in - iter::zip(bx.struct_element_types(src_ty), bx.struct_element_types(dest_ty)) - .enumerate() - { - let elt = bx.extract_value(val, idx as u64); - let casted_elt = autocast(bx, elt, src_element_ty, dest_element_ty); - ret = bx.insert_value(ret, casted_elt, idx as u64); - } - ret - } // cast from the i1xN vector type to the primitive type (TypeKind::Vector, TypeKind::Integer) if let Some((elem, vector_length)) = bx.vector_element_type_and_length(src_ty) @@ -1251,9 +1289,17 @@ fn intrinsic_fn<'ll, 'tcx>( let llvm_argument_tys = bx.func_params_types(llvm_fn_ty); let llvm_is_variadic = bx.func_is_variadic(llvm_fn_ty); + let (rust_return_tys, llvm_return_tys) = if bx.type_kind(rust_return_ty) == TypeKind::Struct + && bx.type_kind(llvm_return_ty) == TypeKind::Struct + { + (bx.struct_element_types(rust_return_ty), bx.struct_element_types(llvm_return_ty)) + } else { + (vec![rust_return_ty], vec![llvm_return_ty]) + }; let is_correct_signature = !llvm_is_variadic && rust_argument_tys.len() == llvm_argument_tys.len() - && iter::once((rust_return_ty, llvm_return_ty)) + && rust_return_tys.len() == llvm_return_tys.len() + && iter::zip(rust_return_tys, llvm_return_tys) .chain(iter::zip(rust_argument_tys, llvm_argument_tys)) .all(|(rust_ty, llvm_ty)| can_autocast(bx, rust_ty, llvm_ty)); @@ -2420,12 +2466,9 @@ fn generic_simd_intrinsic<'ll, 'tcx>( { // Zero-extend iN to the array length: let ze = bx.zext(i_, bx.type_ix(expected_bytes * 8)); - - // Convert the integer to a byte array - let ptr = bx.alloca(Size::from_bytes(expected_bytes), Align::ONE); - bx.store(ze, ptr, Align::ONE); - let array_ty = bx.type_byte_array(Size::from_bytes(expected_bytes)); - return Ok(bx.load(array_ty, ptr, Align::ONE)); + // `codegen_intrinsic_call` will store the result to the return place for + // `BackendRepr::Memory` types. + return Ok(ze); } _ => return_error!(InvalidMonomorphization::CannotReturn { span, diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index 678d8c00c68dc..71889fa9c417d 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -2,7 +2,8 @@ use std::cmp; use std::ops::Range; use rustc_abi::{ - Align, ArmCall, CanonAbi, ExternAbi, FieldsShape, HasDataLayout, Size, VariantIdx, Variants, + Align, ArmCall, BackendRepr, CanonAbi, ExternAbi, FieldsShape, HasDataLayout, Size, VariantIdx, + Variants, }; use rustc_ast as ast; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; @@ -1166,38 +1167,42 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let result_layout = self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref())); - let return_dest = if result_layout.is_zst() { - ReturnDest::Nothing - } else if let Some(index) = destination.as_local() { - match self.locals[index] { - LocalRef::Place(dest) => ReturnDest::Store(dest), - LocalRef::UnsizedPlace(_) => bug!("return type must be sized"), - LocalRef::PendingOperand => { - // Handle temporary places, specifically `Operand` ones, as - // they don't have `alloca`s. - ReturnDest::DirectOperand(index) - } - LocalRef::Operand(_) => bug!("place local already assigned to"), + let return_mode = if result_layout.is_zst() { + PassMode::Ignore + } else if let BackendRepr::ScalarPair { .. } = result_layout.backend_repr { + PassMode::Pair(ArgAttributes::new(), ArgAttributes::new()) + } else if result_layout.is_aggregate() { + PassMode::Indirect { + attrs: ArgAttributes::new(), + address_space: None, + mode: IndirectMode::Pointer, } } else { - ReturnDest::Store(self.codegen_place(bx, destination.as_ref())) + PassMode::Direct(ArgAttributes::new()) }; + let return_abi = ArgAbi { layout: result_layout, mode: return_mode }; + let (return_dest, memory_return_place) = + self.make_return_place(bx, destination, &return_abi); + assert_eq!( + memory_return_place.is_some(), + !result_layout.is_zst() + && matches!(result_layout.backend_repr, BackendRepr::Memory { sized: true }) + ); let args = args.into_iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect::>(); self.set_debug_loc(bx, source_info); - let llret = - bx.codegen_llvm_intrinsic_call(instance, &args, self.mir[helper.bb].is_cleanup); + let llret = bx.codegen_llvm_intrinsic_call( + instance, + &args, + memory_return_place, + self.mir[helper.bb].is_cleanup, + ); if let Some(target) = target { - self.store_return( - bx, - return_dest, - &ArgAbi { layout: result_layout, mode: PassMode::Direct(ArgAttributes::new()) }, - llret, - ); + self.store_return(bx, return_dest, &return_abi, llret); return helper.funclet_br(self, bx, target, mergeable_succ, &[]); } else { bx.unreachable(); @@ -2435,15 +2440,33 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } } + // This function is separate from `make_return_place` as `ReturnSlot` should only be constructed + // when it will be used for an indirect return (sret) from an actual backend function call. fn make_return_dest( &mut self, bx: &mut Bx, dest: mir::Place<'tcx>, fn_ret: &ArgAbi<'tcx, Ty<'tcx>>, ) -> (ReturnDest<'tcx, Bx::Value>, ReturnSlot) { + let (dest, place) = self.make_return_place(bx, dest, fn_ret); + ( + dest, + match place { + None => ReturnSlot::Direct, + Some(place) => ReturnSlot::Indirect(place.llval), + }, + ) + } + + fn make_return_place( + &mut self, + bx: &mut Bx, + dest: mir::Place<'tcx>, + fn_ret: &ArgAbi<'tcx, Ty<'tcx>>, + ) -> (ReturnDest<'tcx, Bx::Value>, Option>) { // If the return is ignored, we can just return a do-nothing `ReturnDest`. if fn_ret.is_ignore() { - return (ReturnDest::Nothing, ReturnSlot::Direct); + return (ReturnDest::Nothing, None); } let dest = if let Some(index) = dest.as_local() { match self.locals[index] { @@ -2457,12 +2480,9 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // but the calling convention has an indirect return. let tmp = PlaceRef::alloca(bx, fn_ret.layout); tmp.storage_live(bx); - ( - ReturnDest::IndirectOperand(tmp, index), - ReturnSlot::Indirect(tmp.val.llval), - ) + (ReturnDest::IndirectOperand(tmp, index), Some(tmp.val)) } else { - (ReturnDest::DirectOperand(index), ReturnSlot::Direct) + (ReturnDest::DirectOperand(index), None) }; } LocalRef::Operand(_) => { @@ -2482,13 +2502,13 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // to create a temporary. span_bug!(self.mir.span, "can't directly store to unaligned value"); } - (ReturnDest::Nothing, ReturnSlot::Indirect(dest.val.llval)) + (ReturnDest::Nothing, Some(dest.val)) } else { - (ReturnDest::Store(dest), ReturnSlot::Direct) + (ReturnDest::Store(dest), None) } } - // Stores the return value of a function call into it's final location. + /// Stores the return value of a function call into it's final location. fn store_return( &mut self, bx: &mut Bx, @@ -2618,3 +2638,64 @@ pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( bx.store(value, ptr, align); }; } + +/// This function returns the fields of a Rust struct or tuple for use with +/// [`store_intrinsic_return_struct`] below. All fields must be scalar or SIMD types. This returns +/// a [`Vec`] of `(field_type, field_offset)` pairs. +pub fn intrinsic_return_struct_fields<'tcx, Cx: CodegenMethods<'tcx>>( + cx: &Cx, + ret_layout: TyAndLayout<'tcx>, +) -> Vec<(Cx::Type, Size)> { + let ret_layout = ret_layout.peel_transparent_wrappers_from_non_1zst(cx); + match ret_layout.ty.kind() { + ty::Adt(adt_def, _) if adt_def.is_struct() => {} + ty::Tuple(_) => {} + _ => bug!("invalid intrinsic return type: {ret_layout:?}"), + } + let fields = (0..ret_layout.fields.count()) + .map(|i| { + let field = ret_layout.field(cx, i); + assert!(!field.is_aggregate(), "invalid intrinsic return field: {field:?}"); + (cx.immediate_backend_type(field), ret_layout.fields.offset(i)) + }) + .collect::>(); + assert!(fields.len() >= 2, "invalid intrinsic return type: {ret_layout:?}"); + fields +} + +/// Some LLVM intrinsics return LLVM structs that don't have an equivalent in the Rust type system. +/// This function allows the fields of a LLVM struct to be stored in the fields of a Rust struct. +/// The Rust struct's fields can be obtained using [`intrinsic_return_struct_fields`]. `fields` must +/// be a [`Vec`] of (field_offset, field_value) pairs. +pub fn store_intrinsic_return_struct<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + ret_layout: TyAndLayout<'tcx>, + memory_return_place: Option>, + fields: Vec<(Size, Bx::Value)>, +) -> IntrinsicResult<'tcx, Bx::Value> { + match ret_layout.backend_repr { + BackendRepr::ScalarPair { a: _, b: _, b_offset } => { + let &[(offset0, value0), (offset1, value1)] = fields.as_slice() else { + bug!("Invalid fields for ScalarPair: {fields:?}") + }; + assert_ne!(offset0, offset1); + assert!(offset0 == Size::ZERO || offset1 == Size::ZERO); + assert!(offset0 == b_offset || offset1 == b_offset); + let (a, b) = if offset0 < offset1 { (value0, value1) } else { (value1, value0) }; + IntrinsicResult::Operand(OperandValue::Pair(a, b)) + } + BackendRepr::Memory { sized: true } => { + let dest = + memory_return_place.expect("BackendRepr::Memory return with no return place"); + for (offset, value) in fields.into_iter() { + let pointer = match offset.bytes() { + 0 => dest.llval, + bytes => bx.inbounds_ptradd(dest.llval, bx.const_usize(bytes)), + }; + bx.store(value, pointer, dest.align.restrict_for_offset(offset)); + } + IntrinsicResult::WroteIntoPlace + } + _ => bug!("unexpected aggregate return layout: {ret_layout:?}"), + } +} diff --git a/compiler/rustc_codegen_ssa/src/mir/mod.rs b/compiler/rustc_codegen_ssa/src/mir/mod.rs index 2826952a3bec3..3a74677577eb2 100644 --- a/compiler/rustc_codegen_ssa/src/mir/mod.rs +++ b/compiler/rustc_codegen_ssa/src/mir/mod.rs @@ -28,7 +28,7 @@ mod retag; mod rvalue; mod statement; -pub use self::block::store_cast; +pub use self::block::{intrinsic_return_struct_fields, store_cast, store_intrinsic_return_struct}; use self::debuginfo::{FunctionDebugContext, PerLocalVarDebugInfo}; use self::operand::{OperandRef, OperandValue}; use self::place::PlaceRef; @@ -160,6 +160,7 @@ enum LocalRef<'tcx, V> { PendingOperand, } +#[derive(Debug)] pub enum IntrinsicResult<'tcx, V> { /// This intrinsic created an operand without using the `result_place` argument. /// diff --git a/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs b/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs index 530597c616ff9..49a8eedc8898b 100644 --- a/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs @@ -35,6 +35,7 @@ pub trait IntrinsicCallBuilderMethods<'tcx>: BackendTypes { &mut self, instance: ty::Instance<'tcx>, args: &[OperandRef<'tcx, Self::Value>], + memory_return_place: Option>, is_cleanup: bool, ) -> Self::Value; diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 501bb21c1eea9..8695e7dd71672 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -44,7 +44,7 @@ pub enum Annotatable { Item(Box), AssocItem(Box, AssocCtxt), ForeignItem(Box), - Stmt(Box), + Stmt(ast::Stmt), Expr(Box), Arm(ast::Arm), ExprField(ast::ExprField), @@ -168,7 +168,7 @@ impl Annotatable { pub fn expect_stmt(self) -> ast::Stmt { match self { - Annotatable::Stmt(stmt) => *stmt, + Annotatable::Stmt(stmt) => stmt, _ => panic!("expected statement"), } } @@ -272,12 +272,12 @@ impl<'cx> MacroExpanderResult<'cx> { site_span: Span, arm_span: Span, macro_ident: Ident, - ) -> Self { + ) -> Box { // Emit SEMICOLON_IN_EXPRESSIONS_FROM_MACROS here, rather than the NON_LOCAL version. let is_local = true; let parser = ParserAnyMacro::from_tts(cx, tts, site_span, arm_span, is_local, macro_ident, &[], &[]); - ExpandResult::Ready(Box::new(parser)) + Box::new(parser) } } diff --git a/compiler/rustc_expand/src/build.rs b/compiler/rustc_expand/src/build.rs index 44f4799ab1abc..54e92ac5a4378 100644 --- a/compiler/rustc_expand/src/build.rs +++ b/compiler/rustc_expand/src/build.rs @@ -634,6 +634,21 @@ impl<'a> ExtCtxt<'a> { } } + pub fn param_self_ref(&self, span: Span) -> ast::Param { + let infer_ty = self.ty(span, ast::TyKind::ImplicitSelf); + let ty = self.ty_ref(span, infer_ty, None, ast::Mutability::Not); + let pat = Box::new(self.pat_name(span, kw::SelfLower)); + ast::Param { + attrs: AttrVec::default(), + id: ast::DUMMY_NODE_ID, + pat, + span, + ty, + is_placeholder: false, + has_const_keyword: false, + } + } + // `self` is unused but keep it as method for the convenience use. pub fn fn_decl(&self, inputs: ThinVec, output: ast::FnRetTy) -> Box { Box::new(ast::FnDecl { inputs, output }) diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index d3dea34aff80e..e60b1829e56de 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -1769,7 +1769,7 @@ impl InvocationCollectorNode for ast::Arm { impl InvocationCollectorNode for ast::Stmt { const KIND: AstFragmentKind = AstFragmentKind::Stmts; fn to_annotatable(self) -> Annotatable { - Annotatable::Stmt(Box::new(self)) + Annotatable::Stmt(self) } fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { fragment.make_stmts() diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index 5e01b851b75c7..aa4e1aafcda41 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -135,7 +135,7 @@ impl MultiItemModifier for DeriveProcMacro { Ok(None) => break, Ok(Some(item)) => { if is_stmt { - items.push(Annotatable::Stmt(Box::new(ecx.stmt_item(span, item)))); + items.push(Annotatable::Stmt(ecx.stmt_item(span, item))); } else { items.push(Annotatable::Item(item)); } diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index b2823e3ab9c06..7538ec2660322 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -386,6 +386,8 @@ declare_features! ( (unstable, asm_experimental_reg, "1.85.0", Some(133416)), /// Allows using `label` operands in inline assembly together with output operands. (unstable, asm_goto_with_outputs, "1.85.0", Some(119364)), + /// Allows using thin `NonNull` pointer input operands in inline assembly. + (unstable, asm_nonnull_inputs, "CURRENT_RUSTC_VERSION", Some(166132)), /// Allows the `may_unwind` option in inline assembly. (unstable, asm_unwind, "1.58.0", Some(93334)), /// Allows `_` for the name of associated constants. diff --git a/compiler/rustc_graphviz/src/lib.rs b/compiler/rustc_graphviz/src/lib.rs index 2aaf9cea97e44..237d1ecfdeb83 100644 --- a/compiler/rustc_graphviz/src/lib.rs +++ b/compiler/rustc_graphviz/src/lib.rs @@ -319,22 +319,30 @@ pub enum Style { Bold, Rounded, Diagonals, - Filled, + Filled(FillColor), Striped, Wedged, } +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum FillColor { + Red, + Green, + Unspecified, +} + impl Style { pub fn as_slice(self) -> &'static str { match self { - Style::None => "", + Style::None + // Filling is handled later in `render_opts` + | Style::Filled(_) => "", Style::Solid => "solid", Style::Dashed => "dashed", Style::Dotted => "dotted", Style::Bold => "bold", Style::Rounded => "rounded", Style::Diagonals => "diagonals", - Style::Filled => "filled", Style::Striped => "striped", Style::Wedged => "wedged", } @@ -624,7 +632,17 @@ where let style = g.node_style(n); if !options.contains(&RenderOption::NoNodeStyles) && style != Style::None { - write!(text, "[style=\"{}\"]", style.as_slice()).unwrap(); + if let Style::Filled(fillcolor) = style { + // Filling needs separate handling + let fillcolor_str = match fillcolor { + FillColor::Green => "green", + FillColor::Red => "red", + FillColor::Unspecified => "lightgrey", + }; + write!(text, "[style=\"filled\" fillcolor=\"{fillcolor_str}\"]").unwrap(); + } else { + write!(text, "[style=\"{}\"]", style.as_slice()).unwrap(); + } } if let Some(s) = g.node_shape(n) { diff --git a/compiler/rustc_hir_typeck/src/inline_asm.rs b/compiler/rustc_hir_typeck/src/inline_asm.rs index 384d5302e39e7..32873c1d0d3e9 100644 --- a/compiler/rustc_hir_typeck/src/inline_asm.rs +++ b/compiler/rustc_hir_typeck/src/inline_asm.rs @@ -52,6 +52,19 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { } } + fn maybe_to_pointee_ty(&self, ty: Ty<'tcx>) -> Option> { + Some(match *ty.kind() { + ty::RawPtr(pointee, _) => pointee, + ty::Adt(adt, args) + if self.tcx().is_lang_item(adt.did(), LangItem::NonNull) + && self.tcx().features().asm_nonnull_inputs() => + { + args.type_at(0) + } + _ => return None, + }) + } + // FIXME(compiler-errors): This could use `<$ty as Pointee>::Metadata == ()` fn is_thin_ptr_ty(&self, ty: Ty<'tcx>) -> bool { // Type still may have region variables, but `Sized` does not depend @@ -91,7 +104,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { ty::Float(FloatTy::F64) => Ok(InlineAsmType::F64), ty::Float(FloatTy::F128) => Ok(InlineAsmType::F128), ty::FnPtr(..) => Ok(asm_ty_isize), - ty::RawPtr(elem_ty, _) => { + _ if let Some(elem_ty) = self.maybe_to_pointee_ty(ty) => { if self.is_thin_ptr_ty(elem_ty) { Ok(asm_ty_isize) } else { @@ -245,15 +258,24 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { bug!("inference variable in asm operand ty: {:?} {:?}", expr, ty); } - let asm_ty = match *ty.kind() { + let eff_ty = match *ty.kind() { // `!` is allowed for input but not for output (issue #87802) ty::Never if is_input => return None, _ if ty.references_error() => return None, ty::Adt(adt, args) if self.tcx().is_lang_item(adt.did(), LangItem::MaybeUninit) => { - let ty = args.type_at(0); - self.get_asm_ty(expr.span, ty) + args.type_at(0) + } + _ => ty, + }; + + let asm_ty = match *eff_ty.kind() { + // `NonNull` is allowed as input but not as output. + ty::Adt(adt, _) + if !is_input && self.tcx().is_lang_item(adt.did(), LangItem::NonNull) => + { + Err(NonAsmTypeReason::Invalid(ty)) } - _ => self.get_asm_ty(expr.span, ty), + _ => self.get_asm_ty(expr.span, eff_ty), }; let asm_ty = match asm_ty { Ok(asm_ty) => asm_ty, diff --git a/compiler/rustc_incremental/src/assert_dep_graph.rs b/compiler/rustc_incremental/src/assert_dep_graph.rs index 8147e3c3ae550..74d35753a1461 100644 --- a/compiler/rustc_incremental/src/assert_dep_graph.rs +++ b/compiler/rustc_incremental/src/assert_dep_graph.rs @@ -40,13 +40,15 @@ use std::io::Write; use rustc_attr_ir::{Attribute, AttributeKind}; use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::graph::linked_graph::{Direction, INCOMING, NodeIndex, OUTGOING}; -use rustc_graphviz as dot; +use rustc_graphviz::{self as dot, FillColor, Style}; use rustc_hir as hir; use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; -use rustc_middle::dep_graph::{DepKind, DepNode, DepNodeFilter, EdgeFilter, RetainedDepGraph}; +use rustc_middle::dep_graph::{ + DepGraph, DepKind, DepNode, DepNodeColor, DepNodeFilter, EdgeFilter, RetainedDepGraph, +}; use rustc_middle::hir::nested_filter; -use rustc_middle::ty::TyCtxt; +use rustc_middle::ty::{TyCtxt, tls}; use rustc_span::{Span, Symbol, bug, sym}; use tracing::debug; @@ -60,9 +62,7 @@ pub(crate) fn assert_dep_graph(tcx: TyCtxt<'_>) { let retained_dep_graph = tcx.dep_graph.retained_dep_graph(); if tcx.sess.opts.unstable_opts.dump_dep_graph { - if let Some(graph) = &retained_dep_graph { - dump_graph(graph); - } + dump_graph(&tcx.dep_graph); } if !tcx.sess.opts.unstable_opts.query_dep_graph { @@ -206,7 +206,11 @@ fn check_paths<'tcx>( } } -fn dump_graph(graph: &RetainedDepGraph) { +fn dump_graph(graph: &DepGraph) { + let Some(retained) = &graph.retained_dep_graph() else { + return; + }; + let path: String = env::var("RUST_DEP_GRAPH").unwrap_or_else(|_| "dep_graph".to_string()); let nodes = match env::var("RUST_DEP_GRAPH_FILTER") { @@ -214,13 +218,13 @@ fn dump_graph(graph: &RetainedDepGraph) { // Expect one of: "-> target", "source -> target", or "source ->". let edge_filter = EdgeFilter::new(&string).unwrap_or_else(|e| bug!("invalid filter: {}", e)); - let sources = node_set(graph, &edge_filter.source); - let targets = node_set(graph, &edge_filter.target); - filter_nodes(graph, &sources, &targets) + let sources = node_set(retained, &edge_filter.source); + let targets = node_set(retained, &edge_filter.target); + filter_nodes(retained, &sources, &targets) } - Err(_) => graph.nodes().into_iter().map(|n| n.kind).collect(), + Err(_) => retained.nodes().into_iter().collect(), }; - let edges = filter_edges(graph, &nodes); + let edges = filter_edges(retained, &nodes); { // dump a .txt file with just the edges: @@ -235,39 +239,51 @@ fn dump_graph(graph: &RetainedDepGraph) { // dump a .dot file in graphviz format: let dot_path = format!("{path}.dot"); let mut v = Vec::new(); - dot::render(&GraphvizDepGraph(nodes, edges), &mut v).unwrap(); + dot::render( + &GraphvizDepGraph { + dep_graph: graph.clone(), + nodes: nodes.clone(), + edges: edges.into_iter().map(|(&a, &b)| (a, b)).clone().collect(), + }, + &mut v, + ) + .unwrap(); fs::write(dot_path, v).unwrap(); } } #[allow(missing_docs)] -struct GraphvizDepGraph(FxIndexSet, Vec<(DepKind, DepKind)>); +struct GraphvizDepGraph<'g> { + dep_graph: DepGraph, + nodes: FxIndexSet<&'g DepNode>, + edges: Vec<(DepNode, DepNode)>, +} -impl<'a> dot::GraphWalk<'a> for GraphvizDepGraph { - type Node = DepKind; - type Edge = (DepKind, DepKind); - fn nodes(&self) -> dot::Nodes<'_, DepKind> { - let nodes: Vec<_> = self.0.iter().cloned().collect(); +impl<'a> dot::GraphWalk<'a> for GraphvizDepGraph<'a> { + type Node = DepNode; + type Edge = (DepNode, DepNode); + fn nodes(&self) -> dot::Nodes<'_, DepNode> { + let nodes: Vec<_> = self.nodes.iter().cloned().map(|&a| a).collect(); nodes.into() } - fn edges(&self) -> dot::Edges<'_, (DepKind, DepKind)> { - self.1[..].into() + fn edges(&self) -> dot::Edges<'_, (DepNode, DepNode)> { + self.edges[..].into() } - fn source(&self, edge: &(DepKind, DepKind)) -> DepKind { + fn source(&self, edge: &(DepNode, DepNode)) -> DepNode { edge.0 } - fn target(&self, edge: &(DepKind, DepKind)) -> DepKind { + fn target(&self, edge: &(DepNode, DepNode)) -> DepNode { edge.1 } } -impl<'a> dot::Labeller<'a> for GraphvizDepGraph { - type Node = DepKind; - type Edge = (DepKind, DepKind); +impl<'a> dot::Labeller<'a> for GraphvizDepGraph<'a> { + type Node = DepNode; + type Edge = (DepNode, DepNode); fn graph_id(&self) -> dot::Id<'_> { dot::Id::new("DependencyGraph").unwrap() } - fn node_id(&self, n: &DepKind) -> dot::Id<'_> { + fn node_id(&self, n: &DepNode) -> dot::Id<'_> { let s: String = format!("{n:?}") .chars() .map(|c| if c == '_' || c.is_alphanumeric() { c } else { '_' }) @@ -275,8 +291,25 @@ impl<'a> dot::Labeller<'a> for GraphvizDepGraph { debug!("n={:?} s={:?}", n, s); dot::Id::new(s).unwrap() } - fn node_label(&self, n: &DepKind) -> dot::LabelText<'_> { - dot::LabelText::label(format!("{n:?}")) + fn node_label(&self, n: &DepNode) -> dot::LabelText<'_> { + tls::with_opt(|opt_tcx| { + if let Some(tcx) = opt_tcx + && let Some(def_id) = n.extract_def_id(tcx) + { + dot::LabelText::label(format!("{:?} ({})", n.kind, tcx.def_path_debug_str(def_id))) + } else { + dot::LabelText::label(format!("{:?}", n.kind)) + } + }) + } + + /// Maps `n` to a style that will be used in the rendered output. + fn node_style(&'a self, n: &DepNode) -> Style { + Style::Filled(match self.dep_graph.node_color(n) { + DepNodeColor::Green(_) => FillColor::Green, + DepNodeColor::Red => FillColor::Red, + DepNodeColor::Unknown => FillColor::Unspecified, + }) } } @@ -300,7 +333,7 @@ fn filter_nodes<'g>( graph: &'g RetainedDepGraph, sources: &Option>, targets: &Option>, -) -> FxIndexSet { +) -> FxIndexSet<&'g DepNode> { if let Some(sources) = sources { if let Some(targets) = targets { walk_between(graph, sources, targets) @@ -310,7 +343,7 @@ fn filter_nodes<'g>( } else if let Some(targets) = targets { walk_nodes(graph, targets, INCOMING) } else { - graph.nodes().into_iter().map(|n| n.kind).collect() + graph.nodes().into_iter().collect() } } @@ -318,17 +351,17 @@ fn walk_nodes<'g>( graph: &'g RetainedDepGraph, starts: &FxIndexSet<&'g DepNode>, direction: Direction, -) -> FxIndexSet { +) -> FxIndexSet<&'g DepNode> { let mut set = FxIndexSet::default(); for &start in starts { debug!("walk_nodes: start={:?} outgoing?={:?}", start, direction == OUTGOING); - if set.insert(start.kind) { + if set.insert(start) { let mut stack = vec![graph.indices[start]]; while let Some(index) = stack.pop() { for (_, edge) in graph.inner.adjacent_edges(index, direction) { let neighbor_index = edge.source_or_target(direction); let neighbor = graph.inner.node_data(neighbor_index); - if set.insert(neighbor.kind) { + if set.insert(neighbor) { stack.push(neighbor_index); } } @@ -342,7 +375,7 @@ fn walk_between<'g>( graph: &'g RetainedDepGraph, sources: &FxIndexSet<&'g DepNode>, targets: &FxIndexSet<&'g DepNode>, -) -> FxIndexSet { +) -> FxIndexSet<&'g DepNode> { // This is a bit tricky. We want to include a node only if it is: // (a) reachable from a source and (b) will reach a target. And we // have to be careful about cycles etc. Luckily efficiency is not @@ -373,7 +406,6 @@ fn walk_between<'g>( let index = graph.indices[n]; node_states[index.0] == State::Included }) - .map(|n| n.kind) .collect(); fn recurse(graph: &RetainedDepGraph, node_states: &mut [State], node: NodeIndex) -> bool { @@ -409,12 +441,14 @@ fn walk_between<'g>( } } -fn filter_edges(graph: &RetainedDepGraph, nodes: &FxIndexSet) -> Vec<(DepKind, DepKind)> { +fn filter_edges<'g>( + graph: &'g RetainedDepGraph, + nodes: &'g FxIndexSet<&'g DepNode>, +) -> Vec<(&'g DepNode, &'g DepNode)> { let uniq: FxIndexSet<_> = graph .edges() .into_iter() - .map(|(s, t)| (s.kind, t.kind)) - .filter(|(source, target)| nodes.contains(source) && nodes.contains(target)) + .filter(|&(&source, &target)| nodes.contains(&source) && nodes.contains(&target)) .collect(); uniq.into_iter().collect() } diff --git a/compiler/rustc_middle/src/dep_graph/graph.rs b/compiler/rustc_middle/src/dep_graph/graph.rs index 040e33b16bb17..d2d2a49d13c17 100644 --- a/compiler/rustc_middle/src/dep_graph/graph.rs +++ b/compiler/rustc_middle/src/dep_graph/graph.rs @@ -124,7 +124,7 @@ impl Drop for EdgeFrame<'_> { } #[derive(Debug)] -pub(super) enum DepNodeColor { +pub enum DepNodeColor { Green(DepNodeIndex), Red, Unknown, @@ -877,7 +877,7 @@ impl DepGraph { .any(|node| node.kind == dep_kind) } - fn node_color(&self, dep_node: &DepNode) -> DepNodeColor { + pub fn node_color(&self, dep_node: &DepNode) -> DepNodeColor { if let Some(ref data) = self.data { return data.node_color(dep_node); } diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index e63a281002f0d..b28c5f8a53f15 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -5,7 +5,7 @@ use tracing::instrument; pub use self::dep_node::{DepKind, DepKindVTable, DepNode, WorkProductId, dep_kind_from_label}; pub use self::dep_node_key::DepNodeKey; pub use self::graph::{ - DepGraph, DepGraphData, DepNodeIndex, QuerySideEffect, TaskDepsRef, WorkProduct, + DepGraph, DepGraphData, DepNodeColor, DepNodeIndex, QuerySideEffect, TaskDepsRef, WorkProduct, WorkProductMap, hash_result, }; use self::graph::{MarkFrame, print_markframe_trace}; diff --git a/compiler/rustc_public/src/compiler_interface.rs b/compiler/rustc_public/src/compiler_interface.rs index 0c77abee2dab6..d8021447be79d 100644 --- a/compiler/rustc_public/src/compiler_interface.rs +++ b/compiler/rustc_public/src/compiler_interface.rs @@ -389,6 +389,19 @@ impl<'tcx> CompilerInterface<'tcx> { self.with_cx(|tables, cx| cx.adt_repr(def.internal(tables, cx.tcx)).stable(tables, cx)) } + /// Returns whether this ADT is a phantom data + pub(crate) fn adt_is_phantom_data(&self, def: AdtDef) -> bool { + self.with_cx(|tables, cx| cx.adt_is_phantom_data(def.internal(tables, cx.tcx))) + } + /// Returns whether this ADT is manually drop + pub(crate) fn adt_is_manually_drop(&self, def: AdtDef) -> bool { + self.with_cx(|tables, cx| cx.adt_is_manually_drop(def.internal(tables, cx.tcx))) + } + /// Returns whether this ADT is unsafe cell + pub(crate) fn adt_is_unsafe_cell(&self, def: AdtDef) -> bool { + self.with_cx(|tables, cx| cx.adt_is_unsafe_cell(def.internal(tables, cx.tcx))) + } + /// Retrieve the function signature for the given generic arguments. pub(crate) fn fn_sig(&self, def: FnDef, args: &GenericArgs) -> PolyFnSig { self.with_cx(|tables, cx| { diff --git a/compiler/rustc_public/src/ty/def.rs b/compiler/rustc_public/src/ty/def.rs index 4e34e3bbb2e33..2ce9c1d572c53 100644 --- a/compiler/rustc_public/src/ty/def.rs +++ b/compiler/rustc_public/src/ty/def.rs @@ -204,6 +204,18 @@ impl AdtDef { with(|cx| cx.adt_is_simd(*self)) } + pub fn is_phantom_data(&self) -> bool { + with(|cx| cx.adt_is_phantom_data(*self)) + } + + pub fn is_manually_drop(&self) -> bool { + with(|cx| cx.adt_is_manually_drop(*self)) + } + + pub fn is_unsafe_cell(&self) -> bool { + with(|cx| cx.adt_is_unsafe_cell(*self)) + } + /// The number of variants in this ADT. pub fn num_variants(&self) -> usize { with(|cx| cx.adt_variants_len(*self)) diff --git a/compiler/rustc_public_bridge/src/context/impls.rs b/compiler/rustc_public_bridge/src/context/impls.rs index 1ae42f619c4ba..1290273f2c408 100644 --- a/compiler/rustc_public_bridge/src/context/impls.rs +++ b/compiler/rustc_public_bridge/src/context/impls.rs @@ -376,6 +376,20 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { def.repr() } + /// Returns if the ADT is a PhantomData + pub fn adt_is_phantom_data(&self, def: AdtDef<'tcx>) -> bool { + def.is_phantom_data() + } + + /// Returns if the ADT is ManuallyDrop + pub fn adt_is_manually_drop(&self, def: AdtDef<'tcx>) -> bool { + def.is_manually_drop() + } + + /// Returns if the ADT is an UnsafeCell + pub fn adt_is_unsafe_cell(&self, def: AdtDef<'tcx>) -> bool { + def.is_unsafe_cell() + } /// Retrieve the function signature for the given generic arguments. pub fn fn_sig(&self, def_id: DefId, args_ref: GenericArgs<'tcx>) -> Binder<'tcx, FnSig<'tcx>> { let sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args_ref).skip_norm_wip(); diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index a128abd07b460..a21cecf04448f 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -468,6 +468,7 @@ symbols! { asm_experimental_reg, asm_goto, asm_goto_with_outputs, + asm_nonnull_inputs, asm_sym, asm_unwind, assert, diff --git a/library/Cargo.lock b/library/Cargo.lock index bd63144008d6c..27cb038fb8023 100644 --- a/library/Cargo.lock +++ b/library/Cargo.lock @@ -234,6 +234,8 @@ name = "profiler_builtins" version = "0.0.0" dependencies = [ "cc", + "compiler_builtins", + "core", ] [[package]] diff --git a/library/alloc/src/alloc.rs b/library/alloc/src/alloc.rs index 06bc8a589e1fc..1bb17abbe661e 100644 --- a/library/alloc/src/alloc.rs +++ b/library/alloc/src/alloc.rs @@ -119,8 +119,7 @@ unsafe impl core::alloc::StaticAllocator for Global {} /// /// Users of this function have to consider that in the future, allocators may be allowed to unwind. /// -/// This function is expected to be deprecated in favor of the `allocate` method -/// of the [`Global`] type when it and the [`Allocator`] trait become stable. +/// Calling [`Allocator::allocate`] on `Global` is preferred. /// /// # Safety /// diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index eb122c3a4294d..19621a5b1cb64 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -284,7 +284,7 @@ pub enum DebugAsHex { /// /// `FormattingOptions` is a [`Formatter`] without an attached [`Write`] trait. /// It is mainly used to construct `Formatter` instances. -#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[derive(Copy, Clone, PartialEq, Eq)] #[unstable(feature = "formatting_options", issue = "118117")] pub struct FormattingOptions { /// Flags, with the following bit fields: @@ -535,6 +535,49 @@ impl FormattingOptions { pub const fn create_formatter<'a>(self, write: &'a mut (dyn Write + 'a)) -> Formatter<'a> { Formatter { options: self, buf: write } } + + /// Recreate a format specifier like `-<04x` matching these options. Public only for testing. + #[doc(hidden)] + #[unstable(feature = "fmt_internals", issue = "none")] + pub fn write_fmt_specifier(&self, f: &mut Formatter<'_>, str_escape: bool) -> Result { + let fill = self.get_fill(); + if fill != ' ' { + if str_escape { + write!(f, "{}", fill.escape_debug())?; + } else { + write!(f, "{fill}")?; + } + } + match self.get_align() { + Some(Alignment::Left) => write!(f, "<")?, + Some(Alignment::Right) => write!(f, ">")?, + Some(Alignment::Center) => write!(f, "^")?, + None => (), + } + match self.get_sign() { + Some(Sign::Plus) => write!(f, "+")?, + Some(Sign::Minus) => write!(f, "-")?, + None => (), + } + if self.get_alternate() { + write!(f, "#")?; + } + if self.get_sign_aware_zero_pad() { + write!(f, "0")?; + } + if let Some(width) = self.get_width() { + write!(f, "{width}")?; + } + if let Some(precision) = self.get_precision() { + write!(f, ".{precision}")?; + } + match self.get_debug_as_hex() { + Some(DebugAsHex::Lower) => write!(f, "x")?, + Some(DebugAsHex::Upper) => write!(f, "X")?, + None => (), + } + Ok(()) + } } #[unstable(feature = "formatting_options", issue = "118117")] @@ -546,6 +589,30 @@ impl Default for FormattingOptions { } } +#[unstable(feature = "formatting_options", issue = "118117")] +impl Debug for FormattingOptions { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + // `field_with` for optional values so we don't propagate `#` and turn a simple + // `Some(1)` into three lines. + f.debug_struct("FormattingOptions") + .field_with("align", |f| write!(f, "{:?}", self.get_align())) + .field("alternate", &self.get_alternate()) + .field_with("debug_as_hex", |f| write!(f, "{:?}", self.get_debug_as_hex())) + .field("fill", &self.get_fill()) + .field_with("precision", |f| write!(f, "{:?}", self.get_precision())) + .field_with("sign", |f| write!(f, "{:?}", self.get_sign())) + .field("sign_aware_zero_pad", &self.get_sign_aware_zero_pad()) + .field_with("width", |f| write!(f, "{:?}", self.get_width())) + .field_with("specifier", |f| { + f.write_char('"')?; + self.write_fmt_specifier(f, true)?; + f.write_char('"')?; + Ok(()) + }) + .finish() + } +} + /// Configuration for formatting. /// /// A `Formatter` represents various options related to formatting. Users do not diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 5c20f4a93fb2e..a1153e61bb873 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -2701,7 +2701,7 @@ pub const fn ub_checks() -> bool { #[inline(always)] #[rustc_intrinsic] pub const fn overflow_checks() -> bool { - cfg!(debug_assertions) + cfg!(overflow_checks) } /// Allocates a block of memory at compile time. diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 7f0f250a96486..d1d15c974c0d4 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -110,6 +110,7 @@ #![feature(allow_internal_unstable)] #![feature(arbitrary_self_types_pointers)] #![feature(auto_traits)] +#![feature(cfg_overflow_checks)] #![feature(cfg_sanitize)] #![feature(cfg_target_has_atomic)] #![feature(cfg_ub_checks)] diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index 6aded7cfec682..2f53435f3c3c9 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -1340,8 +1340,6 @@ macro_rules! nonzero_integer { /// # Examples /// /// ``` - /// #![feature(nonzero_ops)] - /// /// # use std::num::NonZero; /// # /// # fn main() { test().unwrap(); } @@ -1355,12 +1353,17 @@ macro_rules! nonzero_integer { /// ``` /// /// [`checked_mul`]: Self::checked_mul - #[unstable(feature = "nonzero_ops", issue = "84186")] + #[stable(feature = "nonzero_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "nonzero_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] pub const unsafe fn unchecked_mul(self, other: Self) -> Self { - // SAFETY: The caller ensures there is no overflow. + // SAFETY: + // - the caller promises that the multiplication does not overflow; + // - `self` and `other` are non-zero; + // - the only way to get zero from a multiplication without overflow + // is for either factor to be zero. unsafe { Self::new_unchecked(self.get().unchecked_mul(other.get())) } } @@ -2042,8 +2045,6 @@ macro_rules! nonzero_integer_signedness_dependent_methods { /// # Examples /// /// ``` - /// #![feature(nonzero_ops)] - /// /// # use std::num::NonZero; /// # /// # fn main() { test().unwrap(); } @@ -2057,12 +2058,17 @@ macro_rules! nonzero_integer_signedness_dependent_methods { /// ``` /// /// [`checked_add`]: Self::checked_add - #[unstable(feature = "nonzero_ops", issue = "84186")] + #[stable(feature = "nonzero_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "nonzero_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] pub const unsafe fn unchecked_add(self, other: $Int) -> Self { - // SAFETY: The caller ensures there is no overflow. + // SAFETY: + // - the caller promises that the addition does not overflow; + // - `self` is non-zero; + // - the only way to get zero from an addition of unsigned integers + // without overflow is for both addends to be zero. unsafe { Self::new_unchecked(self.get().unchecked_add(other)) } } diff --git a/library/core/src/ops/range.rs b/library/core/src/ops/range.rs index d81279cb56be3..1395630396b89 100644 --- a/library/core/src/ops/range.rs +++ b/library/core/src/ops/range.rs @@ -1,6 +1,5 @@ use crate::fmt; use crate::hash::Hash; -use crate::marker::Destruct; /// An unbounded range (`..`). /// /// `RangeFull` is primarily used as a [slicing index], its shorthand is `..`. @@ -987,76 +986,6 @@ pub const trait IntoBounds: [const] RangeBounds { /// assert_eq!((..=7).into_bounds(), (Unbounded, Included(7))); /// ``` fn into_bounds(self) -> (Bound, Bound); - - /// Compute the intersection of `self` and `other`. - /// - /// # Examples - /// - /// ``` - /// #![feature(range_into_bounds)] - /// use std::ops::Bound::*; - /// use std::ops::IntoBounds; - /// - /// assert_eq!((3..).intersect(..5), (Included(3), Excluded(5))); - /// assert_eq!((-12..387).intersect(0..256), (Included(0), Excluded(256))); - /// assert_eq!((1..5).intersect(..), (Included(1), Excluded(5))); - /// assert_eq!((1..=9).intersect(0..10), (Included(1), Included(9))); - /// assert_eq!((7..=13).intersect(8..13), (Included(8), Excluded(13))); - /// ``` - /// - /// Combine with `is_empty` to determine if two ranges overlap. - /// - /// ``` - /// #![feature(range_into_bounds)] - /// #![feature(range_bounds_is_empty)] - /// use std::ops::{RangeBounds, IntoBounds}; - /// - /// assert!(!(3..).intersect(..5).is_empty()); - /// assert!(!(-12..387).intersect(0..256).is_empty()); - /// assert!((1..5).intersect(6..).is_empty()); - /// ``` - fn intersect(self, other: R) -> (Bound, Bound) - where - Self: Sized, - T: [const] Ord + [const] Destruct, - R: Sized + [const] IntoBounds, - { - let (self_start, self_end) = IntoBounds::into_bounds(self); - let (other_start, other_end) = IntoBounds::into_bounds(other); - - let start = match (self_start, other_start) { - (Included(a), Included(b)) => Included(Ord::max(a, b)), - (Excluded(a), Excluded(b)) => Excluded(Ord::max(a, b)), - (Unbounded, Unbounded) => Unbounded, - - (x, Unbounded) | (Unbounded, x) => x, - - (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => { - if i > e { - Included(i) - } else { - Excluded(e) - } - } - }; - let end = match (self_end, other_end) { - (Included(a), Included(b)) => Included(Ord::min(a, b)), - (Excluded(a), Excluded(b)) => Excluded(Ord::min(a, b)), - (Unbounded, Unbounded) => Unbounded, - - (x, Unbounded) | (Unbounded, x) => x, - - (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => { - if i < e { - Included(i) - } else { - Excluded(e) - } - } - }; - - (start, end) - } } use self::Bound::{Excluded, Included, Unbounded}; diff --git a/library/core/src/range.rs b/library/core/src/range.rs index ea4ac96179981..a96abbee34de4 100644 --- a/library/core/src/range.rs +++ b/library/core/src/range.rs @@ -17,6 +17,7 @@ use crate::fmt; use crate::hash::Hash; +use crate::marker::Destruct; mod iter; @@ -759,3 +760,452 @@ where (OneSidedRangeBound::EndInclusive, self.last) } } + +/// Computes the intersection of two ranges, returning the most specific range type possible. +/// +/// This trait is not implemented for all combinations, only the ones with a good +/// `Self::Intersection` type available. +/// +/// However, because `(Bound, Bound): RangeIntersect`, you can always use +/// `a.into_bounds().intersect(b.into_bounds())` for any two [`IntoBounds`] types if needed. +/// +/// # Examples +/// +/// ``` +/// #![feature(range_intersect)] +/// use core::range::{Range, RangeFrom, RangeInclusive, RangeIntersect}; +/// +/// assert_eq!( +/// Range::from(-12..387).intersect(Range::from(0..256)), +/// Range::from(0..256), +/// ); +/// assert_eq!( +/// RangeFrom::from(3..).intersect(..5), +/// Range::from(3..5), +/// ); +/// assert_eq!( +/// RangeInclusive::from(1..=9).intersect(RangeFrom::from(5..)), +/// RangeInclusive::from(5..=9), +/// ); +/// ``` +/// +/// Combine with `is_empty` to determine if two ranges overlap: +/// +/// ``` +/// #![feature(range_intersect)] +/// use core::range::{Range, RangeFrom, RangeIntersect}; +/// +/// assert!(!RangeFrom::from(3..).intersect(..5).is_empty()); +/// assert!(!Range::from(-12..387).intersect(Range::from(0..256)).is_empty()); +/// assert!(Range::from(1..5).intersect(RangeFrom::from(6..)).is_empty()); +/// ``` +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +pub const trait RangeIntersect: Sized { + /// The resulting range type of the intersection. + #[unstable(feature = "range_intersect", issue = "165428")] + type Intersection; + + /// Computes the intersection of `self` and `rhs`. + #[unstable(feature = "range_intersect", issue = "165428")] + #[must_use] + fn intersect(self, rhs: Rhs) -> Self::Intersection; +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for (Bound, Bound) +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = Self; + + #[inline] + fn intersect(self, rhs: Self) -> Self::Intersection { + let (self_start, self_end) = self; + let (other_start, other_end) = rhs; + + let start = match (self_start, other_start) { + (Included(a), Included(b)) => Included(Ord::max(a, b)), + (Excluded(a), Excluded(b)) => Excluded(Ord::max(a, b)), + (Unbounded, Unbounded) => Unbounded, + + (x, Unbounded) | (Unbounded, x) => x, + + (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => { + if i > e { + Included(i) + } else { + Excluded(e) + } + } + }; + let end = match (self_end, other_end) { + (Included(a), Included(b)) => Included(Ord::min(a, b)), + (Excluded(a), Excluded(b)) => Excluded(Ord::min(a, b)), + (Unbounded, Unbounded) => Unbounded, + + (x, Unbounded) | (Unbounded, x) => x, + + (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => { + if i < e { + Included(i) + } else { + Excluded(e) + } + } + }; + + (start, end) + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for Range +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: Self) -> Self::Intersection { + Range { start: Ord::max(self.start, rhs.start), end: Ord::min(self.end, rhs.end) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for Range +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: RangeFrom) -> Self::Intersection { + Range { start: Ord::max(self.start, rhs.start), end: self.end } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for Range +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: RangeTo) -> Self::Intersection { + Range { start: self.start, end: Ord::min(self.end, rhs.end) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for Range { + type Intersection = Range; + + #[inline] + fn intersect(self, _rhs: RangeFull) -> Self::Intersection { + self + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFrom +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: Range) -> Self::Intersection { + Range { start: Ord::max(self.start, rhs.start), end: rhs.end } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeFrom +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeFrom; + + #[inline] + fn intersect(self, rhs: Self) -> Self::Intersection { + RangeFrom { start: Ord::max(self.start, rhs.start) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFrom { + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: RangeTo) -> Self::Intersection { + Range { start: self.start, end: rhs.end } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeFrom { + type Intersection = RangeFrom; + + #[inline] + fn intersect(self, _rhs: RangeFull) -> Self::Intersection { + self + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFrom +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeInclusive) -> Self::Intersection { + RangeInclusive { start: Ord::max(self.start, rhs.start), last: rhs.last } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFrom { + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeToInclusive) -> Self::Intersection { + RangeInclusive { start: self.start, last: rhs.last } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeTo +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: Range) -> Self::Intersection { + Range { start: rhs.start, end: Ord::min(self.end, rhs.end) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeTo { + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: RangeFrom) -> Self::Intersection { + Range { start: rhs.start, end: self.end } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeTo +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeTo; + + #[inline] + fn intersect(self, rhs: Self) -> Self::Intersection { + RangeTo { end: Ord::min(self.end, rhs.end) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeTo { + type Intersection = RangeTo; + + #[inline] + fn intersect(self, _rhs: RangeFull) -> Self::Intersection { + self + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFull { + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: Range) -> Self::Intersection { + rhs + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFull { + type Intersection = RangeFrom; + + #[inline] + fn intersect(self, rhs: RangeFrom) -> Self::Intersection { + rhs + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFull { + type Intersection = RangeTo; + + #[inline] + fn intersect(self, rhs: RangeTo) -> Self::Intersection { + rhs + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeFull { + type Intersection = RangeFull; + + #[inline] + fn intersect(self, _rhs: RangeFull) -> Self::Intersection { + RangeFull + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFull { + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeInclusive) -> Self::Intersection { + rhs + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFull { + type Intersection = RangeToInclusive; + + #[inline] + fn intersect(self, rhs: RangeToInclusive) -> Self::Intersection { + rhs + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeInclusive +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeFrom) -> Self::Intersection { + RangeInclusive { start: Ord::max(self.start, rhs.start), last: self.last } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeInclusive { + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, _rhs: RangeFull) -> Self::Intersection { + self + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeInclusive +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: Self) -> Self::Intersection { + RangeInclusive { + start: Ord::max(self.start, rhs.start), + last: Ord::min(self.last, rhs.last), + } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeInclusive +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeToInclusive) -> Self::Intersection { + RangeInclusive { start: self.start, last: Ord::min(self.last, rhs.last) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeToInclusive { + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeFrom) -> Self::Intersection { + RangeInclusive { start: rhs.start, last: self.last } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeToInclusive { + type Intersection = RangeToInclusive; + + #[inline] + fn intersect(self, _rhs: RangeFull) -> Self::Intersection { + self + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeToInclusive +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeInclusive) -> Self::Intersection { + RangeInclusive { start: rhs.start, last: Ord::min(self.last, rhs.last) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeToInclusive +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeToInclusive; + + #[inline] + fn intersect(self, rhs: Self) -> Self::Intersection { + RangeToInclusive { last: Ord::min(self.last, rhs.last) } + } +} diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index be0162e9ccc5e..ca90bdb60efac 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -186,12 +186,14 @@ impl [T] { /// # Examples /// /// ``` - /// let x = &[0, 1, 2]; + /// let many = &[0, 1, 2]; + /// assert_eq!(many.split_first(), Some((&0, &[1, 2][..]))); /// - /// if let Some((first, elements)) = x.split_first() { - /// assert_eq!(first, &0); - /// assert_eq!(elements, &[1, 2]); - /// } + /// let one = &[42]; + /// assert_eq!(one.split_first(), Some((&42, &[][..]))); + /// + /// let none: &[i32] = &[]; + /// assert_eq!(none.split_first(), None); /// ``` #[stable(feature = "slice_splits", since = "1.5.0")] #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] @@ -206,14 +208,22 @@ impl [T] { /// # Examples /// /// ``` - /// let x = &mut [0, 1, 2]; + /// let many = &mut [0, 1, 2]; /// - /// if let Some((first, elements)) = x.split_first_mut() { + /// if let Some((first, rest)) = many.split_first_mut() { /// *first = 3; - /// elements[0] = 4; - /// elements[1] = 5; + /// rest[0] = 4; + /// rest[1] = 5; /// } - /// assert_eq!(x, &[3, 4, 5]); + /// assert_eq!(many, &[3, 4, 5]); + /// + /// let mut one = [42]; + /// let (first, rest) = one.split_first_mut().unwrap(); + /// assert_eq!(*first, 42); + /// assert!(rest.is_empty()); + /// + /// let none: &mut [i32] = &mut []; + /// assert!(none.split_first_mut().is_none()); /// ``` #[stable(feature = "slice_splits", since = "1.5.0")] #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")] @@ -228,12 +238,14 @@ impl [T] { /// # Examples /// /// ``` - /// let x = &[0, 1, 2]; + /// let many = &[0, 1, 2]; + /// assert_eq!(many.split_last(), Some((&2, &[0, 1][..]))); /// - /// if let Some((last, elements)) = x.split_last() { - /// assert_eq!(last, &2); - /// assert_eq!(elements, &[0, 1]); - /// } + /// let one = &[42]; + /// assert_eq!(one.split_last(), Some((&42, &[][..]))); + /// + /// let none: &[i32] = &[]; + /// assert_eq!(none.split_last(), None); /// ``` #[stable(feature = "slice_splits", since = "1.5.0")] #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] @@ -248,14 +260,22 @@ impl [T] { /// # Examples /// /// ``` - /// let x = &mut [0, 1, 2]; + /// let many = &mut [0, 1, 2]; /// - /// if let Some((last, elements)) = x.split_last_mut() { + /// if let Some((last, rest)) = many.split_last_mut() { /// *last = 3; - /// elements[0] = 4; - /// elements[1] = 5; + /// rest[0] = 4; + /// rest[1] = 5; /// } - /// assert_eq!(x, &[4, 5, 3]); + /// assert_eq!(many, &[4, 5, 3]); + /// + /// let mut one = [42]; + /// let (last, rest) = one.split_last_mut().unwrap(); + /// assert_eq!(*last, 42); + /// assert!(rest.is_empty()); + /// + /// let none: &mut [i32] = &mut []; + /// assert!(none.split_last_mut().is_none()); /// ``` #[stable(feature = "slice_splits", since = "1.5.0")] #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")] diff --git a/library/coretests/tests/fmt/mod.rs b/library/coretests/tests/fmt/mod.rs index 67ba49db4d919..016c57e69944d 100644 --- a/library/coretests/tests/fmt/mod.rs +++ b/library/coretests/tests/fmt/mod.rs @@ -2,6 +2,9 @@ mod builders; mod float; mod num; +use core::fmt; +use core::fmt::Write; + #[test] fn test_lifetime() { // Trigger all different forms of expansion, @@ -199,3 +202,74 @@ fn formatting_options_flags() { } } } + +#[test] +fn test_options_as_specifier() { + struct F; + impl fmt::Display for F { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.options().write_fmt_specifier(f, false) + } + } + impl fmt::Debug for F { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } + } + + // LowerExp (arbitrary choice) prints in string format + impl fmt::LowerExp for F { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_char('"')?; + f.options().write_fmt_specifier(f, true)?; + f.write_char('"')?; + Ok(()) + } + } + + let f = F; + + // Default + assert_eq!(format!("{f}"), ""); + + // Width + assert_eq!(format!("{f:1}"), "1"); + + // Fill and align + assert_eq!(format!("{f:<}"), "<"); + assert_eq!(format!("{f:^}"), "^"); + assert_eq!(format!("{f:>}"), ">"); + assert_eq!(format!("{f:<5}"), "<5"); + assert_eq!(format!("{f:^5}"), "^5"); + assert_eq!(format!("{f:>5}"), ">5"); + assert_eq!(format!("{f:x>5}"), "x>5"); + + // Sign and alternates + assert_eq!(format!("{f:+}"), "+"); + assert_eq!(format!("{f:-}"), "-"); + assert_eq!(format!("{f:#}"), "#"); + assert_eq!(format!("{f:0}"), "0"); + + // Precision + assert_eq!(format!("{f:.1}"), ".1"); + + // Hex within other format types + assert_eq!(format!("{f:x?}"), "x"); + assert_eq!(format!("{f:X?}"), "X"); + + // Hodgepodge + assert_eq!(format!("{f:#018}"), "#018"); + assert_eq!(format!("{f:0123}"), "0123"); + assert_eq!(format!("{f:-<5}"), "-<5"); + assert_eq!(format!("{f:+<05.2}"), "+<05.2"); + assert_eq!(format!("{f:x<+#065535.123X?}"), "x<+#065535.123X"); + + // String quoting is done by the lowerexp impl in our tests + assert_eq!(format!("{f:\"<5e}"), r#""\"<5""#); + assert_eq!(format!("{f:'<5e}"), r#""\'<5""#); + assert_eq!(format!("{f:\\<5e}"), r#""\\<5""#); + // Same thing, unescaped + assert_eq!(format!("{f:\"<5}"), r#""<5"#); + assert_eq!(format!("{f:'<5}"), r#"'<5"#); + assert_eq!(format!("{f:\\<5}"), r#"\<5"#); +} diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index 3e79c88a116e3..224f316fcbc8f 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -105,6 +105,8 @@ #![feature(pointer_is_aligned_to)] #![feature(portable_simd)] #![feature(ptr_metadata)] +#![feature(range_intersect)] +#![feature(range_into_bounds)] #![feature(raw_os_error_ty)] #![feature(register_tool)] #![feature(rustc_attrs)] diff --git a/library/coretests/tests/ops.rs b/library/coretests/tests/ops.rs index 1cbc625959886..6c644d4d221a6 100644 --- a/library/coretests/tests/ops.rs +++ b/library/coretests/tests/ops.rs @@ -318,3 +318,86 @@ fn test_fmt() { assert_eq!(format!("{:?}", ..=1), "..=1"); assert_eq!(format!("{:?}", ..), ".."); } + +#[test] +fn test_range_intersect() { + use core::ops::Bound::{Excluded, Included, Unbounded}; + use core::ops::IntoBounds; + use core::range::{ + Range as NewRange, RangeFrom as NewRangeFrom, RangeInclusive as NewRangeInclusive, + RangeIntersect, RangeToInclusive as NewRangeToInclusive, + }; + + assert_eq!(NewRange::from(-12..387).intersect(NewRange::from(0..256)), NewRange::from(0..256)); + assert_eq!(NewRange::from(1..5).intersect(NewRangeFrom::from(3..)), NewRange::from(3..5)); + assert_eq!(NewRange::from(1..5).intersect(..3), NewRange::from(1..3)); + assert_eq!(NewRange::from(1..5).intersect(..), NewRange::from(1..5)); + + assert_eq!(NewRangeFrom::from(3..).intersect(NewRange::from(1..5)), NewRange::from(3..5)); + assert_eq!(NewRangeFrom::from(3..).intersect(NewRangeFrom::from(5..)), NewRangeFrom::from(5..)); + assert_eq!(NewRangeFrom::from(3..).intersect(..5), NewRange::from(3..5)); + assert_eq!(NewRangeFrom::from(3..).intersect(..), NewRangeFrom::from(3..)); + assert_eq!( + NewRangeFrom::from(3..).intersect(NewRangeInclusive::from(1..=5)), + NewRangeInclusive::from(3..=5), + ); + assert_eq!( + NewRangeFrom::from(3..).intersect(NewRangeToInclusive::from(..=5)), + NewRangeInclusive::from(3..=5), + ); + + assert_eq!((..5).intersect(NewRange::from(1..8)), NewRange::from(1..5)); + assert_eq!((..5).intersect(NewRangeFrom::from(3..)), NewRange::from(3..5)); + assert_eq!((..5).intersect(..3), ..3); + assert_eq!((..5).intersect(..), ..5); + + assert_eq!((..).intersect(NewRange::from(1..5)), NewRange::from(1..5)); + assert_eq!((..).intersect(NewRangeFrom::from(3..)), NewRangeFrom::from(3..)); + assert_eq!((..).intersect(..5), ..5); + assert_eq!((..).intersect(..), ..); + assert_eq!((..).intersect(NewRangeInclusive::from(1..=5)), NewRangeInclusive::from(1..=5)); + assert_eq!((..).intersect(NewRangeToInclusive::from(..=5)), NewRangeToInclusive::from(..=5)); + + assert_eq!( + NewRangeInclusive::from(1..=9).intersect(NewRangeFrom::from(3..)), + NewRangeInclusive::from(3..=9), + ); + assert_eq!(NewRangeInclusive::from(1..=9).intersect(..), NewRangeInclusive::from(1..=9)); + assert_eq!( + NewRangeInclusive::from(1..=9).intersect(NewRangeInclusive::from(3..=5)), + NewRangeInclusive::from(3..=5), + ); + assert_eq!( + NewRangeInclusive::from(1..=9).intersect(NewRangeToInclusive::from(..=5)), + NewRangeInclusive::from(1..=5), + ); + + assert_eq!( + NewRangeToInclusive::from(..=9).intersect(NewRangeFrom::from(3..)), + NewRangeInclusive::from(3..=9), + ); + assert_eq!(NewRangeToInclusive::from(..=9).intersect(..), NewRangeToInclusive::from(..=9)); + assert_eq!( + NewRangeToInclusive::from(..=9).intersect(NewRangeInclusive::from(3..=12)), + NewRangeInclusive::from(3..=9), + ); + assert_eq!( + NewRangeToInclusive::from(..=9).intersect(NewRangeToInclusive::from(..=5)), + NewRangeToInclusive::from(..=5), + ); + + // Fallback via into_bounds() for combinations without a concrete range type + assert_eq!((1..=9).into_bounds().intersect((0..10).into_bounds()), (Included(1), Included(9))); + assert_eq!( + (7..=13).into_bounds().intersect((8..13).into_bounds()), + (Included(8), Excluded(13)), + ); + assert_eq!( + (Excluded(1), Included(9)).intersect((Included(2), Excluded(9))), + (Included(2), Excluded(9)), + ); + assert_eq!( + (Unbounded::, Unbounded).intersect((Included(1), Excluded(5))), + (Included(1), Excluded(5)), + ); +} diff --git a/library/profiler_builtins/Cargo.toml b/library/profiler_builtins/Cargo.toml index 00a535544bf47..f9c34bf56ff4d 100644 --- a/library/profiler_builtins/Cargo.toml +++ b/library/profiler_builtins/Cargo.toml @@ -9,6 +9,8 @@ bench = false doc = false [dependencies] +core = { path = "../core" } +compiler_builtins = { path = "../compiler-builtins/compiler-builtins", features = ["compiler-builtins"] } [build-dependencies] # Pinned so `cargo update` bumps don't cause breakage diff --git a/library/profiler_builtins/src/lib.rs b/library/profiler_builtins/src/lib.rs index a258f7d31a191..68b6058db978c 100644 --- a/library/profiler_builtins/src/lib.rs +++ b/library/profiler_builtins/src/lib.rs @@ -1,12 +1,11 @@ // tidy-alphabetical-start #![allow(internal_features)] -#![feature(no_core)] #![feature(profiler_runtime)] #![feature(staged_api)] // tidy-alphabetical-end // Other attributes: -#![no_core] +#![no_std] #![profiler_runtime] #![unstable( feature = "profiler_runtime_lib", diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index d75107616a283..6f05f6246ad86 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -2035,16 +2035,14 @@ impl OpenOptions { /// Sets the option for the append mode. /// - /// This option, when true, means that writes will append to a file instead - /// of overwriting previous contents. - /// Note that setting `.write(true).append(true)` has the same effect as - /// setting only `.append(true)`. + /// This option, when true, means that writes will append to a file instead of overwriting + /// previous contents. The `write` setting is ignored when `append` is true, i.e., + /// `.write(true).append(true).open(...)` has the same effect as `.append(true).open(...)`. /// /// Append mode guarantees that writes will be positioned at the current end of file, /// even when there are other processes or threads appending to the same file. This is - /// unlike [seek]\([SeekFrom]::[End]\(0)) followed by `write()`, which - /// has a race between seeking and writing during which another writer can write, with - /// our `write()` overwriting their data. + /// a race-free version of [seek]\([SeekFrom]::[End]\(0)) followed by `write()`, + /// working correctly even if there are concurrent writers. /// /// Keep in mind that this does not necessarily guarantee that data appended by /// different processes or threads does not interleave. The amount of data accepted a @@ -2872,6 +2870,7 @@ impl DirEntry { /// # Examples /// /// ``` + /// # if cfg!(all(windows, skip_unsupported_miri_tests)) { return; } /// use std::fs; /// /// if let Ok(entries) = fs::read_dir(".") { @@ -2909,6 +2908,7 @@ impl DirEntry { /// # Examples /// /// ``` + /// # if cfg!(all(windows, skip_unsupported_miri_tests)) { return; } /// use std::fs; /// /// if let Ok(entries) = fs::read_dir(".") { @@ -2942,6 +2942,7 @@ impl DirEntry { /// # Examples /// /// ``` + /// # if cfg!(all(windows, skip_unsupported_miri_tests)) { return; } /// use std::fs; /// /// if let Ok(entries) = fs::read_dir(".") { diff --git a/library/std/src/os/unix/net/addr.rs b/library/std/src/os/unix/net/addr.rs index e5fcb93b88308..f4567959f0931 100644 --- a/library/std/src/os/unix/net/addr.rs +++ b/library/std/src/os/unix/net/addr.rs @@ -80,6 +80,7 @@ enum AddressKind<'a> { /// #[cfg_attr(target_family = "unix", doc = "```")] #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")] +/// # if cfg!(skip_unsupported_miri_tests) { return; } /// use std::os::unix::net::UnixListener; /// /// let socket = match UnixListener::bind("/tmp/sock") { @@ -204,6 +205,7 @@ impl SocketAddr { /// use std::os::unix::net::UnixDatagram; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let socket = UnixDatagram::unbound()?; /// let addr = socket.local_addr().expect("`UnixListener::local_addr` should not fail"); /// assert_eq!(addr.is_unnamed(), true); @@ -242,6 +244,7 @@ impl SocketAddr { /// use std::os::unix::net::UnixDatagram; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let socket = UnixDatagram::unbound()?; /// let addr = socket.local_addr().expect("`UnixListener::local_addr` should not fail"); /// assert_eq!(addr.as_pathname(), None); diff --git a/library/std/src/os/unix/net/datagram.rs b/library/std/src/os/unix/net/datagram.rs index ce5654b5576c7..0aea5115f042f 100644 --- a/library/std/src/os/unix/net/datagram.rs +++ b/library/std/src/os/unix/net/datagram.rs @@ -722,6 +722,7 @@ impl UnixDatagram { /// use std::time::Duration; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let sock = UnixDatagram::unbound()?; /// sock.set_read_timeout(Some(Duration::new(1, 0))) /// .expect("`UnixDatagram::set_read_timeout` should not fail"); @@ -769,6 +770,7 @@ impl UnixDatagram { /// use std::time::Duration; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let sock = UnixDatagram::unbound()?; /// sock.set_write_timeout(Some(Duration::new(1, 0))) /// .expect("`UnixDatagram::set_write_timeout` should not fail"); @@ -809,6 +811,7 @@ impl UnixDatagram { /// use std::time::Duration; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let sock = UnixDatagram::unbound()?; /// sock.set_read_timeout(Some(Duration::new(1, 0))) /// .expect("`UnixDatagram::set_read_timeout` should not fail"); @@ -832,6 +835,7 @@ impl UnixDatagram { /// use std::time::Duration; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let sock = UnixDatagram::unbound()?; /// sock.set_write_timeout(Some(Duration::new(1, 0))) /// .expect("`UnixDatagram::set_write_timeout` should not fail"); @@ -854,6 +858,7 @@ impl UnixDatagram { /// use std::os::unix::net::UnixDatagram; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let sock = UnixDatagram::unbound()?; /// sock.set_nonblocking(true).expect("`UnixDatagram::set_nonblocking` should not fail"); /// Ok(()) diff --git a/library/std/src/os/unix/process.rs b/library/std/src/os/unix/process.rs index 1aa6076f3a7ed..f555e5e686ae2 100644 --- a/library/std/src/os/unix/process.rs +++ b/library/std/src/os/unix/process.rs @@ -818,6 +818,7 @@ impl From for process::ChildStderr { /// #[cfg_attr(target_family = "unix", doc = "```")] #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")] +/// # if cfg!(skip_unsupported_miri_tests) { return; } /// use std::os::unix::process; /// let parent = process::parent_id(); /// println!("The parent process has ID {}", parent); diff --git a/library/std/src/os/windows/process.rs b/library/std/src/os/windows/process.rs index 422e5f172229d..6be974443ff68 100644 --- a/library/std/src/os/windows/process.rs +++ b/library/std/src/os/windows/process.rs @@ -334,6 +334,7 @@ pub impl(self) trait CommandExt { #[cfg_attr(windows, doc = "```")] #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_process_extensions_raw_attribute)] + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// use std::os::windows::io::AsRawHandle; /// use std::os::windows::process::{CommandExt, ProcThreadAttributeList}; /// use std::process::Command; @@ -614,6 +615,7 @@ impl<'a> ProcThreadAttributeListBuilder<'a> { #[cfg_attr(all(windows, target_vendor = "win7"), doc = "```no_run")] #[cfg_attr(all(windows, not(target_vendor = "win7")), doc = "```")] /// #![feature(windows_process_extensions_raw_attribute)] + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// use std::ffi::c_void; /// use std::os::windows::process::{CommandExt, ProcThreadAttributeList}; /// use std::os::windows::raw::HANDLE; diff --git a/library/std/src/process.rs b/library/std/src/process.rs index fb3b72607e4d8..5bb8e3c73ec4c 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -550,7 +550,7 @@ impl fmt::Debug for ChildStderr { /// to be changed (for example, by adding arguments) prior to spawning: /// /// ``` -/// # if cfg!(not(all(target_vendor = "apple", not(target_os = "macos")))) { +/// # if cfg!(all(not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests))) { /// use std::process::Command; /// /// let output = if cfg!(target_os = "windows") { @@ -1249,6 +1249,7 @@ impl Command { /// # Examples /// /// ``` + /// # if cfg!(all(windows, skip_unsupported_miri_tests)) { return; } /// use std::ffi::OsStr; /// use std::process::Command; /// @@ -1283,6 +1284,7 @@ impl Command { /// /// ``` /// #![feature(command_resolved_envs)] + /// # if cfg!(all(windows, skip_unsupported_miri_tests)) { return; } /// use std::process::Command; /// use std::ffi::{OsString, OsStr}; /// use std::env; @@ -1509,7 +1511,7 @@ impl Output { /// ``` /// # #![allow(unused_features)] /// #![feature(exit_status_error)] - /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos")))))] { + /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests)))] { /// use std::process::Command; /// assert!(Command::new("false").output().unwrap().exit_ok().is_err()); /// # } @@ -1856,7 +1858,7 @@ impl From for Stdio { /// # Ok(()) /// # } /// # - /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) { + /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests))) { /// # test().unwrap(); /// # } /// ``` @@ -1885,7 +1887,7 @@ impl From for Stdio { /// # Ok(()) /// # } /// # - /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) { + /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests))) { /// # test().unwrap(); /// # } /// ``` @@ -1957,7 +1959,7 @@ impl ExitStatus { /// /// ``` /// #![feature(exit_status_error)] - /// # if cfg!(all(unix, not(all(target_vendor = "apple", not(target_os = "macos"))))) { + /// # if cfg!(all(unix, not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests))) { /// use std::process::Command; /// /// let status = Command::new("ls") @@ -2060,7 +2062,7 @@ impl fmt::Display for ExitStatus { /// /// ``` /// #![feature(exit_status_error)] -/// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) { +/// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests))) { /// use std::process::{Command, ExitStatusError}; /// /// fn run(cmd: &str) -> Result<(), ExitStatusError> { @@ -2104,7 +2106,7 @@ impl ExitStatusError { /// /// ``` /// #![feature(exit_status_error)] - /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos")))))] { + /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests)))] { /// use std::process::Command; /// /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err(); @@ -2129,7 +2131,7 @@ impl ExitStatusError { /// ``` /// #![feature(exit_status_error)] /// - /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) { + /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests))) { /// use std::num::NonZero; /// use std::process::Command; /// diff --git a/library/std/src/sys/alloc/windows.rs b/library/std/src/sys/alloc/windows.rs index a62a634857d1e..b80728956b6f3 100644 --- a/library/std/src/sys/alloc/windows.rs +++ b/library/std/src/sys/alloc/windows.rs @@ -192,7 +192,11 @@ pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) { // SAFETY: Because of the contract of `System`, `ptr` is guaranteed to be non-null // and have a header readable directly before it. - unsafe { ptr::read((ptr as *mut Header).sub(1)).0 } + let block_ptr = unsafe { ptr::read((ptr as *mut Header).sub(1)).0 }; + // Always deallocate using the provenance that was passed to us, not what we stored in + // the header. The passed-in provenance may be protected, for example because it is from + // a Box argument to mem::drop. + ptr.with_addr(block_ptr.addr()) } }; diff --git a/src/bootstrap/mk/Makefile.in b/src/bootstrap/mk/Makefile.in index 07412657f8687..a4e38ce894a9f 100644 --- a/src/bootstrap/mk/Makefile.in +++ b/src/bootstrap/mk/Makefile.in @@ -80,8 +80,7 @@ check-aux: $(BOOTSTRAP) miri --stage 2 \ library/std \ $(BOOTSTRAP_ARGS) \ - --target x86_64-unknown-linux-gnu,aarch64-apple-darwin,i686-pc-windows-msvc \ - --tests # skip all doctests, they are not using skip_unsupported_miri_tests + --target x86_64-unknown-linux-gnu,aarch64-apple-darwin,i686-pc-windows-msvc dist: $(Q)$(BOOTSTRAP) dist $(BOOTSTRAP_ARGS) distcheck: diff --git a/src/doc/unstable-book/src/language-features/asm-nonnull-inputs.md b/src/doc/unstable-book/src/language-features/asm-nonnull-inputs.md new file mode 100644 index 0000000000000..ebe60cdf17baa --- /dev/null +++ b/src/doc/unstable-book/src/language-features/asm-nonnull-inputs.md @@ -0,0 +1,25 @@ +# `asm_nonnull_inputs` + +The tracking issue for this feature is: [#166132] + +[#166132]: https://github.com/rust-lang/rust/issues/166132 + +------------------------ + +This feature allows thin `NonNull` pointers to be used as input +operands in inline assembly. + +Example: +```rust,ignore (partial-example, x86-only) +let mut x = 1; +let p = core::ptr::NonNull::from_mut(&mut x); + +unsafe { + core::arch::asm!( + "mov dword ptr [{}], 2", + in(reg) p, + ) +}; + +assert_eq!(x, 2); +``` diff --git a/src/tools/tidy/src/walk.rs b/src/tools/tidy/src/walk.rs index 701450db5fb50..a1bccb3797c8f 100644 --- a/src/tools/tidy/src/walk.rs +++ b/src/tools/tidy/src/walk.rs @@ -64,6 +64,8 @@ pub fn walk_many( contents.clear(); let mut file = t!(File::open(entry.path()), entry.path()); t!(file.read_to_end(&mut contents), entry.path()); + drop(file); // Drop it early so that tempfiles can persist to this file on Windows + let contents_str = match std::str::from_utf8(&contents) { Ok(s) => s, Err(_) => return, // skip this file diff --git a/tests/assembly-llvm/asm/aarch64-types.rs b/tests/assembly-llvm/asm/aarch64-types.rs index da625b1211602..1c516a6541777 100644 --- a/tests/assembly-llvm/asm/aarch64-types.rs +++ b/tests/assembly-llvm/asm/aarch64-types.rs @@ -9,7 +9,7 @@ //@ [arm64ec] needs-llvm-components: aarch64 //@ compile-flags: -Zmerge-functions=disabled -#![feature(asm_experimental_reg, no_core, f16, f128, rustc_attrs)] +#![feature(asm_experimental_reg, asm_nonnull_inputs, no_core, f16, f128, rustc_attrs)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -19,6 +19,7 @@ use minicore::simd::*; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; #[cfg(target_feature = "sve")] #[rustc_scalable_vector(16)] @@ -113,11 +114,14 @@ pub unsafe fn issue_75761() { macro_rules! check { ($func:ident $ty:ident $class:ident $mov:literal $modifier:literal) => { - // FIXME(f128): Change back to `$func(x: $ty) -> $ty` once arm64ec can pass and return - // `f128` without LLVM erroring. + check!($func $ty:$ty $class $mov $modifier); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident $mov:literal $modifier:literal) => { + // FIXME(f128): Change back to `$func(x: $in_ty) -> $out_ty` once arm64ec + // can pass and return `f128` without LLVM erroring. // LLVM issue: #[no_mangle] - pub unsafe fn $func(inp: &$ty, out: &mut $ty) { + pub unsafe fn $func(inp: &$in_ty, out: &mut $out_ty) { let x = *inp; let y; asm!( @@ -151,9 +155,12 @@ macro_rules! check_sve { macro_rules! check_reg { ($func:ident $ty:ident $reg:tt $mov:literal) => { + check_reg!($func $ty:$ty $reg $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $reg:tt $mov:literal) => { // FIXME(f128): See FIXME in `check!` #[no_mangle] - pub unsafe fn $func(inp: &$ty, out: &mut $ty) { + pub unsafe fn $func(inp: &$in_ty, out: &mut $out_ty) { let x = *inp; let y; asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); @@ -229,6 +236,12 @@ check!(reg_f64 f64 reg "mov" ""); // CHECK: //NO_APP check!(reg_ptr ptr reg "mov" ""); +// CHECK-LABEL: {{("#)?}}reg_nonnull{{"?}} +// CHECK: //APP +// CHECK: mov x{{[0-9]+}}, x{{[0-9]+}} +// CHECK: //NO_APP +check!(reg_nonnull nonnull:ptr reg "mov" ""); + // CHECK-LABEL: {{("#)?}}vreg_i8{{"?}} // CHECK: //APP // CHECK: fmov s{{[0-9]+}}, s{{[0-9]+}} @@ -283,6 +296,12 @@ check!(vreg_f128 f128 vreg "fmov" "s"); // CHECK: //NO_APP check!(vreg_ptr ptr vreg "fmov" "s"); +// CHECK-LABEL: {{("#)?}}vreg_nonnull{{"?}} +// CHECK: //APP +// CHECK: fmov s{{[0-9]+}}, s{{[0-9]+}} +// CHECK: //NO_APP +check!(vreg_nonnull nonnull:ptr vreg "fmov" "s"); + // CHECK-LABEL: {{("#)?}}vreg_i8x8{{"?}} // CHECK: //APP // CHECK: fmov s{{[0-9]+}}, s{{[0-9]+}} @@ -415,6 +434,12 @@ check!(vreg_low16_f128 f128 vreg_low16 "fmov" "s"); // CHECK: //NO_APP check!(vreg_low16_ptr ptr vreg_low16 "fmov" "s"); +// CHECK-LABEL: {{("#)?}}vreg_low16_nonnull{{"?}} +// CHECK: //APP +// CHECK: fmov s{{[0-9]+}}, s{{[0-9]+}} +// CHECK: //NO_APP +check!(vreg_low16_nonnull nonnull:ptr vreg_low16 "fmov" "s"); + // CHECK-LABEL: {{("#)?}}vreg_low16_i8x8{{"?}} // CHECK: //APP // CHECK: fmov s{{[0-9]+}}, s{{[0-9]+}} @@ -637,6 +662,12 @@ check_reg!(x0_f64 f64 "x0" "mov"); // CHECK: //NO_APP check_reg!(x0_ptr ptr "x0" "mov"); +// CHECK-LABEL: {{("#)?}}x0_nonnull{{"?}} +// CHECK: //APP +// CHECK: mov x{{[0-9]+}}, x{{[0-9]+}} +// CHECK: //NO_APP +check_reg!(x0_nonnull nonnull:ptr "x0" "mov"); + // CHECK-LABEL: {{("#)?}}v0_i8{{"?}} // CHECK: //APP // CHECK: fmov s0, s0 @@ -747,6 +778,12 @@ pub unsafe fn p0_bool(inp: &svbool_t, pred: &svbool_t) -> svbool_t { // CHECK: //NO_APP check_reg!(v0_ptr ptr "s0" "fmov"); +// CHECK-LABEL: {{("#)?}}v0_nonnull{{"?}} +// CHECK: //APP +// CHECK: fmov s0, s0 +// CHECK: //NO_APP +check_reg!(v0_nonnull nonnull:ptr "s0" "fmov"); + // CHECK-LABEL: {{("#)?}}v0_i8x8{{"?}} // CHECK: //APP // CHECK: fmov s0, s0 diff --git a/tests/assembly-llvm/asm/arm-types.rs b/tests/assembly-llvm/asm/arm-types.rs index 4cf945c5959b6..16e27049ac6b9 100644 --- a/tests/assembly-llvm/asm/arm-types.rs +++ b/tests/assembly-llvm/asm/arm-types.rs @@ -9,7 +9,7 @@ //@[neon] filecheck-flags: --check-prefix d32 //@ needs-llvm-components: arm -#![feature(no_core, f16)] +#![feature(asm_nonnull_inputs, no_core, f16)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -19,6 +19,7 @@ use minicore::simd::*; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; extern "C" { fn extern_func(); @@ -54,8 +55,11 @@ pub unsafe fn issue_82052() { macro_rules! check { ($func:ident $ty:ident $class:ident $mov:literal) => { + check!($func $ty:$ty $class $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " {}, {}"), out($class) y, in($class) x); y @@ -65,8 +69,11 @@ macro_rules! check { macro_rules! check_reg { ($func:ident $ty:ident $reg:tt $mov:literal) => { + check_reg!($func $ty:$ty $reg $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $reg:tt $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); y @@ -110,6 +117,12 @@ check!(reg_f32 f32 reg "mov"); // CHECK: @NO_APP check!(reg_ptr ptr reg "mov"); +// CHECK-LABEL: reg_nonnull: +// CHECK: @APP +// CHECK: mov {{[a-z0-9]+}}, {{[a-z0-9]+}} +// CHECK: @NO_APP +check!(reg_nonnull nonnull:ptr reg "mov"); + // CHECK-LABEL: sreg_i32: // CHECK: @APP // CHECK: vmov.f32 s{{[0-9]+}}, s{{[0-9]+}} @@ -134,6 +147,12 @@ check!(sreg_f32 f32 sreg "vmov.f32"); // CHECK: @NO_APP check!(sreg_ptr ptr sreg "vmov.f32"); +// CHECK-LABEL: sreg_nonnull: +// CHECK: @APP +// CHECK: vmov.f32 s{{[0-9]+}}, s{{[0-9]+}} +// CHECK: @NO_APP +check!(sreg_nonnull nonnull:ptr sreg "vmov.f32"); + // CHECK-LABEL: sreg_low16_i32: // CHECK: @APP // CHECK: vmov.f32 s{{[0-9]+}}, s{{[0-9]+}} @@ -478,6 +497,12 @@ check_reg!(r0_f32 f32 "r0" "mov"); // CHECK: @NO_APP check_reg!(r0_ptr ptr "r0" "mov"); +// CHECK-LABEL: r0_nonnull: +// CHECK: @APP +// CHECK: mov r0, r0 +// CHECK: @NO_APP +check_reg!(r0_nonnull nonnull:ptr "r0" "mov"); + // CHECK-LABEL: s0_i32: // CHECK: @APP // CHECK: vmov.f32 s0, s0 @@ -502,6 +527,12 @@ check_reg!(s0_f32 f32 "s0" "vmov.f32"); // CHECK: @NO_APP check_reg!(s0_ptr ptr "s0" "vmov.f32"); +// CHECK-LABEL: s0_nonnull: +// CHECK: @APP +// CHECK: vmov.f32 s0, s0 +// CHECK: @NO_APP +check_reg!(s0_nonnull nonnull:ptr "s0" "vmov.f32"); + // FIXME(#126797): "d0" should work with `i64` and `f64` even when `d32` is disabled. // d32-LABEL: d0_i64: // d32: @APP diff --git a/tests/assembly-llvm/asm/hexagon-types.rs b/tests/assembly-llvm/asm/hexagon-types.rs index 829696153293c..2a083758f9673 100644 --- a/tests/assembly-llvm/asm/hexagon-types.rs +++ b/tests/assembly-llvm/asm/hexagon-types.rs @@ -5,7 +5,7 @@ //@ compile-flags: -Zmerge-functions=disabled //@ needs-llvm-components: hexagon -#![feature(no_core, asm_experimental_arch)] +#![feature(asm_nonnull_inputs, no_core, asm_experimental_arch)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -15,6 +15,7 @@ use minicore::simd::*; use minicore::*; type ptr = *const i32; +type nonnull = NonNull; type i32x32 = Simd; // 1024-bit HVX vector (128B mode) type i32x64 = Simd; // 2048-bit HVX vector pair (128B mode) @@ -26,8 +27,11 @@ extern "C" { macro_rules! check { ($func:ident $ty:ident $class:ident) => { + check!($func $ty:$ty $class); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!("{} = {}", out($class) y, in($class) x); y @@ -37,8 +41,11 @@ macro_rules! check { macro_rules! check_reg { ($func:ident $ty:ident $reg:tt) => { + check_reg!($func $ty:$ty $reg); + }; + ($func:ident $in_ty:ident:$out_ty:ident $reg:tt) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($reg, " = ", $reg), lateout($reg) y, in($reg) x); y @@ -89,6 +96,12 @@ pub unsafe fn packet() { // CHECK: InlineAsm End check!(reg_ptr ptr reg); +// CHECK-LABEL: reg_nonnull: +// CHECK: InlineAsm Start +// CHECK: r{{[0-9]+}} = r{{[0-9]+}} +// CHECK: InlineAsm End +check!(reg_nonnull nonnull:ptr reg); + // CHECK-LABEL: reg_f32: // CHECK: InlineAsm Start // CHECK: r{{[0-9]+}} = r{{[0-9]+}} @@ -119,6 +132,12 @@ check!(reg_i16 i16 reg); // CHECK: InlineAsm End check_reg!(r0_ptr ptr "r0"); +// CHECK-LABEL: r0_nonnull: +// CHECK: InlineAsm Start +// CHECK: r0 = r0 +// CHECK: InlineAsm End +check_reg!(r0_nonnull nonnull:ptr "r0"); + // CHECK-LABEL: r0_f32: // CHECK: InlineAsm Start // CHECK: r0 = r0 diff --git a/tests/assembly-llvm/asm/loongarch-type.rs b/tests/assembly-llvm/asm/loongarch-type.rs index 124d82c5d5d6c..27c663403e011 100644 --- a/tests/assembly-llvm/asm/loongarch-type.rs +++ b/tests/assembly-llvm/asm/loongarch-type.rs @@ -14,7 +14,7 @@ //@ compile-flags: -Zmerge-functions=disabled -#![feature(no_core, f16)] +#![feature(asm_nonnull_inputs, no_core, f16)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -23,6 +23,7 @@ extern crate minicore; use minicore::*; type ptr = *const i32; +type nonnull = NonNull; extern "C" { fn extern_func(); @@ -58,23 +59,33 @@ pub unsafe fn sym_static() { asm!("la.got $r12, {}", sym extern_static); } -macro_rules! check { ($func:ident, $ty:ty, $class:ident, $mov:literal) => { - #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { - let y; - asm!(concat!($mov," {}, {}"), out($class) y, in($class) x); - y - } -};} - -macro_rules! check_reg { ($func:ident, $ty:ty, $reg:tt, $mov:literal) => { - #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { - let y; - asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); - y - } -};} +macro_rules! check { + ($func:ident, $ty:ty, $class:ident, $mov:literal) => { + check!($func, $ty:$ty, $class, $mov); + }; + ($func:ident, $in_ty:ty:$out_ty:ty, $class:ident, $mov:literal) => { + #[no_mangle] + pub unsafe fn $func(x: $in_ty) -> $out_ty { + let y; + asm!(concat!($mov," {}, {}"), out($class) y, in($class) x); + y + } + }; +} + +macro_rules! check_reg { + ($func:ident, $ty:ty, $reg:tt, $mov:literal) => { + check_reg!($func, $ty:$ty, $reg, $mov); + }; + ($func:ident, $in_ty:ty:$out_ty:ty, $reg:tt, $mov:literal) => { + #[no_mangle] + pub unsafe fn $func(x: $in_ty) -> $out_ty { + let y; + asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); + y + } + }; +} // CHECK-LABEL: reg_i8: // CHECK: #APP @@ -126,6 +137,12 @@ check!(reg_f64, f64, reg, "move"); // CHECK: #NO_APP check!(reg_ptr, ptr, reg, "move"); +// CHECK-LABEL: reg_nonnull: +// CHECK: #APP +// CHECK: move ${{[a-z0-9]+}}, ${{[a-z0-9]+}} +// CHECK: #NO_APP +check!(reg_nonnull, nonnull:ptr, reg, "move"); + // CHECK-LABEL: freg_f16: // CHECK: #APP // CHECK: fmov.s $f{{[a-z0-9]+}}, $f{{[a-z0-9]+}} @@ -194,6 +211,12 @@ check_reg!(r4_f64, f64, "$r4", "move"); // CHECK: #NO_APP check_reg!(r4_ptr, ptr, "$r4", "move"); +// CHECK-LABEL: r4_nonnull: +// CHECK: #APP +// CHECK: move $a0, $a0 +// CHECK: #NO_APP +check_reg!(r4_nonnull, nonnull:ptr, "$r4", "move"); + // CHECK-LABEL: f0_f16: // CHECK: #APP // CHECK: fmov.s $f{{[a-z0-9]+}}, $f{{[a-z0-9]+}} diff --git a/tests/assembly-llvm/asm/mips-types.rs b/tests/assembly-llvm/asm/mips-types.rs index ea46386df133d..fc879354a6b77 100644 --- a/tests/assembly-llvm/asm/mips-types.rs +++ b/tests/assembly-llvm/asm/mips-types.rs @@ -66,7 +66,7 @@ //@ min-llvm-version: 23 #![deny(unexpected_cfgs)] -#![feature(no_core, asm_experimental_arch, f16)] +#![feature(asm_nonnull_inputs, no_core, asm_experimental_arch, f16)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types, unused)] @@ -96,29 +96,40 @@ compile_error!("mips64r6 cfg mismatch"); compile_error!("msa cfg mismatch"); type ptr = *const i32; +type nonnull = NonNull; extern "C" { fn extern_func(); static extern_static: u8; } -macro_rules! check { ($func:ident, $ty:ty, $class:ident, $mov:literal) => { - #[unsafe(no_mangle)] - pub unsafe fn $func(x: $ty) -> $ty { - let y; - asm!(concat!($mov," {}, {}"), out($class) y, in($class) x); - y - } -};} - -macro_rules! check_reg { ($func:ident, $ty:ty, $reg:tt, $mov:literal) => { - #[unsafe(no_mangle)] - pub unsafe fn $func(x: $ty) -> $ty { - let y; - asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); - y - } -};} +macro_rules! check { + ($func:ident, $ty:ty, $class:ident, $mov:literal) => { + check!($func, $ty:$ty, $class, $mov); + }; + ($func:ident, $in_ty:ty:$out_ty:ty, $class:ident, $mov:literal) => { + #[unsafe(no_mangle)] + pub unsafe fn $func(x: $in_ty) -> $out_ty { + let y; + asm!(concat!($mov," {}, {}"), out($class) y, in($class) x); + y + } + }; +} + +macro_rules! check_reg { + ($func:ident, $ty:ty, $reg:tt, $mov:literal) => { + check_reg!($func, $ty:$ty, $reg, $mov); + }; + ($func:ident, $in_ty:ty:$out_ty:ty, $reg:tt, $mov:literal) => { + #[unsafe(no_mangle)] + pub unsafe fn $func(x: $in_ty) -> $out_ty { + let y; + asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); + y + } + }; +} // mips32-LABEL: sym_static_32: // mips32: #APP @@ -232,6 +243,12 @@ check_reg!(f0_f64, f64, "$f0", "mov.d"); // CHECK: #NO_APP check!(reg_ptr, ptr, reg, "move"); +// CHECK-LABEL: reg_nonnull: +// CHECK: #APP +// CHECK: move ${{[0-9]+}}, ${{[0-9]+}} +// CHECK: #NO_APP +check!(reg_nonnull, nonnull:ptr, reg, "move"); + // CHECK-LABEL: reg_i32: // CHECK: #APP // CHECK: move ${{[0-9]+}}, ${{[0-9]+}} @@ -288,6 +305,12 @@ check!(reg_i64, i64, reg, "move"); // CHECK: #NO_APP check_reg!(r8_ptr, ptr, "$8", "move"); +// CHECK-LABEL: r8_nonnull: +// CHECK: #APP +// CHECK: move $8, $8 +// CHECK: #NO_APP +check_reg!(r8_nonnull, nonnull:ptr, "$8", "move"); + // CHECK-LABEL: r8_i32: // CHECK: #APP // CHECK: move $8, $8 diff --git a/tests/assembly-llvm/asm/nvptx-types.rs b/tests/assembly-llvm/asm/nvptx-types.rs index 15c4dabbfecee..d615beb351d96 100644 --- a/tests/assembly-llvm/asm/nvptx-types.rs +++ b/tests/assembly-llvm/asm/nvptx-types.rs @@ -3,7 +3,7 @@ //@ compile-flags: --target nvptx64-nvidia-cuda //@ needs-llvm-components: nvptx -#![feature(no_core, asm_experimental_arch, f16)] +#![feature(asm_nonnull_inputs, no_core, asm_experimental_arch, f16)] #![crate_type = "rlib"] #![no_core] @@ -11,6 +11,7 @@ extern crate minicore; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; // NVPTX does not support static variables #[no_mangle] @@ -27,8 +28,11 @@ pub unsafe fn sym_fn() { macro_rules! check { ($func:ident $ty:ident $class:ident $mov:literal) => { + check!($func $ty:$ty $class $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " {}, {};"), out($class) y, in($class) x); y @@ -131,3 +135,9 @@ check!(reg64_f64 f64 reg64 "mov.b64"); // CHECK: mov.b64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}}; // CHECK: // end inline asm check!(reg64_ptr ptr reg64 "mov.b64"); + +// CHECK-LABEL: .visible .func (.param .b64 func_retval0) reg64_nonnull +// CHECK: // begin inline asm +// CHECK: mov.b64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}}; +// CHECK: // end inline asm +check!(reg64_nonnull nonnull:ptr reg64 "mov.b64"); diff --git a/tests/assembly-llvm/asm/riscv-types.rs b/tests/assembly-llvm/asm/riscv-types.rs index 3ebfbaee43198..ff3620997d0fb 100644 --- a/tests/assembly-llvm/asm/riscv-types.rs +++ b/tests/assembly-llvm/asm/riscv-types.rs @@ -30,7 +30,7 @@ //@ compile-flags: -C target-feature=+d //@ compile-flags: -Zmerge-functions=disabled -#![feature(no_core, f16)] +#![feature(asm_nonnull_inputs, no_core, f16)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register)] @@ -39,6 +39,7 @@ extern crate minicore; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; extern "C" { fn extern_func(); @@ -66,8 +67,11 @@ pub unsafe fn sym_static() { macro_rules! check { ($func:ident $ty:ident $class:ident $mov:literal) => { + check!($func $ty:$ty $class $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " {}, {}"), out($class) y, in($class) x); y @@ -77,8 +81,11 @@ macro_rules! check { macro_rules! check_reg { ($func:ident $ty:ident $reg:tt $mov:literal) => { + check_reg!($func $ty:$ty $reg $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $reg:tt $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); y @@ -136,6 +143,12 @@ check!(reg_f64 f64 reg "mv"); // CHECK: #NO_APP check!(reg_ptr ptr reg "mv"); +// CHECK-LABEL: reg_nonnull: +// CHECK: #APP +// CHECK: mv {{[a-z0-9]+}}, {{[a-z0-9]+}} +// CHECK: #NO_APP +check!(reg_nonnull nonnull:ptr reg "mv"); + // CHECK-LABEL: freg_f16: // zfhmin-NOT: or // CHECK: #APP @@ -206,6 +219,12 @@ check_reg!(a0_f64 f64 "a0" "mv"); // CHECK: #NO_APP check_reg!(a0_ptr ptr "a0" "mv"); +// CHECK-LABEL: a0_nonnull: +// CHECK: #APP +// CHECK: mv a0, a0 +// CHECK: #NO_APP +check_reg!(a0_nonnull nonnull:ptr "a0" "mv"); + // CHECK-LABEL: fa0_f16: // zfhmin-NOT: or // CHECK: #APP diff --git a/tests/assembly-llvm/asm/s390x-types.rs b/tests/assembly-llvm/asm/s390x-types.rs index f649a6babdc27..f2f3e539fb2e7 100644 --- a/tests/assembly-llvm/asm/s390x-types.rs +++ b/tests/assembly-llvm/asm/s390x-types.rs @@ -7,7 +7,7 @@ //@[s390x_vector] needs-llvm-components: systemz //@ compile-flags: -Zmerge-functions=disabled -#![feature(no_core, f16, f128)] +#![feature(asm_nonnull_inputs, no_core, f16, f128)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -17,20 +17,26 @@ use minicore::simd::*; use minicore::*; type ptr = *const i32; +type nonnull = NonNull; extern "C" { fn extern_func(); static extern_static: u8; } -macro_rules! check { ($func:ident, $ty:ty, $class:ident, $mov:literal) => { - #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { - let y; - asm!(concat!($mov," {}, {}"), out($class) y, in($class) x); - y - } -};} +macro_rules! check { + ($func:ident, $ty:ty, $class:ident, $mov:literal) => { + check!($func, $ty:$ty, $class, $mov); + }; + ($func:ident, $in_ty:ty:$out_ty:ty, $class:ident, $mov:literal) => { + #[no_mangle] + pub unsafe fn $func(x: $in_ty) -> $out_ty { + let y; + asm!(concat!($mov," {}, {}"), out($class) y, in($class) x); + y + } + }; +} macro_rules! check_reg { ($func:ident, $ty:ty, $reg:tt, $mov:literal) => { #[no_mangle] @@ -131,6 +137,12 @@ check!(reg_f64, f64, freg, "ldr"); // CHECK: #NO_APP check!(reg_ptr, ptr, reg, "lgr"); +// CHECK-LABEL: reg_nonnull: +// CHECK: #APP +// CHECK: lgr %r{{[0-9]+}}, %r{{[0-9]+}} +// CHECK: #NO_APP +check!(reg_nonnull, nonnull:ptr, reg, "lgr"); + // s390x_vector-LABEL: vreg_i8x16: // s390x_vector: #APP // s390x_vector: vlr %v{{[0-9]+}}, %v{{[0-9]+}} diff --git a/tests/assembly-llvm/asm/sparc-types.rs b/tests/assembly-llvm/asm/sparc-types.rs index 9fabd8dcdd09e..9763d543ab675 100644 --- a/tests/assembly-llvm/asm/sparc-types.rs +++ b/tests/assembly-llvm/asm/sparc-types.rs @@ -13,7 +13,7 @@ //@ compile-flags: --check-cfg=cfg(v9) #![deny(unexpected_cfgs)] -#![feature(no_core, asm_experimental_arch, f128)] +#![feature(no_core, asm_experimental_arch, asm_nonnull_inputs, f128)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -26,20 +26,26 @@ extern crate minicore; use minicore::*; type ptr = *const i32; +type nonnull = NonNull; extern "C" { fn extern_func(); static extern_static: u8; } -macro_rules! check { ($func:ident, $ty:ty, $class:ident, $mov:literal) => { - #[unsafe(no_mangle)] - pub unsafe fn $func(x: $ty) -> $ty { - let y; - asm!(concat!($mov," {}, {}"), in($class) x, out($class) y); - y - } -};} +macro_rules! check { + ($func:ident, $ty:ty, $class:ident, $mov:literal) => { + check!($func, $ty:$ty, $class, $mov); + }; + ($func:ident, $in_ty:ty:$out_ty:ty, $class:ident, $mov:literal) => { + #[unsafe(no_mangle)] + pub unsafe fn $func(x: $in_ty) -> $out_ty { + let y; + asm!(concat!($mov," {}, {}"), in($class) x, out($class) y); + y + } + }; +} macro_rules! check_reg { ($func:ident, $ty:ty, $reg:tt, $mov:literal) => { @@ -110,6 +116,12 @@ check!(reg_i64, i64, reg, "mov"); // CHECK-NEXT: !NO_APP check!(reg_ptr, ptr, reg, "mov"); +// CHECK-LABEL: reg_nonnull: +// CHECK: !APP +// CHECK-NEXT: mov %{{[goli]}}{{[0-9]+}}, %{{[goli]}}{{[0-9]+}} +// CHECK-NEXT: !NO_APP +check!(reg_nonnull, nonnull:ptr, reg, "mov"); + // CHECK-LABEL: o0_i8: // CHECK: !APP // CHECK-NEXT: mov %o0, %o0 diff --git a/tests/assembly-llvm/asm/wasm-types.rs b/tests/assembly-llvm/asm/wasm-types.rs index b00a84acf50c5..2e452534fa37a 100644 --- a/tests/assembly-llvm/asm/wasm-types.rs +++ b/tests/assembly-llvm/asm/wasm-types.rs @@ -3,7 +3,7 @@ //@ compile-flags: --target wasm32-unknown-unknown //@ needs-llvm-components: webassembly -#![feature(no_core, asm_experimental_arch)] +#![feature(no_core, asm_experimental_arch, asm_nonnull_inputs)] #![crate_type = "rlib"] #![no_core] @@ -11,6 +11,7 @@ extern crate minicore; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; extern "C" { fn extern_func(); @@ -41,8 +42,11 @@ pub unsafe fn sym_static() { macro_rules! check { ($func:ident $ty:ident $instr:literal) => { + check!($func $ty:$ty $instr); + }; + ($func:ident $in_ty:ident:$out_ty:ident $instr:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!("local.get {}\n", $instr, "\nlocal.set {}"), in(local) x, out(local) y); y @@ -129,3 +133,11 @@ check!(f64_f64 f64 "f64.abs"); // CHECK: local.set {{[0-9]}} // CHECK: #NO_APP check!(i32_ptr ptr "i32.eqz"); + +// CHECK-LABEL: i32_nonnull +// CHECK: #APP +// CHECK: local.get {{[0-9]}} +// CHECK: i32.eqz +// CHECK: local.set {{[0-9]}} +// CHECK: #NO_APP +check!(i32_nonnull nonnull:ptr "i32.eqz"); diff --git a/tests/assembly-llvm/asm/x86-types.rs b/tests/assembly-llvm/asm/x86-types.rs index e9511f230d0ea..fb8961e35edea 100644 --- a/tests/assembly-llvm/asm/x86-types.rs +++ b/tests/assembly-llvm/asm/x86-types.rs @@ -9,7 +9,7 @@ //@ compile-flags: -C target-feature=+avx512bw //@ compile-flags: -Zmerge-functions=disabled -#![feature(no_core, f16, f128, asm_const_ptr)] +#![feature(no_core, f16, f128, asm_const_ptr, asm_nonnull_inputs)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -19,6 +19,7 @@ use minicore::simd::*; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; extern "C" { fn extern_func(); @@ -54,8 +55,11 @@ pub unsafe fn const_ptr() { macro_rules! check { ($func:ident $ty:ident $class:ident $mov:literal) => { + check!($func $ty:$ty $class $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " {}, {}"), lateout($class) y, in($class) x); y @@ -65,8 +69,11 @@ macro_rules! check { macro_rules! check_reg { ($func:ident $ty:ident $reg:tt $mov:literal) => { + check_reg!($func $ty:$ty $reg $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $reg:tt $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); y @@ -123,6 +130,13 @@ check!(reg_f64 f64 reg "mov"); // CHECK: #NO_APP check!(reg_ptr ptr reg "mov"); +// CHECK-LABEL: reg_nonnull: +// CHECK: #APP +// x86_64: mov r{{[a-z0-9]+}}, r{{[a-z0-9]+}} +// i686: mov e{{[a-z0-9]+}}, e{{[a-z0-9]+}} +// CHECK: #NO_APP +check!(reg_nonnull nonnull:ptr reg "mov"); + // CHECK-LABEL: reg_abcd_i16: // CHECK: #APP // x86_64: mov r{{[a-z0-9]+}}, r{{[a-z0-9]+}} @@ -172,6 +186,13 @@ check!(reg_abcd_f64 f64 reg_abcd "mov"); // CHECK: #NO_APP check!(reg_abcd_ptr ptr reg_abcd "mov"); +// CHECK-LABEL: reg_abcd_nonnull: +// CHECK: #APP +// x86_64: mov r{{[a-z0-9]+}}, r{{[a-z0-9]+}} +// i686: mov e{{[a-z0-9]+}}, e{{[a-z0-9]+}} +// CHECK: #NO_APP +check!(reg_abcd_nonnull nonnull:ptr reg_abcd "mov"); + // CHECK-LABEL: reg_byte: // CHECK: #APP // CHECK: mov {{[a-z0-9]+}}, {{[a-z0-9]+}} @@ -220,6 +241,12 @@ check!(xmm_reg_f128 f128 xmm_reg "movaps"); // CHECK: #NO_APP check!(xmm_reg_ptr ptr xmm_reg "movaps"); +// CHECK-LABEL: xmm_reg_nonnull: +// CHECK: #APP +// CHECK: movaps xmm{{[0-9]+}}, xmm{{[0-9]+}} +// CHECK: #NO_APP +check!(xmm_reg_nonnull nonnull:ptr xmm_reg "movaps"); + // CHECK-LABEL: xmm_reg_i8x16: // CHECK: #APP // CHECK: movaps xmm{{[0-9]+}}, xmm{{[0-9]+}} @@ -304,6 +331,12 @@ check!(ymm_reg_f128 f128 ymm_reg "vmovaps"); // CHECK: #NO_APP check!(ymm_reg_ptr ptr ymm_reg "vmovaps"); +// CHECK-LABEL: ymm_reg_nonnull: +// CHECK: #APP +// CHECK: vmovaps ymm{{[0-9]+}}, ymm{{[0-9]+}} +// CHECK: #NO_APP +check!(ymm_reg_nonnull nonnull:ptr ymm_reg "vmovaps"); + // CHECK-LABEL: ymm_reg_i8x16: // CHECK: #APP // CHECK: vmovaps ymm{{[0-9]+}}, ymm{{[0-9]+}} @@ -430,6 +463,12 @@ check!(zmm_reg_f128 f128 zmm_reg "vmovaps"); // CHECK: #NO_APP check!(zmm_reg_ptr ptr zmm_reg "vmovaps"); +// CHECK-LABEL: zmm_reg_nonnull: +// CHECK: #APP +// CHECK: vmovaps zmm{{[0-9]+}}, zmm{{[0-9]+}} +// CHECK: #NO_APP +check!(zmm_reg_nonnull nonnull:ptr zmm_reg "vmovaps"); + // CHECK-LABEL: zmm_reg_i8x16: // CHECK: #APP // CHECK: vmovaps zmm{{[0-9]+}}, zmm{{[0-9]+}} @@ -586,6 +625,12 @@ check!(kreg_i64 i64 kreg "kmovq"); // CHECK: #NO_APP check!(kreg_ptr ptr kreg "kmovq"); +// CHECK-LABEL: kreg_nonnull: +// CHECK: #APP +// CHECK: kmovq k{{[0-9]+}}, k{{[0-9]+}} +// CHECK: #NO_APP +check!(kreg_nonnull nonnull:ptr kreg "kmovq"); + // CHECK-LABEL: eax_i16: // CHECK: #APP // CHECK: mov eax, eax @@ -630,6 +675,12 @@ check_reg!(eax_f64 f64 "eax" "mov"); // CHECK: #NO_APP check_reg!(eax_ptr ptr "eax" "mov"); +// CHECK-LABEL: eax_nonnull: +// CHECK: #APP +// CHECK: mov eax, eax +// CHECK: #NO_APP +check_reg!(eax_nonnull nonnull:ptr "eax" "mov"); + // i686-LABEL: ah_byte: // i686: #APP // i686: mov ah, ah @@ -679,6 +730,12 @@ check_reg!(xmm0_f128 f128 "xmm0" "movaps"); // CHECK: #NO_APP check_reg!(xmm0_ptr ptr "xmm0" "movaps"); +// CHECK-LABEL: xmm0_nonnull: +// CHECK: #APP +// CHECK: movaps xmm0, xmm0 +// CHECK: #NO_APP +check_reg!(xmm0_nonnull nonnull:ptr "xmm0" "movaps"); + // CHECK-LABEL: xmm0_i8x16: // CHECK: #APP // CHECK: movaps xmm0, xmm0 @@ -763,6 +820,12 @@ check_reg!(ymm0_f128 f128 "ymm0" "vmovaps"); // CHECK: #NO_APP check_reg!(ymm0_ptr ptr "ymm0" "vmovaps"); +// CHECK-LABEL: ymm0_nonnull: +// CHECK: #APP +// CHECK: vmovaps ymm0, ymm0 +// CHECK: #NO_APP +check_reg!(ymm0_nonnull nonnull:ptr "ymm0" "vmovaps"); + // CHECK-LABEL: ymm0_i8x16: // CHECK: #APP // CHECK: vmovaps ymm0, ymm0 @@ -889,6 +952,12 @@ check_reg!(zmm0_f128 f128 "zmm0" "vmovaps"); // CHECK: #NO_APP check_reg!(zmm0_ptr ptr "zmm0" "vmovaps"); +// CHECK-LABEL: zmm0_nonnull: +// CHECK: #APP +// CHECK: vmovaps zmm0, zmm0 +// CHECK: #NO_APP +check_reg!(zmm0_nonnull nonnull:ptr "zmm0" "vmovaps"); + // CHECK-LABEL: zmm0_i8x16: // CHECK: #APP // CHECK: vmovaps zmm0, zmm0 @@ -1044,3 +1113,9 @@ check_reg!(k1_i64 i64 "k1" "kmovq"); // CHECK: kmovq k1, k1 // CHECK: #NO_APP check_reg!(k1_ptr ptr "k1" "kmovq"); + +// CHECK-LABEL: k1_nonnull: +// CHECK: #APP +// CHECK: kmovq k1, k1 +// CHECK: #NO_APP +check_reg!(k1_nonnull nonnull:ptr "k1" "kmovq"); diff --git a/tests/assembly-llvm/asm/xtensa-types.rs b/tests/assembly-llvm/asm/xtensa-types.rs index 9419a78f9e07c..a7d679c22767e 100644 --- a/tests/assembly-llvm/asm/xtensa-types.rs +++ b/tests/assembly-llvm/asm/xtensa-types.rs @@ -3,7 +3,7 @@ //@ compile-flags: --target xtensa-esp32-none-elf -Zmerge-functions=disabled //@ needs-llvm-components: xtensa -#![feature(no_core, lang_items, rustc_attrs, asm_experimental_arch)] +#![feature(no_core, lang_items, rustc_attrs, asm_experimental_arch, asm_nonnull_inputs)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -13,6 +13,7 @@ use minicore::simd::*; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; extern "C" { fn extern_func(); @@ -29,8 +30,11 @@ pub unsafe fn sym_fn() { macro_rules! check_general_reg { ($func:ident $ty:ident $class:ident $mov:literal) => { + check_general_reg!($func $ty:$ty $class $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " {}, {}"), out($class) y, in($class) x); y @@ -62,10 +66,19 @@ check_general_reg!(reg_i32 i32 reg "mov"); // CHECK: #NO_APP check_general_reg!(reg_ptr ptr reg "mov"); +// CHECK-LABEL: reg_nonnull: +// CHECK: #APP +// CHECK: or a{{[0-9]+}}, a{{[0-9]+}}, a{{[0-9]+}} +// CHECK: #NO_APP +check_general_reg!(reg_nonnull nonnull:ptr reg "mov"); + macro_rules! check_explicit_reg { ($func:ident $ty:ident $reg:tt $mov:literal) => { + check_explicit_reg!($func $ty:$ty $reg $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $reg:tt $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); y @@ -103,6 +116,12 @@ check_explicit_reg!(a5_i32 i32 "a5" "mov"); // CHECK: #NO_APP check_explicit_reg!(a5_ptr ptr "a5" "mov"); +// CHECK-LABEL: a5_nonnull: +// CHECK: #APP +// CHECK: or a5, a5, a5 +// CHECK: #NO_APP +check_explicit_reg!(a5_nonnull nonnull:ptr "a5" "mov"); + // CHECK-LABEL: a14_i32: // CHECK: #APP // CHECK: or a14, a14, a14 diff --git a/tests/auxiliary/minicore.rs b/tests/auxiliary/minicore.rs index aca69642057ab..6e99ef96a7ef6 100644 --- a/tests/auxiliary/minicore.rs +++ b/tests/auxiliary/minicore.rs @@ -203,6 +203,7 @@ impl MaybeUninit { } } +#[lang = "non_null"] #[repr(transparent)] #[rustc_nonnull_optimization_guaranteed] pub struct NonNull { diff --git a/tests/codegen-llvm/inject-autocast.rs b/tests/codegen-llvm/inject-autocast.rs index f07153c17daf7..b2c0ab0e7b809 100644 --- a/tests/codegen-llvm/inject-autocast.rs +++ b/tests/codegen-llvm/inject-autocast.rs @@ -6,9 +6,7 @@ use std::simd::{f32x4, i16x8, i64x2}; -#[repr(C, packed)] pub struct Bar(u32, i64x2, i64x2, i64x2, i64x2, i64x2, i64x2); -// CHECK: %Bar = type <{ i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> }> #[repr(simd)] pub struct Tile([i8; 1024]); @@ -21,21 +19,27 @@ pub unsafe fn struct_autocast(key_metadata: u32, key: i64x2) -> Bar { fn foo(key_metadata: u32, key: i64x2) -> Bar; } - // CHECK: [[A:%[0-9]+]] = call { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } @llvm.x86.encodekey128(i32 {{.*}}, <2 x i64> {{.*}}) - // CHECK: [[B:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 0 - // CHECK: [[C:%[0-9]+]] = insertvalue %Bar poison, i32 [[B]], 0 - // CHECK: [[D:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 1 - // CHECK: [[E:%[0-9]+]] = insertvalue %Bar [[C]], <2 x i64> [[D]], 1 - // CHECK: [[F:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 2 - // CHECK: [[G:%[0-9]+]] = insertvalue %Bar [[E]], <2 x i64> [[F]], 2 - // CHECK: [[H:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 3 - // CHECK: [[I:%[0-9]+]] = insertvalue %Bar [[G]], <2 x i64> [[H]], 3 - // CHECK: [[J:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 4 - // CHECK: [[K:%[0-9]+]] = insertvalue %Bar [[I]], <2 x i64> [[J]], 4 - // CHECK: [[L:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 5 - // CHECK: [[M:%[0-9]+]] = insertvalue %Bar [[K]], <2 x i64> [[L]], 5 - // CHECK: [[N:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 6 - // CHECK: insertvalue %Bar [[M]], <2 x i64> [[N]], 6 + // CHECK: %0 = call { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } @llvm.x86.encodekey128(i32 %key_metadata, <2 x i64> %key) + // CHECK-NEXT: %1 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 0 + // CHECK-NEXT: %2 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 1 + // CHECK-NEXT: %3 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 2 + // CHECK-NEXT: %4 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 3 + // CHECK-NEXT: %5 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 4 + // CHECK-NEXT: %6 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 5 + // CHECK-NEXT: %7 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 6 + // CHECK-NEXT: %8 = getelementptr inbounds i8, ptr %_0, i64 96 + // CHECK-NEXT: store i32 %1, ptr %8, align 16 + // CHECK-NEXT: store <2 x i64> %2, ptr %_0, align 16 + // CHECK-NEXT: %9 = getelementptr inbounds i8, ptr %_0, i64 16 + // CHECK-NEXT: store <2 x i64> %3, ptr %9, align 16 + // CHECK-NEXT: %10 = getelementptr inbounds i8, ptr %_0, i64 32 + // CHECK-NEXT: store <2 x i64> %4, ptr %10, align 16 + // CHECK-NEXT: %11 = getelementptr inbounds i8, ptr %_0, i64 48 + // CHECK-NEXT: store <2 x i64> %5, ptr %11, align 16 + // CHECK-NEXT: %12 = getelementptr inbounds i8, ptr %_0, i64 64 + // CHECK-NEXT: store <2 x i64> %6, ptr %12, align 16 + // CHECK-NEXT: %13 = getelementptr inbounds i8, ptr %_0, i64 80 + // CHECK-NEXT: store <2 x i64> %7, ptr %13, align 16 foo(key_metadata, key) } @@ -47,15 +51,17 @@ pub unsafe fn struct_with_i1_vector_autocast(a: i64x2, b: i64x2) -> (u8, u8) { fn foo(a: i64x2, b: i64x2) -> (u8, u8); } - // CHECK: [[A:%[0-9]+]] = call { <2 x i1>, <2 x i1> } @llvm.x86.avx512.vp2intersect.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}) - // CHECK: [[B:%[0-9]+]] = extractvalue { <2 x i1>, <2 x i1> } [[A]], 0 - // CHECK: [[C:%[0-9]+]] = shufflevector <2 x i1> [[B]], <2 x i1> zeroinitializer, <8 x i32> - // CHECK: [[D:%[0-9]+]] = bitcast <8 x i1> [[C]] to i8 - // CHECK: [[E:%[0-9]+]] = insertvalue { i8, i8 } poison, i8 [[D]], 0 - // CHECK: [[F:%[0-9]+]] = extractvalue { <2 x i1>, <2 x i1> } [[A]], 1 - // CHECK: [[G:%[0-9]+]] = shufflevector <2 x i1> [[F]], <2 x i1> zeroinitializer, <8 x i32> - // CHECK: [[H:%[0-9]+]] = bitcast <8 x i1> [[G]] to i8 - // CHECK: insertvalue { i8, i8 } [[E]], i8 [[H]], 1 + // CHECK: %0 = call { <2 x i1>, <2 x i1> } @llvm.x86.avx512.vp2intersect.q.128(<2 x i64> %a, <2 x i64> %b) + // CHECK-NEXT: %1 = extractvalue { <2 x i1>, <2 x i1> } %0, 0 + // CHECK-NEXT: %2 = shufflevector <2 x i1> %1, <2 x i1> zeroinitializer, <8 x i32> + // CHECK-NEXT: %3 = bitcast <8 x i1> %2 to i8 + // CHECK-NEXT: %4 = extractvalue { <2 x i1>, <2 x i1> } %0, 1 + // CHECK-NEXT: %5 = shufflevector <2 x i1> %4, <2 x i1> zeroinitializer, <8 x i32> + // CHECK-NEXT: %6 = bitcast <8 x i1> %5 to i8 + // CHECK-NEXT: %7 = insertvalue { i8, i8 } poison, i8 %3, 0 + // CHECK-NEXT: %8 = insertvalue { i8, i8 } %7, i8 %6, 1 + // CHECK-NEXT: %_0.0 = extractvalue { i8, i8 } %8, 0 + // CHECK-NEXT: %_0.1 = extractvalue { i8, i8 } %8, 1 foo(a, b) } diff --git a/tests/ui-fulldeps/rustc_public/check_adt_queries.rs b/tests/ui-fulldeps/rustc_public/check_adt_queries.rs new file mode 100644 index 0000000000000..ebad1b56903e3 --- /dev/null +++ b/tests/ui-fulldeps/rustc_public/check_adt_queries.rs @@ -0,0 +1,158 @@ +//@ run-pass +//! Test that users are able to retrieve information about ADTs + +//@ ignore-stage1 +//@ ignore-cross-compile +//@ ignore-remote +//@ edition: 2024 + +#![feature(rustc_private)] + +extern crate rustc_middle; + +extern crate rustc_driver; +extern crate rustc_interface; +#[macro_use] +extern crate rustc_public; + +use std::{collections::HashSet, io::Write, ops::ControlFlow}; +use rustc_public::{ + mir::{mono::Instance, MirVisitor}, + ty::{AdtDef, RigidTy, Ty, TyKind} +}; + +const CRATE_NAME: &str = "adt_test"; + +#[derive(Default)] +struct AdtDefVisitor { + adt_defs: HashSet, +} + +impl MirVisitor for AdtDefVisitor { + fn visit_ty(&mut self, ty: &Ty, _location: rustc_public::mir::visit::Location) { + if let TyKind::RigidTy(RigidTy::Adt(adt, _)) = ty.kind() { + self.adt_defs.insert(adt); + } + self.super_ty(ty) + } +} + +/// This function uses the Stable MIR APIs to get information about the test crate. +fn test_adts() -> ControlFlow<()> { + let entry = rustc_public::entry_fn().expect("Expected main function"); + let main_fn = Instance::try_from(entry).expect("Expected main instance"); + let mut visitor = AdtDefVisitor::default(); + visitor.visit_body(&main_fn.body().expect("Expected main body")); + let AdtDefVisitor { adt_defs } = visitor; + + assert_eq!( + adt_defs.len(), + 5, + "Expected 5 ADTs, but found {:?}", adt_defs, + ); + + let has_box = adt_defs + .iter() + .any(|item| item.is_box()); + + let has_simd = adt_defs + .iter() + .any(|item| item.is_simd()); + + let has_phantom_data = adt_defs + .iter() + .any(|item| item.is_phantom_data()); + + let has_manually_drop = adt_defs + .iter() + .any(|item| item.is_manually_drop()); + + let has_unsafe_cell = adt_defs + .iter() + .any(|item| item.is_unsafe_cell()); + + assert!(has_box); + assert!(has_simd); + assert!(has_phantom_data); + assert!(has_manually_drop); + assert!(has_unsafe_cell); + + let adt_names = adt_defs.iter().map(|def| def.0.trimmed_name()).collect::>(); + + assert_name(&adt_names, "Box"); + assert_name(&adt_names, "PhantomData"); + assert_name(&adt_names, "Simd"); + assert_name(&adt_names, "ManuallyDrop"); + assert_name(&adt_names, "UnsafeCell"); + + // Verify all AdtDef::ty() returns the self type (Adt) + adt_defs.iter().for_each(|adt|{ + let ty = adt.ty(); + assert!( + matches!( + ty.kind(), + rustc_public::ty::TyKind::RigidTy(RigidTy::Adt(..)) + ), + ); + }); + + ControlFlow::Continue(()) +} + +fn assert_name(adt_names: &HashSet, target: &str) { + assert!( + adt_names.contains(target), + "Failed to find `{target}`. Implementations available: {adt_names:?}", + ); +} + +/// This test will generate and analyze a dummy crate using the stable mir. +/// For that, it will first write the dummy crate into a file. +/// Then it will create a `RustcPublic` using custom arguments and then +/// it will run the compiler. +fn main() { + let path = "adt_queries.rs"; + generate_input(&path).unwrap(); + let args = &[ + "rustc".to_string(), + "-Cpanic=abort".to_string(), + "--edition".to_string(), + "2024".to_string(), + "--crate-name".to_string(), + CRATE_NAME.to_string(), + path.to_string(), + ]; + run!(args, test_adts).unwrap(); +} + +fn generate_input(path: &str) -> std::io::Result<()> { + let mut file = std::fs::File::create(path)?; + write!( + file, + r#" + #![feature(portable_simd)] + + use std::boxed::Box; + use std::cell::UnsafeCell; + use std::ffi::CStr; + use std::mem::ManuallyDrop; + use std::marker::PhantomData; + use std::simd::f32x4; + + fn main() {{ + let _box = Box::new(42); + + let _phantom = PhantomData::; + + let _unsafe_cell = UnsafeCell::new(42); + + let mut _manually_drop = ManuallyDrop::new(42); + + let _cs: &CStr = c"hello"; + + let _simd = f32x4::splat(10.0); + }} + "# + )?; + Ok(()) +} diff --git a/tests/ui/asm/nonnull-output-fail.rs b/tests/ui/asm/nonnull-output-fail.rs new file mode 100644 index 0000000000000..457d1e7f6cee8 --- /dev/null +++ b/tests/ui/asm/nonnull-output-fail.rs @@ -0,0 +1,23 @@ +//@ needs-asm-support + +#![feature(asm_nonnull_inputs)] + +use std::arch::asm; +use std::ptr::NonNull; + +fn _f() { + let p: NonNull; + unsafe { + asm!("/* {} */", out(reg) p); + //~^ ERROR cannot use value of type `NonNull` for inline assembly + } +} + +fn _g(mut p: NonNull) { + unsafe { + asm!("/* {} */", inout(reg) p); + //~^ ERROR cannot use value of type `NonNull` for inline assembly + } +} + +fn main() {} diff --git a/tests/ui/asm/nonnull-output-fail.stderr b/tests/ui/asm/nonnull-output-fail.stderr new file mode 100644 index 0000000000000..16156a924199b --- /dev/null +++ b/tests/ui/asm/nonnull-output-fail.stderr @@ -0,0 +1,18 @@ +error: cannot use value of type `NonNull` for inline assembly + --> $DIR/nonnull-output-fail.rs:11:35 + | +LL | asm!("/* {} */", out(reg) p); + | ^ + | + = note: only integers, floats, SIMD vectors, scalable vectors, pointers and function pointers can be used as arguments for inline assembly + +error: cannot use value of type `NonNull` for inline assembly + --> $DIR/nonnull-output-fail.rs:18:37 + | +LL | asm!("/* {} */", inout(reg) p); + | ^ + | + = note: only integers, floats, SIMD vectors, scalable vectors, pointers and function pointers can be used as arguments for inline assembly + +error: aborting due to 2 previous errors + diff --git a/tests/ui/asm/x86_64/type-check-5.rs b/tests/ui/asm/x86_64/type-check-5.rs index aa7d3b2d2308b..b373a5aab5cf2 100644 --- a/tests/ui/asm/x86_64/type-check-5.rs +++ b/tests/ui/asm/x86_64/type-check-5.rs @@ -1,5 +1,7 @@ //@ only-x86_64 +#![feature(asm_nonnull_inputs)] + use std::arch::asm; fn main() { @@ -31,8 +33,8 @@ fn main() { // Register operands must be Copy - // Register operands must be integers, floats, SIMD vectors, pointers or - // function pointers. + // Register operands must be integers, floats, SIMD vectors, pointers, + // function pointers, or `NonNull` pointers. asm!("{}", in(reg) 0i64); asm!("{}", in(reg) 0f64); @@ -40,14 +42,18 @@ fn main() { asm!("{}", in(reg) 0 as *const u8); asm!("{}", in(reg) 0 as *mut u8); asm!("{}", in(reg) main as fn()); + asm!("{}", in(reg) std::ptr::NonNull::::dangling()); - // Register inputs (but not outputs) allow references and function types + // Register inputs (but not outputs) allow references, function types, + // and `NonNull` pointers. let mut f = main; let mut r = &mut 0; + let mut p = std::ptr::NonNull::::dangling(); asm!("{}", in(reg) f); asm!("{}", in(reg) r); - let _ = (f, r); + asm!("{}", in(reg) p); + let _ = (f, r, p); // Type checks ignore never type diff --git a/tests/ui/asm/x86_64/type-check-5.stderr b/tests/ui/asm/x86_64/type-check-5.stderr index 0c471ee28d261..377e1d19f6c5c 100644 --- a/tests/ui/asm/x86_64/type-check-5.stderr +++ b/tests/ui/asm/x86_64/type-check-5.stderr @@ -1,5 +1,5 @@ error[E0381]: used binding `x` isn't initialized - --> $DIR/type-check-5.rs:10:28 + --> $DIR/type-check-5.rs:12:28 | LL | let x: u64; | - binding declared here but left uninitialized @@ -12,7 +12,7 @@ LL | let x: u64 = 42; | ++++ error[E0381]: used binding `y` isn't initialized - --> $DIR/type-check-5.rs:13:9 + --> $DIR/type-check-5.rs:15:9 | LL | let mut y: u64; | ----- binding declared here but left uninitialized @@ -25,7 +25,7 @@ LL | let mut y: u64 = 42; | ++++ error[E0596]: cannot borrow `v` as mutable, as it is not declared as mutable - --> $DIR/type-check-5.rs:19:13 + --> $DIR/type-check-5.rs:21:13 | LL | let v: Vec = vec![0, 1, 2]; | ^ not mutable diff --git a/tests/ui/derives/deriving-all-codegen.stdout b/tests/ui/derives/deriving-all-codegen.stdout index 356e81b9a483e..6a385dde1353e 100644 --- a/tests/ui/derives/deriving-all-codegen.stdout +++ b/tests/ui/derives/deriving-all-codegen.stdout @@ -434,11 +434,10 @@ impl ::core::fmt::Debug for Big { #[inline] #[rustc_trivial_field_reads] fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - let names: &'static _ = "Big b1 b2 b3 b4 b5 b6 b7 b8"; - let values: &[&dyn ::core::fmt::Debug] = + ::core::fmt::Formatter::debug_struct_fields_finish(f, + "Big b1 b2 b3 b4 b5 b6 b7 b8", &[&self.b1, &self.b2, &self.b3, &self.b4, &self.b5, &self.b6, - &self.b7, &&self.b8]; - ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values) + &self.b7, &&self.b8]) } } #[automatically_derived] diff --git a/tests/ui/diagnostic_namespace/unsafe_attr.rs b/tests/ui/diagnostic_namespace/unsafe_attr.rs index 7a945dad0b66e..7db50a9ca4103 100644 --- a/tests/ui/diagnostic_namespace/unsafe_attr.rs +++ b/tests/ui/diagnostic_namespace/unsafe_attr.rs @@ -1,7 +1,9 @@ #[unsafe(diagnostic::on_unimplemented(message = "xyz"))] //~ ERROR `diagnostic::on_unimplemented` is not an unsafe attribute trait Test1 {} -#[unsafe(diagnostic::invalid)] //~ WARN unknown diagnostic attribute +#[unsafe(diagnostic::invalid)] +//~^ ERROR `diagnostic::invalid` is not an unsafe attribute +//~| WARN unknown diagnostic attribute trait Test2 {} fn main() { } diff --git a/tests/ui/diagnostic_namespace/unsafe_attr.stderr b/tests/ui/diagnostic_namespace/unsafe_attr.stderr index 732b466f22faa..a231ff5cfe3ec 100644 --- a/tests/ui/diagnostic_namespace/unsafe_attr.stderr +++ b/tests/ui/diagnostic_namespace/unsafe_attr.stderr @@ -6,6 +6,14 @@ LL | #[unsafe(diagnostic::on_unimplemented(message = "xyz"))] | = note: extraneous unsafe is not allowed in attributes +error: `diagnostic::invalid` is not an unsafe attribute + --> $DIR/unsafe_attr.rs:4:3 + | +LL | #[unsafe(diagnostic::invalid)] + | ^^^^^^ this is not an unsafe attribute + | + = note: extraneous unsafe is not allowed in attributes + warning: unknown diagnostic attribute --> $DIR/unsafe_attr.rs:4:22 | @@ -14,5 +22,5 @@ LL | #[unsafe(diagnostic::invalid)] | = note: `#[warn(unknown_diagnostic_attributes)]` (part of `#[warn(unknown_or_malformed_diagnostic_attributes)]`) on by default -error: aborting due to 1 previous error; 1 warning emitted +error: aborting due to 2 previous errors; 1 warning emitted diff --git a/tests/ui/feature-gates/feature-gate-asm_nonnull_inputs.rs b/tests/ui/feature-gates/feature-gate-asm_nonnull_inputs.rs new file mode 100644 index 0000000000000..9d70bb4051219 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-asm_nonnull_inputs.rs @@ -0,0 +1,11 @@ +//@ only-x86_64 + +use std::arch::asm; + +fn main() { + let mut p = core::ptr::NonNull::::dangling(); + unsafe { + asm!("/* {} */", in(reg) p); + //~^ ERROR cannot use value of type `NonNull` for inline assembly + } +} diff --git a/tests/ui/feature-gates/feature-gate-asm_nonnull_inputs.stderr b/tests/ui/feature-gates/feature-gate-asm_nonnull_inputs.stderr new file mode 100644 index 0000000000000..feee0d0bf92b6 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-asm_nonnull_inputs.stderr @@ -0,0 +1,10 @@ +error: cannot use value of type `NonNull` for inline assembly + --> $DIR/feature-gate-asm_nonnull_inputs.rs:8:34 + | +LL | asm!("/* {} */", in(reg) p); + | ^ + | + = note: only integers, floats, SIMD vectors, scalable vectors, pointers and function pointers can be used as arguments for inline assembly + +error: aborting due to 1 previous error +