diff --git a/.github/renovate.json5 b/.github/renovate.json5 index 1725fb3426564..1827901fc041e 100644 --- a/.github/renovate.json5 +++ b/.github/renovate.json5 @@ -35,11 +35,16 @@ "dependencyDashboardApproval": false }, { - // Update all Cargo.lock files except library/Cargo.lock in one PR. + // Set defaults for all Cargo.lock files. + // library/Cargo.lock is grouped into a dedicated PR by the more + // specific rule below. "matchManagers": ["cargo"], "matchUpdateTypes": ["lockFileMaintenance"], "groupName": "Cargo lock file maintenance", - "commitMessageAction": "Cargo lock file maintenance" + "commitMessageAction": "Compiler and tools lock file update", + // Renovate merges all matching rules, so the lockfiles rules below + // also inherits this note and asks Triagebot for a dep-bumps reviewer. + "prBodyNotes": ["r? dep-bumps"] }, { // Update library/Cargo.lock in a dedicated PR. @@ -47,7 +52,7 @@ "matchUpdateTypes": ["lockFileMaintenance"], "matchFileNames": ["library/Cargo.lock"], "groupName": "library lock file maintenance", - "commitMessageAction": "Library lock file maintenance" + "commitMessageAction": "Library lock file update" }, { // These packages don't have a committed Cargo.lock file. @@ -63,7 +68,7 @@ "matchManagers": ["npm"], "matchUpdateTypes": ["lockFileMaintenance"], "groupName": "Yarn lock file maintenance", - "commitMessageAction": "Yarn lock file maintenance" + "commitMessageAction": "Yarn lock file update" } ], "ignorePaths": [ diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 1f50fd8ac36e0..110c64c103acb 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -3981,7 +3981,7 @@ pub struct Fn { /// This function is an implementation of an externally implementable item (EII). /// This means, there was an EII declared somewhere and this function is the /// implementation that should be run when the declaration is called. - pub eii_impls: ThinVec, + pub eii_impl: Option>, } impl Fn { @@ -4073,9 +4073,7 @@ pub struct StaticItem { /// This static is an implementation of an externally implementable item (EII). /// This means, there was an EII declared somewhere and this static is the /// implementation that should be used for the declaration. - /// - /// For statics, there may be at most one `EiiImpl`, but this is a `ThinVec` to make usages of this field nicer. - pub eii_impls: ThinVec, + pub eii_impl: Option>, } #[derive(Clone, Encodable, Decodable, Debug, Walkable)] diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index a768935f38fc3..9d4c32825e1e4 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -933,12 +933,12 @@ macro_rules! common_visitor_and_walkers { _ctxt, // Visibility is visited as a part of the item. _vis, - Fn { defaultness, ident, sig, generics, contract, body, define_opaque, eii_impls }, + Fn { defaultness, ident, sig, generics, contract, body, define_opaque, eii_impl }, ) => { let FnSig { header, decl, span } = sig; visit_visitable!($($mut)? vis, defaultness, ident, header, generics, decl, - contract, body, span, define_opaque, eii_impls + contract, body, span, define_opaque, eii_impl ); } FnKind::Closure(binder, coroutine_kind, decl, body) => diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 34c7137b8676d..3cc27be600965 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -170,15 +170,13 @@ impl<'hir> LoweringContext<'_, 'hir> { i: &ItemKind, ) -> Vec { match i { - ItemKind::Fn(Fn { eii_impls, .. }) | ItemKind::Static(StaticItem { eii_impls, .. }) - if eii_impls.is_empty() => - { - Vec::new() - } - ItemKind::Fn(Fn { eii_impls, .. }) | ItemKind::Static(StaticItem { eii_impls, .. }) => { - vec![hir::Attribute::Parsed(AttributeKind::EiiImpls( - eii_impls.iter().map(|i| self.lower_eii_impl(i)).collect(), - ))] + ItemKind::Fn(Fn { eii_impl: None, .. }) + | ItemKind::Static(StaticItem { eii_impl: None, .. }) => Vec::new(), + ItemKind::Fn(Fn { eii_impl: Some(eii_impl), .. }) + | ItemKind::Static(StaticItem { eii_impl: Some(eii_impl), .. }) => { + vec![hir::Attribute::Parsed(AttributeKind::EiiImpl(Box::new( + self.lower_eii_impl(eii_impl), + )))] } ItemKind::MacroDef(name, MacroDef { eii_declaration: Some(target), .. }) => self .lower_eii_decl(id, *name, target) @@ -226,7 +224,7 @@ impl<'hir> LoweringContext<'_, 'hir> { kind, vis_span, span: self.lower_span(i.span), - eii: find_attr!(attrs, EiiImpls(..) | EiiDeclaration(..)), + eii: find_attr!(attrs, EiiImpl(..) | EiiDeclaration(..)), }; self.arena.alloc(item) } @@ -259,7 +257,7 @@ impl<'hir> LoweringContext<'_, 'hir> { mutability: m, expr: e, define_opaque, - eii_impls: _, + eii_impl: _, }) => { let ident = self.lower_ident(*ident); let ty = self @@ -696,7 +694,7 @@ impl<'hir> LoweringContext<'_, 'hir> { kind, vis_span, span: this.lower_span(use_tree.span()), - eii: find_attr!(attrs, EiiImpls(..) | EiiDeclaration(..)), + eii: find_attr!(attrs, EiiImpl(..) | EiiDeclaration(..)), }; hir::OwnerNode::Item(this.arena.alloc(item)) }); @@ -763,7 +761,7 @@ impl<'hir> LoweringContext<'_, 'hir> { expr: _, safety, define_opaque, - eii_impls: _, + eii_impl: _, }) => { let ty = self .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy)); diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 12a345aaeaf1d..c22b517b3ddf9 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -935,6 +935,13 @@ impl<'a> AstValidator<'a> { match fn_ctxt { FnCtxt::Foreign => return, FnCtxt::Free | FnCtxt::Assoc(_) => { + // Reject `...` without a pattern post-expansion. The varargs_without_pattern + // FCW is already triggered pre-expansion. + if let PatKind::Missing = variadic_param.pat.kind { + self.dcx() + .emit_err(diagnostics::VarargsWithoutPattern { span: variadic_param.span }); + } + match self.sess.target.supports_c_variadic_definitions() { CVariadicStatus::NotSupported => { self.dcx().emit_err(diagnostics::CVariadicNotSupported { @@ -1259,10 +1266,10 @@ impl<'a> AstValidator<'a> { } // Check EII implementation attributes against an allowlist. - fn check_eii_impl_attrs(&self, attrs: &[Attribute], eii_impls: &[EiiImpl]) { - if eii_impls.is_empty() { + fn check_eii_impl_attrs(&self, attrs: &[Attribute], eii_impl: &Option>) { + let Some(eii_impl) = eii_impl else { return; - } + }; let allowed_attrs: &[Symbol] = &[ sym::allow, @@ -1289,14 +1296,12 @@ impl<'a> AstValidator<'a> { } let attr_name = pprust::path_to_string(&normal.item.path); - for eii_impl in eii_impls { - self.dcx().emit_err(diagnostics::EiiImplAttributeNotSupported { - attr_span: attr.span, - attr_name: &attr_name, - eii_span: eii_impl.span, - eii_name: pprust::path_to_string(&eii_impl.eii_macro_path), - }); - } + self.dcx().emit_err(diagnostics::EiiImplAttributeNotSupported { + attr_span: attr.span, + attr_name: &attr_name, + eii_span: eii_impl.span, + eii_name: pprust::path_to_string(&eii_impl.eii_macro_path), + }); } } } @@ -1479,16 +1484,16 @@ impl Visitor<'_> for AstValidator<'_> { contract: _, body, define_opaque: _, - eii_impls, + eii_impl, }, ) => { self.visit_attrs_vis_ident(&item.attrs, &item.vis, ident); self.check_defaultness(item.span, *defaultness, AllowDefault::No, AllowFinal::No); - for EiiImpl { eii_macro_path, .. } in eii_impls { + if let Some(EiiImpl { eii_macro_path, .. }) = eii_impl { self.visit_path(eii_macro_path); } - self.check_eii_impl_attrs(&item.attrs, eii_impls); + self.check_eii_impl_attrs(&item.attrs, eii_impl); let is_intrinsic = item.attrs.iter().any(|a| a.has_name(sym::rustc_intrinsic)); if body.is_none() && !is_intrinsic && !self.is_sdylib_interface { @@ -1664,9 +1669,9 @@ impl Visitor<'_> for AstValidator<'_> { visit::walk_item(self, item); } - ItemKind::Static(StaticItem { expr, safety, eii_impls, .. }) => { + ItemKind::Static(StaticItem { expr, safety, eii_impl, .. }) => { self.check_item_safety(item.span, *safety); - self.check_eii_impl_attrs(&item.attrs, eii_impls); + self.check_eii_impl_attrs(&item.attrs, eii_impl); if matches!(safety, Safety::Unsafe(_)) { self.dcx().emit_err(diagnostics::UnsafeStatic { span: item.span }); } diff --git a/compiler/rustc_ast_passes/src/diagnostics.rs b/compiler/rustc_ast_passes/src/diagnostics.rs index 241b2dae97ea1..db006e50aaa31 100644 --- a/compiler/rustc_ast_passes/src/diagnostics.rs +++ b/compiler/rustc_ast_passes/src/diagnostics.rs @@ -1245,3 +1245,15 @@ pub(crate) enum DeprecatedWhereClauseLocationSugg { span: Span, }, } + +#[derive(Diagnostic)] +#[diag("missing pattern for `...` argument")] +pub(crate) struct VarargsWithoutPattern { + #[suggestion( + "add a pattern for this argument", + applicability = "machine-applicable", + code = "_: ..." + )] + #[primary_span] + pub span: Span, +} diff --git a/compiler/rustc_ast_pretty/src/pprust/state/item.rs b/compiler/rustc_ast_pretty/src/pprust/state/item.rs index 1fb71b7b06299..04f78ea7f467a 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/item.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/item.rs @@ -42,7 +42,7 @@ impl<'a> State<'a> { expr, safety, define_opaque, - eii_impls, + eii_impl, }) => self.print_item_const( *ident, Some(*mutability), @@ -53,7 +53,7 @@ impl<'a> State<'a> { *safety, ast::Defaultness::Implicit, define_opaque.as_deref(), - eii_impls, + eii_impl.as_deref(), ), ast::ForeignItemKind::TyAlias(ast::TyAlias { defaultness, @@ -94,10 +94,10 @@ impl<'a> State<'a> { safety: ast::Safety, defaultness: ast::Defaultness, define_opaque: Option<&[(ast::NodeId, ast::Path)]>, - eii_impls: &[EiiImpl], + eii_impl: Option<&EiiImpl>, ) { self.print_define_opaques(define_opaque); - for eii_impl in eii_impls { + if let Some(eii_impl) = eii_impl { self.print_eii_impl(eii_impl); } let (cb, ib) = self.head(""); @@ -196,7 +196,7 @@ impl<'a> State<'a> { mutability: mutbl, expr: body, define_opaque, - eii_impls, + eii_impl, }) => { self.print_safety(*safety); self.print_item_const( @@ -209,7 +209,7 @@ impl<'a> State<'a> { ast::Safety::Default, ast::Defaultness::Implicit, define_opaque.as_deref(), - eii_impls, + eii_impl.as_deref(), ); } ast::ItemKind::ConstBlock(ast::ConstBlockItem { id: _, span: _, block }) => { @@ -242,7 +242,7 @@ impl<'a> State<'a> { ast::Safety::Default, *defaultness, define_opaque.as_deref(), - &[], + None, ); } ast::ItemKind::Fn(func) => { @@ -631,7 +631,7 @@ impl<'a> State<'a> { ast::Safety::Default, *defaultness, define_opaque.as_deref(), - &[], + None, ); } ast::AssocItemKind::Type(ast::TyAlias { @@ -731,12 +731,12 @@ impl<'a> State<'a> { } fn print_fn_full(&mut self, vis: &ast::Visibility, attrs: &[ast::Attribute], func: &ast::Fn) { - let ast::Fn { defaultness, ident, generics, sig, contract, body, define_opaque, eii_impls } = + let ast::Fn { defaultness, ident, generics, sig, contract, body, define_opaque, eii_impl } = func; self.print_define_opaques(define_opaque.as_deref()); - for eii_impl in eii_impls { + if let Some(eii_impl) = eii_impl { self.print_eii_impl(eii_impl); } diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index db8588f49c371..6107cdac166aa 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -4277,7 +4277,8 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> { ) -> Option> { // Define a fallback for when we can't match a closure. let fallback = || { - let is_closure = self.infcx.tcx.is_closure_like(self.mir_def_id().to_def_id()); + let tcx = self.infcx.tcx; + let is_closure = tcx.is_closure_like(self.mir_def_id().to_def_id()); if is_closure { None } else { @@ -4288,7 +4289,7 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> { .instantiate_identity() .skip_norm_wip(); match ty.kind() { - ty::FnDef(_, _) | ty::FnPtr(..) => self.annotate_fn_sig( + ty::FnDef(_, _) => self.annotate_fn_sig( self.mir_def_id(), self.infcx .tcx @@ -4296,6 +4297,8 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> { .instantiate_identity() .skip_norm_wip(), ), + // a const/static can have a fn ptr type, take the sig from the type instead. + ty::FnPtr(_, _) => self.annotate_fn_sig(self.mir_def_id(), ty.fn_sig(tcx)), _ => None, } } diff --git a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs index d50fc78b51e14..57e589ac5a1e8 100644 --- a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs +++ b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs @@ -96,7 +96,7 @@ fn generate_handler(cx: &ExtCtxt<'_>, handler: Ident, span: Span, sig_span: Span contract: None, body, define_opaque: None, - eii_impls: ThinVec::new(), + eii_impl: None, })); let attrs = thin_vec![cx.attr_word(sym::rustc_std_internal_symbol, span)]; diff --git a/compiler/rustc_builtin_macros/src/autodiff.rs b/compiler/rustc_builtin_macros/src/autodiff.rs index 51ab44d8a03ef..0618c28759a66 100644 --- a/compiler/rustc_builtin_macros/src/autodiff.rs +++ b/compiler/rustc_builtin_macros/src/autodiff.rs @@ -344,7 +344,7 @@ mod llvm_enzyme { contract: None, body: Some(d_body), define_opaque: None, - eii_impls: ThinVec::new(), + eii_impl: None, }); let mut rustc_ad_attr = Box::new(ast::NormalAttr::from_ident(Ident::with_dummy_span(sym::rustc_autodiff))); diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index cc036fab83c9d..03ccdbb902a96 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -1083,7 +1083,7 @@ impl<'a> MethodDef<'a> { contract: None, body: Some(body_block), define_opaque: None, - eii_impls: ThinVec::new(), + eii_impl: None, })), tokens: None, }) diff --git a/compiler/rustc_builtin_macros/src/diagnostics.rs b/compiler/rustc_builtin_macros/src/diagnostics.rs index 71dc17b108a97..ce5fb4e86dab6 100644 --- a/compiler/rustc_builtin_macros/src/diagnostics.rs +++ b/compiler/rustc_builtin_macros/src/diagnostics.rs @@ -1094,6 +1094,13 @@ pub(crate) struct CfgSelectNoMatches { pub span: Span, } +#[derive(Diagnostic)] +#[diag("a single item cannot both declare and implement EIIs")] +pub(crate) struct EiiBothDeclAndImpl { + #[primary_span] + pub span: Span, +} + #[derive(Diagnostic)] #[diag("`#[eii_declaration(...)]` is only valid on macros")] pub(crate) struct EiiExternTargetExpectedMacro { @@ -1117,21 +1124,18 @@ pub(crate) struct EiiExternTargetExpectedUnsafe { } #[derive(Diagnostic)] -#[diag("`#[{$name}]` is only valid on functions and statics")] -pub(crate) struct EiiSharedMacroTarget { +#[diag("a single item cannot implement multiple EIIs")] +pub(crate) struct EiiMultipleImplementations { #[primary_span] pub span: Span, - pub name: String, } #[derive(Diagnostic)] -#[diag("static cannot implement multiple EIIs")] -#[note( - "this is not allowed because multiple externally implementable statics that alias may be unintuitive" -)] -pub(crate) struct EiiStaticMultipleImplementations { +#[diag("`#[{$name}]` is only valid on functions and statics")] +pub(crate) struct EiiSharedMacroTarget { #[primary_span] pub span: Span, + pub name: String, } #[derive(Diagnostic)] diff --git a/compiler/rustc_builtin_macros/src/eii.rs b/compiler/rustc_builtin_macros/src/eii.rs index 5a28416900372..cf50460422f52 100644 --- a/compiler/rustc_builtin_macros/src/eii.rs +++ b/compiler/rustc_builtin_macros/src/eii.rs @@ -10,10 +10,10 @@ use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym}; use thin_vec::{ThinVec, thin_vec}; use crate::diagnostics::{ - EiiAttributeNotSupported, EiiExternTargetExpectedList, EiiExternTargetExpectedMacro, - EiiExternTargetExpectedUnsafe, EiiMacroExpectedMaxOneArgument, EiiOnlyOnce, - EiiSharedMacroInStatementPosition, EiiSharedMacroTarget, EiiStaticArgumentRequired, - EiiStaticDefaultApple, EiiStaticMultipleImplementations, EiiStaticMutable, + EiiAttributeNotSupported, EiiBothDeclAndImpl, EiiExternTargetExpectedList, + EiiExternTargetExpectedMacro, EiiExternTargetExpectedUnsafe, EiiMacroExpectedMaxOneArgument, + EiiMultipleImplementations, EiiOnlyOnce, EiiSharedMacroInStatementPosition, + EiiSharedMacroTarget, EiiStaticArgumentRequired, EiiStaticDefaultApple, EiiStaticMutable, }; /// ```rust @@ -125,6 +125,22 @@ fn eii_( } }; + match kind { + ItemKind::Fn(func) => { + if func.eii_impl.is_some() { + ecx.dcx().emit_err(EiiBothDeclAndImpl { span: eii_attr_span }); + return vec![Annotatable::Item(item)]; + } + } + ItemKind::Static(stat) => { + if stat.eii_impl.is_some() { + ecx.dcx().emit_err(EiiBothDeclAndImpl { span: eii_attr_span }); + return vec![Annotatable::Item(item)]; + } + } + _ => unreachable!("Target was checked earlier"), + }; + // only clone what we need let attrs = attrs.clone(); let vis = vis.clone(); @@ -298,7 +314,7 @@ fn generate_default_impl( _ => unreachable!("Target was checked earlier"), }; - let eii_impl = EiiImpl { + let eii_impl = Box::new(EiiImpl { node_id: DUMMY_NODE_ID, inner_span: macro_name.span, eii_macro_path: ast::Path::from_ident(macro_name), @@ -315,15 +331,17 @@ fn generate_default_impl( // NOTE: this is why EIIs can't be used on statements vec![Ident::from_str_and_span("self", foreign_item_name.span), foreign_item_name], )), - }; + }); let mut item_kind = item_kind.clone(); match &mut item_kind { ItemKind::Fn(func) => { - func.eii_impls.push(eii_impl); + assert!(func.eii_impl.is_none()); + func.eii_impl = Some(eii_impl); } ItemKind::Static(stat) => { - stat.eii_impls.push(eii_impl); + assert!(stat.eii_impl.is_none()); + stat.eii_impl = Some(eii_impl); } _ => unreachable!("Target was checked earlier"), }; @@ -579,16 +597,9 @@ pub(crate) fn eii_shared_macro( return vec![item]; }; - let eii_impls = match &mut i.kind { - ItemKind::Fn(func) => &mut func.eii_impls, - ItemKind::Static(stat) => { - if !stat.eii_impls.is_empty() { - // Reject multiple implementations on one static item - // because it might be unintuitive for libraries defining statics the defined statics may alias - ecx.dcx().emit_err(EiiStaticMultipleImplementations { span }); - } - &mut stat.eii_impls - } + let eii_impl = match &mut i.kind { + ItemKind::Fn(func) => &mut func.eii_impl, + ItemKind::Static(stat) => &mut stat.eii_impl, _ => { ecx.dcx() .emit_err(EiiSharedMacroTarget { span, name: path_to_string(&meta_item.path) }); @@ -611,7 +622,10 @@ pub(crate) fn eii_shared_macro( return vec![item]; }; - eii_impls.push(EiiImpl { + if eii_impl.is_some() { + ecx.dcx().emit_err(EiiMultipleImplementations { span }); + } + *eii_impl = Some(Box::new(EiiImpl { node_id: DUMMY_NODE_ID, inner_span: meta_item.path.span, eii_macro_path: meta_item.path.clone(), @@ -619,7 +633,7 @@ pub(crate) fn eii_shared_macro( span, is_default, known_eii_macro_resolution: None, - }); + })); vec![item] } diff --git a/compiler/rustc_builtin_macros/src/global_allocator.rs b/compiler/rustc_builtin_macros/src/global_allocator.rs index 72b493e313326..00ed0f52d6a6f 100644 --- a/compiler/rustc_builtin_macros/src/global_allocator.rs +++ b/compiler/rustc_builtin_macros/src/global_allocator.rs @@ -97,7 +97,7 @@ impl AllocFnFactory<'_, '_> { contract: None, body, define_opaque: None, - eii_impls: ThinVec::new(), + eii_impl: None, })); let item = self.cx.item(self.span, self.attrs(method), kind); self.cx.stmt_item(self.ty_span, item) diff --git a/compiler/rustc_builtin_macros/src/offload.rs b/compiler/rustc_builtin_macros/src/offload.rs index cdb3ba22ec6c8..e47ccc0d85f7d 100644 --- a/compiler/rustc_builtin_macros/src/offload.rs +++ b/compiler/rustc_builtin_macros/src/offload.rs @@ -85,7 +85,7 @@ pub(crate) fn expand_kernel( contract: None, body, define_opaque: None, - eii_impls: Default::default(), + eii_impl: None, }); let extern_gpu_kernel = ast::Extern::from_abi( @@ -157,7 +157,7 @@ pub(crate) fn expand_kernel( contract: None, body: Some(body), define_opaque: None, - eii_impls: Default::default(), + eii_impl: None, }); for param in host_fn.sig.decl.inputs.iter_mut() { diff --git a/compiler/rustc_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs index ff9d9f10dd4e1..5d20fed223468 100644 --- a/compiler/rustc_builtin_macros/src/test_harness.rs +++ b/compiler/rustc_builtin_macros/src/test_harness.rs @@ -347,7 +347,7 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> Box { contract: None, body: Some(main_body), define_opaque: None, - eii_impls: ThinVec::new(), + eii_impl: None, })); let main = Box::new(ast::Item { diff --git a/compiler/rustc_codegen_gcc/.cspell.json b/compiler/rustc_codegen_gcc/.cspell.json index 556432d69a41b..a2856029c2c1a 100644 --- a/compiler/rustc_codegen_gcc/.cspell.json +++ b/compiler/rustc_codegen_gcc/.cspell.json @@ -22,7 +22,7 @@ "src/intrinsic/llvm.rs" ], "ignoreRegExpList": [ - "/(FIXME|NOTE|TODO)\\([^)]+\\)/", + "/(FIXME|NOTE)\\([^)]+\\)/", "__builtin_\\w*" ] } diff --git a/compiler/rustc_codegen_gcc/.github/workflows/ci.yml b/compiler/rustc_codegen_gcc/.github/workflows/ci.yml index fa9535a3729c3..b76c79fd10870 100644 --- a/compiler/rustc_codegen_gcc/.github/workflows/ci.yml +++ b/compiler/rustc_codegen_gcc/.github/workflows/ci.yml @@ -26,7 +26,7 @@ jobs: - { gcc: "gcc-15.deb" } - { gcc: "gcc-15-without-int128.deb" } commands: [ - "--std-tests", + "--std-tests --alloc-tests", # FIXME: re-enable asm tests when GCC can emit in the right syntax. # "--asm-tests", "--test-libcore", @@ -36,6 +36,7 @@ jobs: "--test-successful-rustc --nb-parts 2 --current-part 0", "--test-successful-rustc --nb-parts 2 --current-part 1", "--projects", + "--gcc-asm-tests", ] steps: @@ -52,9 +53,6 @@ jobs: # `llvm-14-tools` is needed to install the `FileCheck` binary which is used for asm tests. run: sudo apt-get install ninja-build ripgrep llvm-14-tools llvm - - name: Install rustfmt & clippy - run: rustup component add rustfmt clippy - - name: Download artifact run: curl -LO https://github.com/rust-lang/gcc/releases/latest/download/${{ matrix.libgccjit_version.gcc }} @@ -88,16 +86,17 @@ jobs: - name: Check formatting run: ./y.sh fmt --check - - name: clippy - run: | - cargo clippy --all-targets -- -D warnings - cargo clippy --all-targets --no-default-features -- -D warnings - cargo clippy --manifest-path build_system/Cargo.toml --all-targets -- -D warnings + - name: Check todo + run: ./y.sh check-todo + + - name: Check lints + run: ./y.sh clippy - name: Build run: | ./y.sh build --sysroot ./y.sh test --cargo-tests + CARGO_TEST_FLAGS="-Zmir-preserve-ub" ./y.sh test --cargo-tests -- mir_preserve_ub_empty_switch - name: Run y.sh cargo build run: | diff --git a/compiler/rustc_codegen_gcc/.github/workflows/stdarch.yml b/compiler/rustc_codegen_gcc/.github/workflows/stdarch.yml index 66f30b147b4c0..17d6449c85e08 100644 --- a/compiler/rustc_codegen_gcc/.github/workflows/stdarch.yml +++ b/compiler/rustc_codegen_gcc/.github/workflows/stdarch.yml @@ -21,7 +21,7 @@ jobs: fail-fast: false matrix: cargo_runner: [ - "sde -future -rtm_mode full --", + "sde -cpuid-in /home/runner/work/rustc_codegen_gcc/rustc_codegen_gcc/tests/cpuid.def -rtm_mode full --", "", ] @@ -42,8 +42,14 @@ jobs: - name: Install more recent binutils run: | echo "deb http://archive.ubuntu.com/ubuntu plucky main universe" | sudo tee /etc/apt/sources.list.d/plucky-copies.list - sudo apt-get update + sudo apt-get update -o Acquire::Retries=3 sudo apt-get install binutils + installed="$(dpkg-query --showformat='${Version}' --show binutils)" + echo "Installed binutils: $installed" + if dpkg --compare-versions "$installed" lt "2.44"; then + echo "::error::binutils upgrade failed (got $installed, need >= 2.44); the apt fetch probably failed" + exit 1 + fi - name: Install Intel Software Development Emulator if: ${{ matrix.cargo_runner }} @@ -51,10 +57,9 @@ jobs: mkdir intel-sde cd intel-sde version=10.8.0-2026-03-15 - url_path=915934 dir=sde-external-$version-lin file=$dir.tar.xz - wget https://downloadmirror.intel.com/$url_path/$file + wget http://ci-mirrors.rust-lang.org/$file tar xvf $file sudo mkdir /usr/share/intel-sde sudo cp -r $dir/* /usr/share/intel-sde @@ -90,14 +95,15 @@ jobs: - name: Run stdarch tests if: ${{ !matrix.cargo_runner }} run: | - CHANNEL=release TARGET=x86_64-unknown-linux-gnu CG_RUSTFLAGS="-Ainternal_features" ./y.sh cargo test --manifest-path build/build_sysroot/sysroot_src/library/stdarch/Cargo.toml + # FIXME: remove --skip test_tile_ and --skip --skip test__tile when it's implemented. + ./y.sh test --release --stdarch-tests -- --skip test_tile_ --skip test__tile - name: Run stdarch tests if: ${{ matrix.cargo_runner }} run: | # FIXME: these tests fail when the sysroot is compiled with LTO because of a missing symbol in proc-macro. - # FIXME: remove --skip test_tile_ when it's implemented. - STDARCH_TEST_SKIP_FUNCTION="xsave,xsaveopt,xsave64,xsaveopt64" STDARCH_TEST_EVERYTHING=1 CHANNEL=release CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER="${{ matrix.cargo_runner }}" TARGET=x86_64-unknown-linux-gnu CG_RUSTFLAGS="-Ainternal_features" ./y.sh cargo test --manifest-path build/build_sysroot/sysroot_src/library/stdarch/Cargo.toml -- --skip rtm --skip tbm --skip sse4a --skip test_tile_ + # FIXME: remove --skip test_tile_ and --skip --skip test__tile when it's implemented. + STDARCH_TEST_SKIP_FUNCTION="xsave,xsaveopt,xsave64,xsaveopt64" STDARCH_TEST_EVERYTHING=1 CHANNEL=release CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER="${{ matrix.cargo_runner }}" TARGET=x86_64-unknown-linux-gnu CG_RUSTFLAGS="-Ainternal_features" ./y.sh cargo test --manifest-path build/build_sysroot/sysroot_src/library/stdarch/Cargo.toml -- --skip rtm --skip tbm --skip sse4a --skip test_tile_ --skip test__tile # Summary job for the merge queue. # ALL THE PREVIOUS JOBS NEED TO BE ADDED TO THE `needs` SECTION OF THIS JOB! diff --git a/compiler/rustc_codegen_gcc/.gitignore b/compiler/rustc_codegen_gcc/.gitignore index 8f73d3eb972a0..1bbd3a9958073 100644 --- a/compiler/rustc_codegen_gcc/.gitignore +++ b/compiler/rustc_codegen_gcc/.gitignore @@ -7,7 +7,7 @@ perf.data.old *.events *.string* gimple* -*asm +*_asm res test-backend projects diff --git a/compiler/rustc_codegen_gcc/CONTRIBUTING.md b/compiler/rustc_codegen_gcc/CONTRIBUTING.md index 8f81ecca445a8..c5c2a783b1ee7 100644 --- a/compiler/rustc_codegen_gcc/CONTRIBUTING.md +++ b/compiler/rustc_codegen_gcc/CONTRIBUTING.md @@ -112,7 +112,7 @@ Full list of debugging options can be found in the [README](Readme.md#env-vars). ### Code Style Guidelines - Follow Rust standard coding conventions -- Ensure your code passes `rustfmt` and `clippy` +- Ensure your code passes `rustfmt` and `clippy` (you can run them with `y.sh fmt` and `y.sh clippy`) - Add comments explaining complex logic, especially in GCC interface code ## Additional Resources diff --git a/compiler/rustc_codegen_gcc/Cargo.lock b/compiler/rustc_codegen_gcc/Cargo.lock index a283ea4cb0b05..060509e51a6f9 100644 --- a/compiler/rustc_codegen_gcc/Cargo.lock +++ b/compiler/rustc_codegen_gcc/Cargo.lock @@ -31,9 +31,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "errno" -version = "0.3.10" +version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", "windows-sys", @@ -56,18 +56,18 @@ dependencies = [ [[package]] name = "gccjit" -version = "3.3.0" +version = "4.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b73d18b642ce16378af78f89664841d7eeafa113682ff5d14573424eb0232a" +checksum = "be5dafc4e649cb4a363e95a5960ef50b0c6f1b8e136ff8eb2e928b40353b5d8b" dependencies = [ "gccjit_sys", ] [[package]] name = "gccjit_sys" -version = "1.3.0" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee689456c013616942d5aef9a84d613cefcc3b335340d036f3650fc1a7459e15" +checksum = "ab6a00a243aba2a45442bfd72b28d871137d4dac094f13de7f48cf9705112ffe" dependencies = [ "libc", ] @@ -117,15 +117,15 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.168" +version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aaeb2981e0606ca11d79718f8bb01164f1d6ed75080182d3abf017e6d244b6d" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" [[package]] name = "linux-raw-sys" -version = "0.9.4" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "memchr" @@ -194,9 +194,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.0.7" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c71e83d6afe7ff64890ec6b71d6a69bb8a610ab78ce364b3352876bb4c801266" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ "bitflags", "errno", @@ -216,9 +216,9 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.20.0" +version = "3.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", "getrandom", @@ -311,78 +311,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] -name = "windows-sys" -version = "0.59.0" +name = "windows-link" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets", -] +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] -name = "windows-targets" -version = "0.52.6" +name = "windows-sys" +version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows-link", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - [[package]] name = "wit-bindgen-rt" version = "0.39.0" diff --git a/compiler/rustc_codegen_gcc/Cargo.toml b/compiler/rustc_codegen_gcc/Cargo.toml index 8956bd6948979..63a20d46b9d2f 100644 --- a/compiler/rustc_codegen_gcc/Cargo.toml +++ b/compiler/rustc_codegen_gcc/Cargo.toml @@ -20,7 +20,7 @@ default = ["master"] [dependencies] object = { version = "0.37.0", default-features = false, features = ["std", "read"] } tempfile = "3.20" -gccjit = { version = "3.3.0", features = ["dlopen"] } +gccjit = { version = "4.0.0", features = ["dlopen"] } #gccjit = { git = "https://github.com/rust-lang/gccjit.rs", branch = "error-dlopen", features = ["dlopen"] } # Local copy. diff --git a/compiler/rustc_codegen_gcc/Readme.md b/compiler/rustc_codegen_gcc/Readme.md index ce5ee1e4adee6..26783aa39cea8 100644 --- a/compiler/rustc_codegen_gcc/Readme.md +++ b/compiler/rustc_codegen_gcc/Readme.md @@ -136,19 +136,21 @@ $ ./y.sh cargo build --manifest-path tests/hello-world/Cargo.toml ### Cargo ```bash -$ CHANNEL="release" $CG_GCCJIT_DIR/y.sh cargo run +$ CHANNEL=release $CG_GCCJIT_DIR/y.sh cargo run ``` -If you compiled cg_gccjit in debug mode (aka you didn't pass `--release` to `./y.sh test`) you should use `CHANNEL="debug"` instead or omit `CHANNEL="release"` completely. +If you compiled `cg_gcc` in debug mode (aka you didn't pass `--release` to `./y.sh build`) you should use `CHANNEL=debug` instead or omit `CHANNEL=release` completely. ### Rustc If you want to run `rustc` directly, you can do so with: ```bash -$ ./y.sh rustc my_crate.rs +$ CHANNEL=release ./y.sh rustc my_crate.rs ``` +If you compiled `cg_gcc` in debug mode (aka you didn't pass `--release` to `./y.sh build`) you should use `CHANNEL=debug` instead or omit `CHANNEL=release` completely. + You can do the same manually (although we don't recommend it): ```bash diff --git a/compiler/rustc_codegen_gcc/build_system/Cargo.lock b/compiler/rustc_codegen_gcc/build_system/Cargo.lock index e727561a2bfba..5e761149eb3bc 100644 --- a/compiler/rustc_codegen_gcc/build_system/Cargo.lock +++ b/compiler/rustc_codegen_gcc/build_system/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "boml" diff --git a/compiler/rustc_codegen_gcc/build_system/asm-tester/Cargo.lock b/compiler/rustc_codegen_gcc/build_system/asm-tester/Cargo.lock new file mode 100644 index 0000000000000..9ad96acfda407 --- /dev/null +++ b/compiler/rustc_codegen_gcc/build_system/asm-tester/Cargo.lock @@ -0,0 +1,507 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "asm-tester" +version = "0.1.0" +dependencies = [ + "compiletest_rs", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "compiletest_rs" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f150fe9105fcd2a57cad53f0c079a24de65195903ef670990f5909f695eac04c" +dependencies = [ + "diff", + "filetime", + "getopts", + "lazy_static", + "libc", + "log", + "miow", + "regex", + "rustfix", + "serde", + "serde_derive", + "serde_json", + "tester", + "windows-sys 0.59.0", +] + +[[package]] +name = "diff" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" + +[[package]] +name = "dirs-next" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1" +dependencies = [ + "cfg-if", + "dirs-sys-next", +] + +[[package]] +name = "dirs-sys-next" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" +dependencies = [ + "libc", + "redox_users", + "winapi", +] + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "getopts" +version = "0.2.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libredox" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652" +dependencies = [ + "libc", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "memchr" +version = "2.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" + +[[package]] +name = "miow" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "536bfad37a309d62069485248eeaba1e8d9853aaf951caaeaed0585a95346f08" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom", + "libredox", + "thiserror", +] + +[[package]] +name = "regex" +version = "1.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustfix" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82fa69b198d894d84e23afde8e9ab2af4400b2cba20d6bf2b428a8b01c222c5a" +dependencies = [ + "serde", + "serde_json", + "thiserror", + "tracing", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.150" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "term" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59df8ac95d96ff9bede18eb7300b0fda5e5d8d90960e76f8e14ae765eedbf1f" +dependencies = [ + "dirs-next", + "rustversion", + "winapi", +] + +[[package]] +name = "tester" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89e8bf7e0eb2dd7b4228cc1b6821fc5114cd6841ae59f652a85488c016091e5f" +dependencies = [ + "cfg-if", + "getopts", + "libc", + "num_cpus", + "term", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/compiler/rustc_codegen_gcc/build_system/asm-tester/Cargo.toml b/compiler/rustc_codegen_gcc/build_system/asm-tester/Cargo.toml new file mode 100644 index 0000000000000..eeefe61bdc75b --- /dev/null +++ b/compiler/rustc_codegen_gcc/build_system/asm-tester/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "asm-tester" +version = "0.1.0" +edition = "2024" + +[dependencies] +compiletest_rs = "0.11.2" + +[[bin]] +name = "asm-tester" +path = "src/main.rs" + +[workspace] diff --git a/compiler/rustc_codegen_gcc/build_system/asm-tester/src/main.rs b/compiler/rustc_codegen_gcc/build_system/asm-tester/src/main.rs new file mode 100644 index 0000000000000..00ee4ac936520 --- /dev/null +++ b/compiler/rustc_codegen_gcc/build_system/asm-tester/src/main.rs @@ -0,0 +1,66 @@ +use std::path::PathBuf; + +#[derive(Default)] +struct Config { + llvm_filecheck: Option, + filters: Vec, + rustc_flags: Vec, +} + +impl Config { + fn new() -> Result { + // We skip the program's name. + let mut args = std::env::args().skip(1); + let mut config = Self::default(); + + while let Some(arg) = args.next() { + match arg.as_str() { + "--llvm-filecheck" => { + config.llvm_filecheck = args.next().map(PathBuf::from); + } + "--filter" => { + if let Some(arg) = args.next() { + config.filters.push(arg); + } + } + "--" => { + config.rustc_flags.extend(&mut args); + // Nothing else to be read but the `break` makes it more clear. + break; + } + arg => return Err(format!("Unknown argument {arg:?}")), + } + } + if config.llvm_filecheck.is_none() { + Err("Missing `--llvm-filecheck` option".to_owned()) + } else if config.rustc_flags.is_empty() { + Err("Missing rustc flags (passed after `--`)".to_owned()) + } else { + Ok(config) + } + } +} + +fn main() { + let Config { llvm_filecheck, filters, rustc_flags } = match Config::new() { + Ok(c) => c, + Err(error) => { + eprintln!("{error}"); + std::process::exit(1); + } + }; + + let mut test_config = compiletest_rs::Config::default(); + + test_config.mode = compiletest_rs::common::Mode::Assembly; + test_config.src_base = PathBuf::from("tests/asm"); + test_config.llvm_filecheck = llvm_filecheck; + test_config.filters = filters; + test_config.strict_headers = true; + test_config.build_base = PathBuf::from("build/tests/asm"); + test_config.target_rustcflags = Some(rustc_flags.join(" ")); + test_config.link_deps(); + test_config.clean_rmeta(); + + compiletest_rs::run_tests(&test_config) +} diff --git a/compiler/rustc_codegen_gcc/build_system/src/build.rs b/compiler/rustc_codegen_gcc/build_system/src/build.rs index 839c762fed742..e570a3f16c39e 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/build.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/build.rs @@ -227,7 +227,7 @@ fn build_codegen(args: &mut BuildArg) -> Result<(), String> { } run_command_with_output_and_env(&command, None, Some(&env))?; - args.config_info.setup(&mut env, false)?; + args.config_info.setup(&mut env, false, true)?; // We voluntarily ignore the error. let _ = fs::remove_dir_all("target/out"); diff --git a/compiler/rustc_codegen_gcc/build_system/src/clean.rs b/compiler/rustc_codegen_gcc/build_system/src/clean.rs index 43f01fdf35ecb..ec2092ee92ef5 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/clean.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/clean.rs @@ -74,7 +74,8 @@ fn clean_ui_tests() -> Result<(), String> { let path = Path::new(crate::BUILD_DIR) .join("rust/build/x86_64-unknown-linux-gnu/test/") .join(directory); - run_command(&[&"find", &path, &"-name", &"stamp", &"-delete"], None)?; + // The directory might not exist, so ignore the error. + let _ = run_command(&[&"find", &path, &"-name", &"stamp", &"-delete"], None); } Ok(()) } diff --git a/compiler/rustc_codegen_gcc/build_system/src/clippy.rs b/compiler/rustc_codegen_gcc/build_system/src/clippy.rs new file mode 100644 index 0000000000000..813d4b9141e1c --- /dev/null +++ b/compiler/rustc_codegen_gcc/build_system/src/clippy.rs @@ -0,0 +1,62 @@ +use std::path::Path; + +use crate::utils::{run_command_with_output, run_tool_and_install_it_if_not_present}; + +fn show_usage() { + println!( + r#" +`clippy` command help: + + --help : Show this help"# + ); +} + +pub fn run() -> Result<(), String> { + // We skip binary name and the `info` command. + let args = std::env::args().skip(2); + #[allow(clippy::never_loop)] + for arg in args { + match arg.as_str() { + "--help" => { + show_usage(); + return Ok(()); + } + _ => return Err(format!("Unknown option {arg}")), + } + } + + run_tool_and_install_it_if_not_present(&[ + &"cargo", + &"clippy", + &"--all-targets", + &"--", + &"-D", + &"warnings", + ])?; + run_command_with_output( + &[ + &"cargo", + &"clippy", + &"--all-targets", + &"--no-default-features", + &"--", + &"-D", + &"warnings", + ], + Some(Path::new(".")), + )?; + run_command_with_output( + &[ + &"cargo", + &"clippy", + &"--all-targets", + &"--manifest-path", + &"build_system/Cargo.toml", + &"--", + &"-D", + &"warnings", + ], + Some(Path::new(".")), + )?; + Ok(()) +} diff --git a/compiler/rustc_codegen_gcc/build_system/src/config.rs b/compiler/rustc_codegen_gcc/build_system/src/config.rs index 8eb6d8f019e1c..fd78f691d1657 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/config.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/config.rs @@ -314,6 +314,7 @@ impl ConfigInfo { &mut self, env: &mut HashMap, use_system_gcc: bool, + generate_out_dir: bool, ) -> Result<(), String> { env.insert("CARGO_INCREMENTAL".to_string(), "0".to_string()); @@ -444,12 +445,12 @@ impl ConfigInfo { self.rustc_command = vec![rustc]; self.rustc_command.extend_from_slice(&rustflags); - self.rustc_command.extend_from_slice(&[ - "-L".to_string(), - format!("crate={}", self.cargo_target_dir), - "--out-dir".to_string(), - self.cargo_target_dir.clone(), - ]); + self.rustc_command + .extend_from_slice(&["-L".to_string(), format!("crate={}", self.cargo_target_dir)]); + if generate_out_dir { + self.rustc_command + .extend_from_slice(&["--out-dir".to_string(), self.cargo_target_dir.clone()]); + } if !env.contains_key("RUSTC_LOG") { env.insert("RUSTC_LOG".to_string(), "warn".to_string()); diff --git a/compiler/rustc_codegen_gcc/build_system/src/fmt.rs b/compiler/rustc_codegen_gcc/build_system/src/fmt.rs index 91535f217e351..dc1ca1d3e82ae 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/fmt.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/fmt.rs @@ -1,7 +1,7 @@ use std::ffi::OsStr; use std::path::Path; -use crate::utils::{run_command_with_output, walk_dir}; +use crate::utils::{run_command_with_output, run_tool_and_install_it_if_not_present, walk_dir}; fn show_usage() { println!( @@ -31,8 +31,9 @@ pub fn run() -> Result<(), String> { let cmd: &[&dyn AsRef] = if check { &[&"cargo", &"fmt", &"--check"] } else { &[&"cargo", &"fmt"] }; - run_command_with_output(cmd, Some(Path::new(".")))?; + run_tool_and_install_it_if_not_present(cmd)?; run_command_with_output(cmd, Some(Path::new("build_system")))?; + run_command_with_output(cmd, Some(Path::new("build_system/asm-tester")))?; run_rustfmt_recursively("tests/run", check) } diff --git a/compiler/rustc_codegen_gcc/build_system/src/main.rs b/compiler/rustc_codegen_gcc/build_system/src/main.rs index ae975c94fff25..83f07a758d659 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/main.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/main.rs @@ -3,6 +3,7 @@ use std::{env, process}; mod abi_test; mod build; mod clean; +mod clippy; mod clone_gcc; mod config; mod fmt; @@ -12,6 +13,7 @@ mod prepare; mod rust_tools; mod rustc_info; mod test; +mod todo; mod utils; const BUILD_DIR: &str = "build"; @@ -24,43 +26,67 @@ macro_rules! arg_error { }}; } -fn usage() { - println!( - "\ +macro_rules! commands_decl { + ($($variant:ident: $doc_name:literal => $doc:literal ,)+) => { + enum Command { + $($variant),+ + } + + impl<'a> From> for Command { + fn from(arg: Option<&'a str>) -> Self { + match arg { + $(Some($doc_name) => Self::$variant,)+ + Some("--help") => { + usage(); + process::exit(0); + } + Some(flag) if flag.starts_with('-') => arg_error!("Expected command found flag {}", flag), + Some(command) => arg_error!("Unknown command {}", command), + None => { + usage(); + process::exit(0); + } + } + } + } + + fn usage() { + println!("\ rustc_codegen_gcc build system Usage: build_system [command] [options] Options: - --help : Displays this help message. + --help : Displays this help message. + +Commands:", + ); + let mut commands = vec![$(($doc_name, $doc),)+]; + let longest = commands.iter().map(|(name, _)| name.len()).max().unwrap(); -Commands: - cargo : Executes a cargo command. - rustc : Compiles the program using the GCC compiler. - clean : Cleans the build directory, removing all compiled files and artifacts. - prepare : Prepares the environment for building, including fetching dependencies and setting up configurations. - build : Compiles the project. - test : Runs tests for the project. - info : Displays information about the build environment and project configuration. - clone-gcc : Clones the GCC compiler from a specified source. - fmt : Runs rustfmt - fuzz : Fuzzes `cg_gcc` using rustlantis - abi-test : Runs the abi-cafe test suite on the codegen, checking for ABI compatibility with LLVM" - ); + commands.sort_unstable_by(|a, b| a.0.cmp(b.0)); + for (name, doc) in commands { + let spacing = std::iter::repeat(' ').take(longest - name.len() + 1).collect::(); + eprintln!(" {name}{spacing}: {doc}."); + } + } + } } -pub enum Command { - Cargo, - Clean, - CloneGcc, - Prepare, - Build, - Rustc, - Test, - Info, - Fmt, - Fuzz, - AbiTest, +commands_decl! { + Cargo: "cargo" => "Executes a cargo command", + Clean: "clean" => "Cleans the build directory, removing all compiled files and artifacts", + Clippy: "clippy" => "Runs clippy", + CloneGcc: "clone-gcc" => "Clones the GCC compiler from a specified source", + Prepare: "prepare" => "Prepares the environment for building, including fetching dependencies and setting up configurations", + Build: "build" => "Compiles the project", + Rustc: "rustc" => "Compiles the program using the GCC compiler", + Test: "test" => "Runs tests for the project", + Info: "info" => "Displays information about the build environment and project configuration", + Fmt: "fmt" => "Runs rustfmt", + Fuzz: "fuzz" => "Fuzzes `cg_gcc` using `rustlantis`", + AbiTest: "abi-test" => "Runs the abi-cafe test suite on the codegen, checking for ABI compatibility with LLVM", + CheckTodo: "check-todo" => "Checks todo in the project", } fn main() { @@ -70,31 +96,7 @@ fn main() { } } - let command = match env::args().nth(1).as_deref() { - Some("cargo") => Command::Cargo, - Some("rustc") => Command::Rustc, - Some("clean") => Command::Clean, - Some("prepare") => Command::Prepare, - Some("build") => Command::Build, - Some("test") => Command::Test, - Some("info") => Command::Info, - Some("clone-gcc") => Command::CloneGcc, - Some("abi-test") => Command::AbiTest, - Some("fmt") => Command::Fmt, - Some("fuzz") => Command::Fuzz, - Some("--help") => { - usage(); - process::exit(0); - } - Some(flag) if flag.starts_with('-') => arg_error!("Expected command found flag {}", flag), - Some(command) => arg_error!("Unknown command {}", command), - None => { - usage(); - process::exit(0); - } - }; - - if let Err(e) = match command { + if let Err(e) = match Command::from(env::args().nth(1).as_deref()) { Command::Cargo => rust_tools::run_cargo(), Command::Rustc => rust_tools::run_rustc(), Command::Clean => clean::run(), @@ -106,6 +108,8 @@ fn main() { Command::Fmt => fmt::run(), Command::Fuzz => fuzz::run(), Command::AbiTest => abi_test::run(), + Command::Clippy => clippy::run(), + Command::CheckTodo => todo::run(), } { eprintln!("Command failed to run: {e}"); process::exit(1); diff --git a/compiler/rustc_codegen_gcc/build_system/src/rust_tools.rs b/compiler/rustc_codegen_gcc/build_system/src/rust_tools.rs index b1faa27acc4a2..1b50f11c3d324 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/rust_tools.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/rust_tools.rs @@ -72,7 +72,7 @@ impl RustcTools { let mut env: HashMap = std::env::vars().collect(); let mut config = ConfigInfo::default(); - config.setup(&mut env, false)?; + config.setup(&mut env, false, false)?; let toolchain = get_toolchain()?; let toolchain_version = rustc_toolchain_version_info(&toolchain)?; diff --git a/compiler/rustc_codegen_gcc/build_system/src/test.rs b/compiler/rustc_codegen_gcc/build_system/src/test.rs index 2475a3a6a7155..6cc2282c8022f 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/test.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/test.rs @@ -9,8 +9,8 @@ use crate::build; use crate::config::{Channel, ConfigInfo}; use crate::utils::{ create_dir, get_sysroot_dir, get_toolchain, git_clone, git_clone_root_dir, remove_file, - run_command, run_command_with_env, run_command_with_output_and_env, rustc_version_info, - split_args, walk_dir, + run_command, run_command_with_env, run_command_with_output_and_env, + run_command_with_output_and_env_no_err, rustc_version_info, split_args, walk_dir, }; type Env = HashMap; @@ -28,8 +28,10 @@ fn get_runners() -> Runners { ("Run failing ui pattern tests", test_failing_ui_pattern_tests), ); runners.insert("--test-failing-rustc", ("Run failing rustc tests", test_failing_rustc)); + runners.insert("--run-ui-tests", ("Run specified rustc UI tests", run_ui_tests)); runners.insert("--projects", ("Run the tests of popular crates", test_projects)); runners.insert("--test-libcore", ("Run libcore tests", test_libcore)); + runners.insert("--alloc-tests", ("Run alloc tests", test_alloc)); runners.insert("--clean", ("Empty cargo target directory", clean)); runners.insert("--build-sysroot", ("Build sysroot", build_sysroot)); runners.insert("--std-tests", ("Run std tests", std_tests)); @@ -42,8 +44,10 @@ fn get_runners() -> Runners { ); runners.insert("--extended-regex-tests", ("Run extended regex tests", extended_regex_tests)); runners.insert("--mini-tests", ("Run mini tests", mini_tests)); + runners.insert("--gcc-asm-tests", ("Run cg_gcc asm tests", test_asm)); runners.insert("--cargo-tests", ("Run cargo tests", cargo_tests)); runners.insert("--no-builtins-tests", ("Test #![no_builtins] attribute", no_builtins_tests)); + runners.insert("--stdarch-tests", ("Run stdarch tests", test_stdarch as Runner)); runners } @@ -505,6 +509,26 @@ fn std_tests(env: &Env, args: &TestArg) -> Result<(), String> { Ok(()) } +fn get_llvm_filecheck(env: &Env) -> Result { + match run_command_with_env( + &[ + &"bash", + &"-c", + &"which FileCheck-10 || \ + which FileCheck-11 || \ + which FileCheck-12 || \ + which FileCheck-13 || \ + which FileCheck-14 || \ + which FileCheck", + ], + None, + Some(env), + ) { + Ok(cmd) => Ok(String::from_utf8_lossy(&cmd.stdout).trim().to_string()), + Err(_) => Err("Failed to retrieve LLVM FileCheck, ignoring...".to_owned()), + } +} + fn setup_rustc(env: &mut Env, args: &TestArg) -> Result { let toolchain = format!( "+{channel}-{host}", @@ -548,23 +572,10 @@ fn setup_rustc(env: &mut Env, args: &TestArg) -> Result { let rustc = rustc.trim().to_owned(); if rustc.is_empty() { Err("`rustc` path is empty".to_string()) } else { Ok(rustc) } })?; - let llvm_filecheck = match run_command_with_env( - &[ - &"bash", - &"-c", - &"which FileCheck-10 || \ - which FileCheck-11 || \ - which FileCheck-12 || \ - which FileCheck-13 || \ - which FileCheck-14 || \ - which FileCheck", - ], - rust_dir, - Some(env), - ) { - Ok(cmd) => String::from_utf8_lossy(&cmd.stdout).to_string(), - Err(_) => { - eprintln!("Failed to retrieve LLVM FileCheck, ignoring..."); + let llvm_filecheck = match get_llvm_filecheck(env) { + Ok(l) => l, + Err(error) => { + eprintln!("{error}"); // FIXME: the test tests/run-make/no-builtins-attribute will fail if we cannot find // FileCheck. String::new() @@ -634,7 +645,7 @@ fn asm_tests(env: &Env, args: &TestArg) -> Result<(), String> { &"0", &"--set", &"build.compiletest-allow-stage0=true", - &"tests/assembly-llvm/asm", + &"tests/assembly-gcc/asm", &"--compiletest-rustc-args", &rustc_args, ], @@ -764,6 +775,39 @@ fn test_libcore(env: &Env, args: &TestArg) -> Result<(), String> { Ok(()) } +fn test_stdarch(env: &Env, args: &TestArg) -> Result<(), String> { + println!("[TEST] stdarch"); + let manifest_path = get_sysroot_dir().join("sysroot_src/library/stdarch/Cargo.toml"); + let mut env = env.clone(); + + // `config.setup` already baked `CG_RUSTFLAGS` into `RUSTFLAGS`, so append the lint-allow to + // `RUSTFLAGS` directly (which `run_cargo_command` also propagates to `RUSTDOCFLAGS`). + let rustflags = env.get("RUSTFLAGS").cloned().unwrap_or_default(); + env.insert( + "RUSTFLAGS".to_string(), + format!("{rustflags} -Ainternal_features").trim().to_owned(), + ); + env.insert("TARGET".to_string(), args.config_info.target_triple.clone()); + + let mut command: Vec<&dyn AsRef> = + vec![&"test", &"--manifest-path", &manifest_path, &"--"]; + for test_name in &args.test_args { + command.push(test_name); + } + run_cargo_command(&command, None, &env, args)?; + Ok(()) +} + +fn test_alloc(env: &Env, args: &TestArg) -> Result<(), String> { + // FIXME: create a function "display_if_not_quiet" or something along the line. + println!("[TEST] alloc"); + let path = get_sysroot_dir().join("sysroot_src/library/alloctests"); + let _ = remove_dir_all(path.join("target")); + // FIXME(antoyo): run in release mode when we fix the failures. + run_cargo_command(&[&"test"], Some(&path), env, args)?; + Ok(()) +} + fn extended_rand_tests(env: &Env, args: &TestArg) -> Result<(), String> { if !args.is_using_gcc_master_branch() { println!("Not using GCC master branch. Skipping `extended_rand_tests`."); @@ -908,7 +952,6 @@ fn contains_ui_error_patterns(file_path: &Path, keep_lto_tests: bool) -> Result< "//@ known-bug", "-Cllvm-args", "//~", - "thread", ] .iter() .any(|check| line.contains(check)) @@ -985,21 +1028,6 @@ where true, )?; } else { - walk_dir( - rust_path.join("tests/ui"), - &mut |dir| { - let dir_name = dir.file_name().and_then(|name| name.to_str()).unwrap_or(""); - if ["abi", "extern", "proc-macro", "threads-sendsync"].contains(&dir_name) { - remove_dir_all(dir).map_err(|error| { - format!("Failed to remove folder `{}`: {:?}", dir.display(), error) - })?; - } - Ok(()) - }, - &mut |_| Ok(()), - false, - )?; - // These two functions are used to remove files that are known to not be working currently // with the GCC backend to reduce noise. fn dir_handling(keep_lto_tests: bool) -> impl Fn(&Path) -> Result<(), String> { @@ -1196,6 +1224,46 @@ fn test_failing_ui_pattern_tests(env: &Env, args: &TestArg) -> Result<(), String ) } +fn run_ui_tests(env: &Env, args: &TestArg) -> Result<(), String> { + let mut env = env.clone(); + let rust_path = setup_rustc(&mut env, args)?; + + let extra = + if args.is_using_gcc_master_branch() { "" } else { " -Csymbol-mangling-version=v0" }; + + let rustc_args = format!( + "{test_flags} -Zcodegen-backend={backend} --sysroot {sysroot}{extra}", + test_flags = env.get("TEST_FLAGS").unwrap_or(&String::new()), + backend = args.config_info.cg_backend_path, + sysroot = args.config_info.sysroot_path, + extra = extra, + ); + + env.get_mut("RUSTFLAGS").unwrap().clear(); + + let mut command: Vec<&dyn AsRef> = vec![ + &"./x.py", + &"test", + &"--run", + &"always", + &"--stage", + &"0", + &"--set", + &"build.compiletest-allow-stage0=true", + &"--compiletest-rustc-args", + &rustc_args, + &"--bypass-ignore-backends", + &"--force-rerun", + ]; + + for test_name in &args.test_args { + command.push(test_name); + } + + run_command_with_output_and_env(&command, Some(&rust_path), Some(&env))?; + Ok(()) +} + fn retain_files_callback<'a>( file_path: &'a str, test_type: &'a str, @@ -1297,6 +1365,60 @@ fn remove_files_callback<'a>( } } +fn test_asm(env: &Env, args: &TestArg) -> Result<(), String> { + fn is_path_time_more_recent(ref_time: std::time::SystemTime, path: &str) -> bool { + std::fs::metadata(path) + .and_then(|metadata| metadata.modified()) + .is_ok_and(|time| ref_time < time) + } + + // FIXME: create a function "display_if_not_quiet" or something along the line. + println!("[TEST] cg_gcc assembly"); + let llvm_filecheck = get_llvm_filecheck(env)?; + + let target_dir = std::env::current_dir().unwrap().join("build_system/asm-tester/target"); + + // All this code is because `cargo` keeps recompiling this file, and we can't figure out why. + let binary_file_path = "build_system/asm-tester/target/debug/asm-tester"; + let mut need_recompilation = true; + if let Ok(metadata) = std::fs::metadata(binary_file_path) + && let Ok(ref_time) = metadata.modified() + && !is_path_time_more_recent(ref_time, "build_system/asm-tester/Cargo.toml") + && !is_path_time_more_recent(ref_time, "build_system/asm-tester/Cargo.lock") + && !is_path_time_more_recent(ref_time, "build_system/asm-tester/src/main.rs") + { + need_recompilation = false; + } + + if need_recompilation { + let build_asm_args: Vec<&dyn AsRef> = vec![ + &"cargo", + &"build", + &"--manifest-path", + &"build_system/asm-tester/Cargo.toml", + &"--target-dir", + &target_dir, + &"--", + ]; + run_command_with_output_and_env_no_err(&build_asm_args, Some(Path::new(".")), Some(env))?; + } + + let mut test_asm_args: Vec<&dyn AsRef> = vec![ + &"build_system/asm-tester/target/debug/asm-tester", + &"--llvm-filecheck", + &llvm_filecheck, + ]; + for test_arg in &args.test_args { + test_asm_args.push(&"--filter"); + test_asm_args.push(test_arg); + } + test_asm_args.push(&"--"); + for arg in args.config_info.rustc_command_vec().into_iter().skip(1) { + test_asm_args.push(arg); + } + run_command_with_output_and_env_no_err(&test_asm_args, Some(Path::new(".")), Some(env)) +} + fn run_all(env: &Env, args: &TestArg) -> Result<(), String> { clean(env, args)?; mini_tests(env, args)?; @@ -1308,6 +1430,7 @@ fn run_all(env: &Env, args: &TestArg) -> Result<(), String> { cargo_tests(env, args)?; no_builtins_tests(env, args)?; test_rustc(env, args)?; + test_asm(env, args)?; Ok(()) } @@ -1329,7 +1452,7 @@ pub fn run() -> Result<(), String> { return Ok(()); } - args.config_info.setup(&mut env, args.use_system_gcc)?; + args.config_info.setup(&mut env, args.use_system_gcc, true)?; if args.runners.is_empty() { run_all(&env, &args)?; diff --git a/compiler/rustc_codegen_gcc/build_system/src/todo.rs b/compiler/rustc_codegen_gcc/build_system/src/todo.rs new file mode 100644 index 0000000000000..5b89410844788 --- /dev/null +++ b/compiler/rustc_codegen_gcc/build_system/src/todo.rs @@ -0,0 +1,72 @@ +use std::ffi::OsStr; +use std::fs::File; +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +const EXTENSIONS: &[&str] = + &["rs", "py", "js", "sh", "c", "cpp", "h", "md", "css", "ftl", "toml", "yml", "yaml"]; + +fn has_supported_extension(path: &Path) -> bool { + path.extension().is_some_and(|ext| EXTENSIONS.iter().any(|e| ext == OsStr::new(e))) +} + +fn list_tracked_files() -> Result, String> { + let output = Command::new("git") + .args(["ls-files", "-z"]) + .output() + .map_err(|e| format!("Failed to run `git ls-files`: {e}"))?; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(format!("`git ls-files` failed: {stderr}")); + } + + let mut files = Vec::new(); + for entry in output.stdout.split(|b| *b == 0) { + if entry.is_empty() { + continue; + } + let path = std::str::from_utf8(entry).unwrap(); + files.push(PathBuf::from(path)); + } + + Ok(files) +} + +pub(crate) fn run() -> Result<(), String> { + let files = list_tracked_files()?; + let mut error_count = 0; + // Avoid embedding the task marker in source so greps only find real occurrences. + let todo_marker = "todo".to_ascii_uppercase(); + + for file in files { + if !has_supported_extension(&file) { + continue; + } + + let file_handle = + File::open(&file).map_err(|e| format!("Failed to open {}: {e}", file.display()))?; + let reader = BufReader::new(file_handle); + + for (i, line) in reader.lines().enumerate() { + let line = line.map_err(|e| format!("Failed to read {}: {e}", file.display()))?; + let trimmed = line.trim(); + if trimmed.contains(&todo_marker) { + eprintln!( + "{}:{}: {} is used for tasks that should be done before merging a PR; if you want to leave a message in the codebase use FIXME", + file.display(), + i + 1, + todo_marker + ); + error_count += 1; + } + } + } + + if error_count == 0 { + return Ok(()); + } + + Err(format!("found {} {}(s)", error_count, todo_marker)) +} diff --git a/compiler/rustc_codegen_gcc/build_system/src/utils.rs b/compiler/rustc_codegen_gcc/build_system/src/utils.rs index 112322f8688c1..4c67156a85fb2 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/utils.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/utils.rs @@ -2,10 +2,11 @@ use std::collections::HashMap; use std::ffi::OsStr; use std::fmt::Debug; use std::fs; +use std::io::{BufReader, Read}; #[cfg(unix)] use std::os::unix::process::ExitStatusExt; use std::path::{Path, PathBuf}; -use std::process::{Command, ExitStatus, Output}; +use std::process::{Command, ExitStatus, Output, Stdio}; fn exec_command( input: &[&dyn AsRef], @@ -47,7 +48,7 @@ pub(crate) fn get_command_inner( command } -fn check_exit_status( +pub(crate) fn check_exit_status( input: &[&dyn AsRef], cwd: Option<&Path>, exit_status: ExitStatus, @@ -115,6 +116,30 @@ pub fn run_command_with_output( check_exit_status(input, cwd, exit_status, None, true) } +pub fn run_command_with_output_and_get_it( + input: &[&dyn AsRef], + cwd: Option<&Path>, +) -> Result<(ExitStatus, String), String> { + let mut child = get_command_inner(input, cwd, None) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| command_error(input, &cwd, e))?; + + let stderr = child.stderr.take().expect("Failed to capture stderr"); + let mut captured = String::new(); + BufReader::new(stderr).read_to_string(&mut captured).expect("failed to read stderr"); + + let status = child.wait().map_err(|e| command_error(input, &cwd, e))?; + #[cfg(unix)] + { + if let Some(signal) = status.signal() { + // In case the signal didn't kill the current process. + return Err(command_error(input, &cwd, format!("Process received signal {signal}"))); + } + } + Ok((status, captured)) +} + pub fn run_command_with_output_and_env( input: &[&dyn AsRef], cwd: Option<&Path>, @@ -124,7 +149,6 @@ pub fn run_command_with_output_and_env( check_exit_status(input, cwd, exit_status, None, true) } -#[cfg(not(unix))] pub fn run_command_with_output_and_env_no_err( input: &[&dyn AsRef], cwd: Option<&Path>, @@ -419,6 +443,34 @@ pub fn get_sysroot_dir() -> PathBuf { Path::new(crate::BUILD_DIR).join("build_sysroot") } +pub fn run_tool_and_install_it_if_not_present(cmd: &[&dyn AsRef]) -> Result<(), String> { + let (exit_status, stderr) = run_command_with_output_and_get_it(cmd, Some(Path::new(".")))?; + if exit_status.success() { + return Ok(()); + } + let mut iter = stderr.split('\n'); + if let Some(line) = iter.next() + && line.contains("is not installed for the toolchain") + && let Some(line) = iter.next() + && line.contains("run `rustup component add") + && let Some(cmd) = line.split('`').nth(1) + && let Some(tool_name) = cmd.rsplit(' ').next() + { + println!("`{tool_name}` is not installed for this toolchain, installing it..."); + // A weird round-about way to get a `&&str` so I can get a `&dyn AsRef` but + // as long as it works... + let cmd = cmd.split(' ').collect::>(); + let cmd = cmd.iter().map(|s: &&str| s as &dyn AsRef).collect::>(); + run_command_with_output(cmd.as_slice(), Some(Path::new(".")))?; + } else { + // If the component is installed, then it's something else. In this case we fail like we + // should have and let the user handles the error. + return check_exit_status(cmd, Some(Path::new(".")), exit_status, None, true); + } + // We retry the command... + run_command_with_output(cmd, Some(Path::new("."))) +} + #[cfg(test)] mod tests { use super::*; diff --git a/compiler/rustc_codegen_gcc/doc/subtree.md b/compiler/rustc_codegen_gcc/doc/subtree.md index a81b6c9c74bdd..fcac399e46542 100644 --- a/compiler/rustc_codegen_gcc/doc/subtree.md +++ b/compiler/rustc_codegen_gcc/doc/subtree.md @@ -1,7 +1,7 @@ # git subtree sync `rustc_codegen_gcc` is a subtree of the rust compiler. As such, it needs to be -sync from time to time to ensure changes that happened on their side are also +synced from time to time to ensure changes that happened on their side are also included on our side. ### How to install a forked git-subtree @@ -41,6 +41,8 @@ cd ../rust git pull origin master git checkout -b subtree-update_cg_gcc_YYYY-MM-DD PATH="$HOME/bin:$PATH" ~/bin/git-subtree pull --prefix=compiler/rustc_codegen_gcc/ https://github.com/rust-lang/rustc_codegen_gcc.git master +# Don't forget to update the `gcc` submodule to the same version as the +# one in `rustc_codegen_gcc/libgccjit.version`. git push # Immediately merge the merge commit into cg_gcc to prevent merge conflicts when syncing from rust-lang/rust later. diff --git a/compiler/rustc_codegen_gcc/libgccjit.version b/compiler/rustc_codegen_gcc/libgccjit.version index 5eef70260466f..7c141c20c4d3d 100644 --- a/compiler/rustc_codegen_gcc/libgccjit.version +++ b/compiler/rustc_codegen_gcc/libgccjit.version @@ -1 +1 @@ -6f155cc3f5a2dff33afe6cc3ed6c2e0e605ae6a3 +dfbee712e611693596ffec1de22177089c537491 diff --git a/compiler/rustc_codegen_gcc/patches/0001-Add-stdarch-Cargo.toml-for-testing.patch b/compiler/rustc_codegen_gcc/patches/0001-Add-stdarch-Cargo.toml-for-testing.patch deleted file mode 100644 index 3a8c37a8b8d9a..0000000000000 --- a/compiler/rustc_codegen_gcc/patches/0001-Add-stdarch-Cargo.toml-for-testing.patch +++ /dev/null @@ -1,39 +0,0 @@ -From 190e26c9274b3c93a9ee3516b395590e6bd9213b Mon Sep 17 00:00:00 2001 -From: None -Date: Sun, 3 Aug 2025 19:54:56 -0400 -Subject: [PATCH] Patch 0001-Add-stdarch-Cargo.toml-for-testing.patch - ---- - library/stdarch/Cargo.toml | 20 ++++++++++++++++++++ - 1 file changed, 20 insertions(+) - create mode 100644 library/stdarch/Cargo.toml - -diff --git a/library/stdarch/Cargo.toml b/library/stdarch/Cargo.toml -new file mode 100644 -index 0000000..bd6725c ---- /dev/null -+++ b/library/stdarch/Cargo.toml -@@ -0,0 +1,20 @@ -+[workspace] -+resolver = "1" -+members = [ -+ "crates/*", -+ #"examples/" -+] -+exclude = [ -+ "crates/wasm-assert-instr-tests", -+ "rust_programs", -+] -+ -+[profile.release] -+debug = true -+opt-level = 3 -+incremental = true -+ -+[profile.bench] -+debug = 1 -+opt-level = 3 -+incremental = true --- -2.50.1 - diff --git a/compiler/rustc_codegen_gcc/rust-toolchain b/compiler/rustc_codegen_gcc/rust-toolchain index 56fcfdff1c719..104992b5da46b 100644 --- a/compiler/rustc_codegen_gcc/rust-toolchain +++ b/compiler/rustc_codegen_gcc/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2026-04-29" +channel = "nightly-2026-07-24" components = ["rust-src", "rustc-dev", "llvm-tools-preview"] diff --git a/compiler/rustc_codegen_gcc/src/abi.rs b/compiler/rustc_codegen_gcc/src/abi.rs index 1b7bb8c907735..45fc5e3c4f619 100644 --- a/compiler/rustc_codegen_gcc/src/abi.rs +++ b/compiler/rustc_codegen_gcc/src/abi.rs @@ -146,12 +146,23 @@ impl<'gcc, 'tcx> FnAbiGccExt<'gcc, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { if attrs.regular.contains(rustc_target::callconv::ArgAttribute::NonNull) { non_null_args.push(arg_index as i32 + 1); } + // There are a few others `ArgAttribute` variants" + // + // * ArgAttribute::ReadOnly: `access(read_only())`, but it's only used for emitting + // warning, not for optimization. + // * ArgAttribute::NoUndef: No equivalent in GCC + // * ArgAttribute::Writable: `access(read_write())` or `access(write_only())`, but it's + // only used for emitting warning, not for optimization. + // * ArgAttribute::NoFree: No equivalent in GCC ty }; #[cfg(not(feature = "master"))] let apply_attrs = |ty: Type<'gcc>, _attrs: &ArgAttributes, _arg_index: usize| ty; - for arg in self.args.iter() { + for (source_arg_index, arg) in self.args.iter().enumerate() { + #[cfg(not(feature = "master"))] + let _ = source_arg_index; + let arg_ty = match arg.mode { PassMode::Ignore => continue, PassMode::Pair(a, b) => { @@ -177,9 +188,31 @@ impl<'gcc, 'tcx> FnAbiGccExt<'gcc, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { apply_attrs(ty, &cast.attrs, argument_tys.len()) } PassMode::Indirect { attrs: _, meta_attrs: None, on_stack: true } => { - // This is a "byval" argument, so we don't apply the `restrict` attribute on it. - on_stack_param_indices.insert(argument_tys.len()); - arg.layout.gcc_type(cx) + let x86_interrupt_first_arg = { + #[cfg(feature = "master")] + { + source_arg_index == 0 + && matches!(self.conv, CanonAbi::Interrupt(InterruptKind::X86)) + } + #[cfg(not(feature = "master"))] + { + false + } + }; + + if x86_interrupt_first_arg { + // Rust lowers the first `x86-interrupt` argument as a byval stack slot. + // LLVM represents that as a pointer parameter with `byval`; GCC's + // interrupt attribute likewise requires a pointer-shaped first parameter. + // Do not add this parameter to `on_stack_param_indices`: that set is only + // needed when GCC represents a byval argument as a value parameter, while + // this parameter is already pointer-shaped. + cx.type_ptr_to(arg.layout.gcc_type(cx)) + } else { + // This is a "byval" argument, so we don't apply the `restrict` attribute on it. + on_stack_param_indices.insert(argument_tys.len()); + arg.layout.gcc_type(cx) + } } PassMode::Direct(attrs) => { apply_attrs(arg.layout.immediate_gcc_type(cx), &attrs, argument_tys.len()) diff --git a/compiler/rustc_codegen_gcc/src/asm.rs b/compiler/rustc_codegen_gcc/src/asm.rs index ee0cef350b42f..a1d227157314b 100644 --- a/compiler/rustc_codegen_gcc/src/asm.rs +++ b/compiler/rustc_codegen_gcc/src/asm.rs @@ -298,7 +298,9 @@ impl<'a, 'gcc, 'tcx> AsmBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tcx> { out_place, }); - if !readwrite { + if readwrite { + self.llbb().add_assignment(None, tmp_var, in_value.immediate()); + } else { let out_gcc_idx = outputs.len() - 1; let constraint = Cow::Owned(out_gcc_idx.to_string()); @@ -364,7 +366,14 @@ impl<'a, 'gcc, 'tcx> AsmBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tcx> { let ty = value.layout.gcc_type(self.cx); let reg_var = self.current_func().new_local(None, ty, "input_register"); reg_var.set_register_name(reg_name); - self.llbb().add_assignment(None, reg_var, value.immediate()); + // FIXME: We should remove this when switching to "untyped" pointers + let value = value.immediate(); + let value = if value.get_type() != ty { + self.context.new_cast(None, value, ty) + } else { + value + }; + self.llbb().add_assignment(None, reg_var, value); inputs.push(AsmInOperand { constraint: "r".into(), @@ -603,6 +612,12 @@ impl<'a, 'gcc, 'tcx> AsmBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tcx> { self.llbb().add_eval(None, self.context.new_call(None, builtin_unreachable, &[])); } + if !options.contains(InlineAsmOptions::NORETURN) + && let Some(dest) = dest + { + self.switch_to_block(dest); + } + // Write results to outputs. // // We need to do this because: diff --git a/compiler/rustc_codegen_gcc/src/attributes.rs b/compiler/rustc_codegen_gcc/src/attributes.rs index ce1877b308e94..95d12480efa69 100644 --- a/compiler/rustc_codegen_gcc/src/attributes.rs +++ b/compiler/rustc_codegen_gcc/src/attributes.rs @@ -2,6 +2,8 @@ use gccjit::FnAttribute; use gccjit::Function; #[cfg(feature = "master")] +use rustc_abi::{CanonAbi, InterruptKind}; +#[cfg(feature = "master")] use rustc_hir::attrs::InlineAttr; use rustc_hir::attrs::InstructionSetAttr; #[cfg(feature = "master")] @@ -9,6 +11,7 @@ use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; #[cfg(feature = "master")] use rustc_middle::mir::TerminatorKind; use rustc_middle::ty; +use rustc_target::callconv::FnAbi; #[cfg(feature = "master")] use rustc_target::spec::Arch; @@ -82,12 +85,23 @@ fn inline_attr<'gcc, 'tcx>( } } +#[cfg(feature = "master")] +fn is_x86_interrupt<'tcx>(fn_abi: Option<&FnAbi<'tcx, ty::Ty<'tcx>>>) -> bool { + matches!( + fn_abi, + Some(fn_abi) if matches!(fn_abi.conv, CanonAbi::Interrupt(InterruptKind::X86)) + ) +} + /// Composite function which sets GCC attributes for function depending on its AST (`#[attribute]`) /// attributes. pub fn from_fn_attrs<'gcc, 'tcx>( cx: &CodegenCx<'gcc, 'tcx>, #[cfg_attr(not(feature = "master"), expect(unused_variables))] func: Function<'gcc>, instance: ty::Instance<'tcx>, + #[cfg_attr(not(feature = "master"), expect(unused_variables))] fn_abi: Option< + &FnAbi<'tcx, ty::Ty<'tcx>>, + >, ) { let codegen_fn_attrs = cx.tcx.codegen_instance_attrs(instance.def); @@ -120,6 +134,11 @@ pub fn from_fn_attrs<'gcc, 'tcx>( } } + #[cfg(feature = "master")] + let x86_interrupt = is_x86_interrupt(fn_abi); + #[cfg(not(feature = "master"))] + let x86_interrupt = false; + let mut function_features = codegen_fn_attrs .target_features .iter() @@ -135,6 +154,13 @@ pub fn from_fn_attrs<'gcc, 'tcx>( // Check if GCC requires the same. let mut global_features = cx.tcx.global_backend_features(()).iter().map(|s| s.as_str()); function_features.extend(&mut global_features); + if x86_interrupt { + // GCC does not preserve SSE, MMX, or x87 state in interrupt handlers and rejects + // them whenever those instruction sets are enabled, even if the handler does not + // emit such instructions. Restrict the function to general registers so the + // interrupt attribute works with the default x86_64 target features. + function_features.push("general-regs-only"); + } let target_features = function_features .iter() .filter_map(|feature| { diff --git a/compiler/rustc_codegen_gcc/src/back/lto.rs b/compiler/rustc_codegen_gcc/src/back/lto.rs index 98f9abdb05c4c..baf1fda02e258 100644 --- a/compiler/rustc_codegen_gcc/src/back/lto.rs +++ b/compiler/rustc_codegen_gcc/src/back/lto.rs @@ -20,6 +20,7 @@ use std::ffi::CString; use std::fs::{self, File}; use std::path::{Path, PathBuf}; +use std::sync::Arc; use gccjit::OutputKind; use object::read::archive::ArchiveFile; @@ -29,14 +30,15 @@ use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput, SharedEmitter} use rustc_codegen_ssa::traits::*; use rustc_codegen_ssa::{CompiledModule, ModuleCodegen, ModuleKind}; use rustc_data_structures::memmap::Mmap; -use rustc_data_structures::profiling::SelfProfilerRef; use rustc_errors::{DiagCtxt, DiagCtxtHandle}; use rustc_log::tracing::info; +use rustc_session::Session; use tempfile::{TempDir, tempdir}; use crate::back::write::{codegen, save_temp_bitcode}; use crate::diagnostics::LtoBitcodeFromRlib; -use crate::{GccCodegenBackend, GccContext, LtoMode, to_gcc_opt_level}; +use crate::gcc_util::new_context; +use crate::{GccCodegenBackend, GccContext, LtoMode, SyncContext, to_gcc_opt_level}; struct LtoData { // FIXME(antoyo): use symbols_below_threshold. @@ -102,8 +104,8 @@ fn save_as_file(obj: &[u8], path: &Path) -> Result<(), LtoBitcodeFromRlib> { /// Performs fat LTO by merging all modules into a single one and returning it /// for further optimization. pub(crate) fn run_fat( + sess: &Session, cgcx: &CodegenContext, - prof: &SelfProfilerRef, shared_emitter: &SharedEmitter, each_linked_rlib_for_lto: &[PathBuf], modules: Vec>, @@ -114,8 +116,8 @@ pub(crate) fn run_fat( /*let symbols_below_threshold = lto_data.symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::>();*/ fat_lto( + sess, cgcx, - prof, dcx, modules, lto_data.upstream_modules, @@ -125,15 +127,15 @@ pub(crate) fn run_fat( } fn fat_lto( + sess: &Session, cgcx: &CodegenContext, - prof: &SelfProfilerRef, dcx: DiagCtxtHandle<'_>, modules: Vec>, mut serialized_modules: Vec<(SerializedModule, CString)>, tmp_path: TempDir, //symbols_below_threshold: &[String], ) -> CompiledModule { - let _timer = prof.generic_activity("GCC_fat_lto_build_monolithic_module"); + let _timer = sess.prof.generic_activity("GCC_fat_lto_build_monolithic_module"); info!("going for a fat lto"); // Sort out all our lists of incoming modules into two lists. @@ -183,17 +185,16 @@ fn fat_lto( // module and create a linker with it. let mut module: ModuleCodegen = match costliest_module { Some((_cost, i)) => in_memory.remove(i), - None => { - unimplemented!("Incremental"); - /*assert!(!serialized_modules.is_empty(), "must have at least one serialized module"); - let (buffer, name) = serialized_modules.remove(0); - info!("no in-memory regular modules to choose from, parsing {:?}", name); - ModuleCodegen { - module_llvm: GccContext::parse(cgcx, &name, buffer.data(), dcx)?, - name: name.into_string().unwrap(), - kind: ModuleKind::Regular, - }*/ - } + None => ModuleCodegen::new_regular( + "lto_module".to_string(), + GccContext { + context: Arc::new(SyncContext::new(new_context(sess))), + relocation_model: sess.relocation_model(), + lto_supported: true, + lto_mode: LtoMode::None, + temp_dir: None, + }, + ), }; { info!("using {:?} as a base module", module.name); @@ -220,7 +221,8 @@ fn fat_lto( // We add the object files and save in should_combine_object_files that we should combine // them into a single object file when compiling later. for (bc_decoded, name) in serialized_modules { - let _timer = prof + let _timer = sess + .prof .generic_activity_with_arg_recorder("GCC_fat_lto_link_module", |recorder| { recorder.record_arg(format!("{:?}", name)) }); @@ -258,7 +260,7 @@ fn fat_lto( // of now. module.module_llvm.temp_dir = Some(tmp_path); - codegen(cgcx, prof, dcx, module, &cgcx.module_config) + codegen(cgcx, &sess.prof, dcx, module, &cgcx.module_config) } pub struct ModuleBuffer(PathBuf); diff --git a/compiler/rustc_codegen_gcc/src/back/write.rs b/compiler/rustc_codegen_gcc/src/back/write.rs index cf5514412f745..1f4fd8a314ad2 100644 --- a/compiler/rustc_codegen_gcc/src/back/write.rs +++ b/compiler/rustc_codegen_gcc/src/back/write.rs @@ -11,8 +11,8 @@ use rustc_log::tracing::debug; use rustc_session::config::OutputType; use rustc_target::spec::SplitDebuginfo; -use crate::base::add_pic_option; use crate::diagnostics::CopyBitcode; +use crate::gcc_util::add_pic_option; use crate::{GccContext, LtoMode}; pub(crate) fn codegen( @@ -60,9 +60,6 @@ pub(crate) fn codegen( let _timer = prof .generic_activity_with_arg("GCC_module_codegen_embed_bitcode", &*module.name); if lto_supported { - // FIXME(antoyo): maybe we should call embed_bitcode to have the proper iOS fixes? - //embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data); - context.add_command_line_option("-flto=auto"); context.add_command_line_option("-flto-partition=one"); context.add_command_line_option("-ffat-lto-objects"); diff --git a/compiler/rustc_codegen_gcc/src/base.rs b/compiler/rustc_codegen_gcc/src/base.rs index 7a25fc46fd3fc..041420e35d2b5 100644 --- a/compiler/rustc_codegen_gcc/src/base.rs +++ b/compiler/rustc_codegen_gcc/src/base.rs @@ -1,9 +1,7 @@ -use std::collections::HashSet; -use std::env; use std::sync::Arc; use std::time::Instant; -use gccjit::{CType, Context, FunctionType, GlobalKind}; +use gccjit::{CType, FunctionType, GlobalKind}; use rustc_codegen_ssa::ModuleCodegen; use rustc_codegen_ssa::base::maybe_create_entry_wrapper; use rustc_codegen_ssa::mono_item::MonoItemExt; @@ -17,11 +15,11 @@ use rustc_session::config::DebugInfo; use rustc_span::Symbol; #[cfg(feature = "master")] use rustc_target::spec::SymbolVisibility; -use rustc_target::spec::{Arch, RelocModel}; use crate::builder::Builder; use crate::context::CodegenCx; -use crate::{GccContext, LockedTargetInfo, LtoMode, SyncContext, gcc_util, new_context}; +use crate::gcc_util::new_context; +use crate::{GccContext, LockedTargetInfo, LtoMode, SyncContext}; #[cfg(feature = "master")] pub fn visibility_to_gcc(visibility: Visibility) -> gccjit::Visibility { @@ -101,41 +99,7 @@ pub fn compile_codegen_unit( ) -> ModuleCodegen { let cgu = tcx.codegen_unit(cgu_name); // Instantiate monomorphizations without filling out definitions yet... - let context = new_context(tcx); - - if tcx.sess.panic_strategy().unwinds() { - context.add_command_line_option("-fexceptions"); - context.add_driver_option("-fexceptions"); - } - - let disabled_features: HashSet<_> = tcx - .sess - .opts - .cg - .target_feature - .split(',') - .filter(|feature| feature.starts_with('-')) - .map(|string| &string[1..]) - .collect(); - - if !disabled_features.contains("avx") && tcx.sess.target.arch == Arch::X86_64 { - // NOTE: we always enable AVX because the equivalent of llvm.x86.sse2.cmp.pd in GCC for - // SSE2 is multiple builtins, so we use the AVX __builtin_ia32_cmppd instead. - // FIXME(antoyo): use the proper builtins for llvm.x86.sse2.cmp.pd and similar. - context.add_command_line_option("-mavx"); - } - - for arg in &tcx.sess.opts.cg.llvm_args { - context.add_command_line_option(arg); - } - // NOTE: This is needed to compile the file src/intrinsic/archs.rs during a bootstrap of rustc. - context.add_command_line_option("-fno-var-tracking-assignments"); - // NOTE: an optimization (https://github.com/rust-lang/rustc_codegen_gcc/issues/53). - context.add_command_line_option("-fno-semantic-interposition"); - // NOTE: Rust relies on LLVM not doing TBAA (https://github.com/rust-lang/unsafe-code-guidelines/issues/292). - context.add_command_line_option("-fno-strict-aliasing"); - // NOTE: Rust relies on LLVM doing wrapping on overflow. - context.add_command_line_option("-fwrapv"); + let context = new_context(tcx.sess); // NOTE: We need to honor the `#![no_builtins]` attribute to prevent GCC from // replacing code patterns (like loops) with calls to builtins (like memset). @@ -148,64 +112,6 @@ pub fn compile_codegen_unit( context.add_command_line_option("-fno-tree-loop-distribute-patterns"); } - if let Some(model) = tcx.sess.code_model() { - use rustc_target::spec::CodeModel; - - context.add_command_line_option(match model { - CodeModel::Tiny => "-mcmodel=tiny", - CodeModel::Small => "-mcmodel=small", - CodeModel::Kernel => "-mcmodel=kernel", - CodeModel::Medium => "-mcmodel=medium", - CodeModel::Large => "-mcmodel=large", - }); - } - - add_pic_option(&context, tcx.sess.relocation_model()); - - let target_cpu = gcc_util::target_cpu(tcx.sess); - if target_cpu != "generic" { - context.add_command_line_option(format!("-march={}", target_cpu)); - } - - if tcx - .sess - .opts - .unstable_opts - .function_sections - .unwrap_or(tcx.sess.target.function_sections) - { - context.add_command_line_option("-ffunction-sections"); - context.add_command_line_option("-fdata-sections"); - } - - if env::var("CG_GCCJIT_DUMP_RTL").as_deref() == Ok("1") { - context.add_command_line_option("-fdump-rtl-vregs"); - } - if env::var("CG_GCCJIT_DUMP_RTL_ALL").as_deref() == Ok("1") { - context.add_command_line_option("-fdump-rtl-all"); - } - if env::var("CG_GCCJIT_DUMP_TREE_ALL").as_deref() == Ok("1") { - context.add_command_line_option("-fdump-tree-all-eh"); - } - if env::var("CG_GCCJIT_DUMP_IPA_ALL").as_deref() == Ok("1") { - context.add_command_line_option("-fdump-ipa-all-eh"); - } - if env::var("CG_GCCJIT_DUMP_CODE").as_deref() == Ok("1") { - context.set_dump_code_on_compile(true); - } - if env::var("CG_GCCJIT_DUMP_GIMPLE").as_deref() == Ok("1") { - context.set_dump_initial_gimple(true); - } - if env::var("CG_GCCJIT_DUMP_EVERYTHING").as_deref() == Ok("1") { - context.set_dump_everything(true); - } - if env::var("CG_GCCJIT_KEEP_INTERMEDIATES").as_deref() == Ok("1") { - context.set_keep_intermediates(true); - } - if env::var("CG_GCCJIT_VERBOSE").as_deref() == Ok("1") { - context.add_driver_option("-v"); - } - // NOTE: The codegen generates unreachable blocks. context.set_allow_unreachable_blocks(true); @@ -269,24 +175,3 @@ pub fn compile_codegen_unit( (module, cost) } - -pub fn add_pic_option<'gcc>(context: &Context<'gcc>, relocation_model: RelocModel) { - match relocation_model { - rustc_target::spec::RelocModel::Static => { - context.add_command_line_option("-fno-pie"); - context.add_driver_option("-fno-pie"); - } - rustc_target::spec::RelocModel::Pic => { - context.add_command_line_option("-fPIC"); - // NOTE: we use both add_command_line_option and add_driver_option because the usage in - // this module (compile_codegen_unit) requires add_command_line_option while the usage - // in the back::write module (codegen) requires add_driver_option. - context.add_driver_option("-fPIC"); - } - rustc_target::spec::RelocModel::Pie => { - context.add_command_line_option("-fPIE"); - context.add_driver_option("-fPIE"); - } - model => eprintln!("Unsupported relocation model: {:?}", model), - } -} diff --git a/compiler/rustc_codegen_gcc/src/builder.rs b/compiler/rustc_codegen_gcc/src/builder.rs index a407362638f10..4096679ba0959 100644 --- a/compiler/rustc_codegen_gcc/src/builder.rs +++ b/compiler/rustc_codegen_gcc/src/builder.rs @@ -4,8 +4,8 @@ use std::convert::TryFrom; use std::ops::Deref; use gccjit::{ - BinaryOp, Block, ComparisonOp, Context, Function, LValue, Location, RValue, ToRValue, Type, - UnaryOp, + BinaryOp, Block, CType, ComparisonOp, Context, Function, LValue, Location, RValue, ToRValue, + Type, UnaryOp, }; use rustc_abi as abi; use rustc_abi::{Align, HasDataLayout, Size, TargetDataLayout, WrappingRange}; @@ -36,7 +36,6 @@ use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, X86Abi}; use crate::abi::FnAbiGccExt; use crate::common::{SignType, TypeReflection, type_is_pointer}; use crate::context::CodegenCx; -use crate::diagnostics; use crate::intrinsic::llvm; use crate::type_of::LayoutGccExt; @@ -85,7 +84,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { self.atomic_load(dst.get_type(), dst, load_ordering, Size::from_bytes(size)); let previous_var = func.new_local(self.location, previous_value.get_type(), "previous_value"); - let return_value = func.new_local(self.location, previous_value.get_type(), "return_value"); + let return_value = self.new_temp(func, self.location, previous_value.get_type()); self.llbb().add_assignment(self.location, previous_var, previous_value); self.llbb().add_assignment(self.location, return_value, previous_var.to_rvalue()); @@ -312,34 +311,59 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { self.block.get_function() } + /// Shared implementation of `call` and `tail_call`. For tail call it is important that this + /// returns a bare call, and not the result assigned to a local, or the result of `add_eval`. + fn build_call( + &mut self, + typ: Type<'gcc>, + fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>, + func: RValue<'gcc>, + args: &[RValue<'gcc>], + funclet: Option<&Funclet>, + must_tail: bool, + ) -> RValue<'gcc> { + // FIXME(antoyo): remove when having a proper API. + let gcc_func = unsafe { std::mem::transmute::, Function<'gcc>>(func) }; + let call = if self.functions.borrow().values().any(|value| *value == gcc_func) { + // FIXME(antoyo): remove when the API supports a different type for functions. + let func: Function<'gcc> = self.cx.rvalue_as_function(func); + self.function_call(func, args, funclet, must_tail) + } else { + // If it's a not function that was defined, it's a function pointer. + self.function_ptr_call(typ, fn_abi, func, args, funclet, must_tail) + }; + if let Some(_fn_abi) = fn_abi { + // FIXME(bjorn3): Apply function attributes + } + call + } + pub fn function_call( &mut self, func: Function<'gcc>, args: &[RValue<'gcc>], _funclet: Option<&Funclet>, + must_tail: bool, ) -> RValue<'gcc> { let args = self.check_call("call", func, args); + let call = self.cx.context.new_call(self.location, func, &args); + if must_tail { + // Return the bare tail call, don't assign or `add_eval` it yet. + return call; + } + // gccjit requires to use the result of functions, even when it's not used. // That's why we assign the result to a local or call add_eval(). let return_type = func.get_return_type(); let void_type = self.context.new_type::<()>(); let current_func = self.block.get_function(); if return_type != void_type { - let result = current_func.new_local( - self.location, - return_type, - format!("returnValue{}", self.next_value_counter()), - ); - self.block.add_assignment( - self.location, - result, - self.cx.context.new_call(self.location, func, &args), - ); + let result = self.new_temp(current_func, self.location, return_type); + self.block.add_assignment(self.location, result, call); result.to_rvalue() } else { - self.block - .add_eval(self.location, self.cx.context.new_call(self.location, func, &args)); + self.block.add_eval(self.location, call); // Return dummy value when not having return value. self.context.new_rvalue_zero(self.isize_type) } @@ -352,6 +376,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { mut func_ptr: RValue<'gcc>, args: &[RValue<'gcc>], _funclet: Option<&Funclet>, + must_tail: bool, ) -> RValue<'gcc> { let func_ptr_type = { let func_ptr_type = func_ptr.get_type(); @@ -376,6 +401,12 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let args_adjusted = args.len() != previous_arg_count; let args = self.check_ptr_call("call", func_ptr, &args, &on_stack_param_indices); + if must_tail { + // Return the bare tail call, don't assign or `add_eval` it yet. + let call = self.cx.context.new_call_through_ptr(self.location, func_ptr, &args); + return call; + } + // gccjit requires to use the result of functions, even when it's not used. // That's why we assign the result to a local or call add_eval(). let return_type = gcc_func.get_return_type(); @@ -392,11 +423,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { args_adjusted, orig_args, ); - let result = current_func.new_local( - self.location, - return_value.get_type(), - format!("ptrReturnValue{}", self.next_value_counter()), - ); + let result = self.new_temp(current_func, self.location, return_value.get_type()); self.block.add_assignment(self.location, result, return_value); result.to_rvalue() } else { @@ -418,8 +445,16 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { self.location, self.cx.context.new_call_through_ptr(self.location, func_ptr, &args), ); - // Return dummy value when not having return value. - self.context.new_rvalue_zero(self.isize_type) + // Return dummy value when not having return value, unless the intrinsic adapter + // needs to synthesize a non-void LLVM-level result from out-parameters. + llvm::adjust_intrinsic_return_value( + self, + self.context.new_rvalue_zero(self.isize_type), + &func_name, + &args, + args_adjusted, + orig_args, + ) } } @@ -434,11 +469,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let return_type = self.context.new_type::(); let current_func = self.block.get_function(); // FIXME(antoyo): return the new_call() directly? Since the overflow function has no side-effects. - let result = current_func.new_local( - self.location, - return_type, - format!("overflowReturnValue{}", self.next_value_counter()), - ); + let result = self.new_temp(current_func, self.location, return_type); self.block.add_assignment( self.location, result, @@ -570,6 +601,18 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { default_block: Block<'gcc>, cases: impl ExactSizeIterator)>, ) { + // A switch with no cases is equivalent to an unconditional jump to the + // default block. Such a `SwitchInt` (one with only an `otherwise` target) + // is normally simplified into a `goto`, but `-Z mir-preserve-ub` keeps it, + // so it can reach here with e.g. the `bool` discriminant produced by a + // range-pattern comparison. `gcc_jit_block_end_with_switch` rejects a + // discriminant that is not of integer type, so emit a plain jump instead + // of a (pointless) switch. + if cases.len() == 0 { + self.block.end_with_jump(self.location, default_block); + return; + } + let mut gcc_cases = vec![]; let typ = self.val_ty(value); // FIXME(FractalFir): This is a workaround for a libgccjit limitation. @@ -616,8 +659,7 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { let call = self.call(typ, fn_attrs, fn_abi, func, args, None, instance); // FIXME(antoyo): use funclet here? self.block = current_block; - let return_value = - self.current_func().new_local(self.location, call.get_type(), "invokeResult"); + let return_value = self.new_temp(self.current_func(), self.location, call.get_type()); try_block.add_assignment(self.location, return_value, call); @@ -664,8 +706,7 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { if return_type == void_type { self.block.end_with_void_return(self.location) } else { - let return_value = - self.current_func().new_local(self.location, return_type, "unreachableReturn"); + let return_value = self.new_temp(self.current_func(), self.location, return_type); self.block.end_with_return(self.location, return_value) } } @@ -984,11 +1025,7 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { // the current basic block. Otherwise, it could be used in another basic block, causing a // dereference after a drop, for instance. let deref = ptr.dereference(self.location).to_rvalue(); - let loaded_value = function.new_local( - self.location, - aligned_type, - format!("loadedValue{}", self.next_value_counter()), - ); + let loaded_value = self.new_temp(function, self.location, aligned_type); block.add_assignment(self.location, loaded_value, deref); loaded_value.to_rvalue() } @@ -1106,7 +1143,7 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { let next_bb = self.append_sibling_block("repeat_loop_next"); let ptr_type = start.get_type(); - let current = self.llbb().get_function().new_local(self.location, ptr_type, "loop_var"); + let current = self.new_temp(self.llbb().get_function(), self.location, ptr_type); let current_val = current.to_rvalue(); self.assign(current, start); @@ -1471,7 +1508,7 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { mut else_val: RValue<'gcc>, ) -> RValue<'gcc> { let func = self.current_func(); - let variable = func.new_local(self.location, then_val.get_type(), "selectVar"); + let variable = self.new_temp(func, self.location, then_val.get_type()); let then_block = func.new_block("then"); let else_block = func.new_block("else"); let after_block = func.new_block("after"); @@ -1493,8 +1530,10 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { variable.to_rvalue() } - fn va_arg(&mut self, _list: RValue<'gcc>, _ty: Type<'gcc>) -> RValue<'gcc> { - unimplemented!(); + fn va_arg(&mut self, list: RValue<'gcc>, ty: Type<'gcc>) -> RValue<'gcc> { + let va_list_type = self.context.new_c_type(CType::VaList); + let list = self.context.new_cast(self.location, list, va_list_type.make_pointer()); + self.context.new_va_arg(self.location, list, ty) } #[cfg(feature = "master")] @@ -1615,11 +1654,9 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { #[cfg(not(feature = "master"))] fn cleanup_landing_pad(&mut self, _pers_fn: Function<'gcc>) -> (RValue<'gcc>, RValue<'gcc>) { let value1 = self - .current_func() - .new_local(self.location, self.u8_type.make_pointer(), "landing_pad0") + .new_temp(self.current_func(), self.location, self.u8_type.make_pointer()) .to_rvalue(); - let value2 = - self.current_func().new_local(self.location, self.i32_type, "landing_pad1").to_rvalue(); + let value2 = self.new_temp(self.current_func(), self.location, self.i32_type).to_rvalue(); (value1, value2) } @@ -1687,7 +1724,7 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { // NOTE: since success contains the call to the intrinsic, it must be added to the basic block before // expected so that we store expected after the call. - let success_var = self.current_func().new_local(self.location, self.bool_type, "success"); + let success_var = self.new_temp(self.current_func(), self.location, self.bool_type); self.llbb().add_assignment(self.location, success_var, success); (expected.to_rvalue(), success_var.to_rvalue()) @@ -1776,34 +1813,34 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { funclet: Option<&Funclet>, _instance: Option>, ) -> RValue<'gcc> { - // FIXME(antoyo): remove when having a proper API. - let gcc_func = unsafe { std::mem::transmute::, Function<'gcc>>(func) }; - let call = if self.functions.borrow().values().any(|value| *value == gcc_func) { - // FIXME(antoyo): remove when the API supports a different type for functions. - let func: Function<'gcc> = self.cx.rvalue_as_function(func); - self.function_call(func, args, funclet) - } else { - // If it's a not function that was defined, it's a function pointer. - self.function_ptr_call(typ, fn_abi, func, args, funclet) - }; - if let Some(_fn_abi) = fn_abi { - // FIXME(bjorn3): Apply function attributes - } - call + self.build_call(typ, fn_abi, func, args, funclet, false) } fn tail_call( &mut self, - _llty: Self::Type, + llty: Self::Type, _fn_attrs: Option<&CodegenFnAttrs>, - _fn_abi: &FnAbi<'tcx, Ty<'tcx>>, - _llfn: Self::Value, - _args: &[Self::Value], - _funclet: Option<&Self::Funclet>, + fn_abi: &FnAbi<'tcx, Ty<'tcx>>, + llfn: Self::Value, + args: &[Self::Value], + funclet: Option<&Self::Funclet>, _instance: Option>, ) { - // FIXME: implement support for explicit tail calls like rustc_codegen_llvm. - self.tcx.dcx().emit_fatal(diagnostics::ExplicitTailCallsUnsupported); + // `emit_call` returns a bare call for here, it has not been assigned or passed to add_eval. + let call = self.build_call(llty, Some(fn_abi), llfn, args, funclet, true); + call.set_require_tail_call(true); + + let return_type = self.current_func().get_return_type(); + let void_type = self.context.new_type::<()>(); + + if return_type == void_type { + // For a void return the call is emitted as its own statement, immediately + // followed by a void return, so the tail call sits in tail position. + self.llbb().add_eval(self.location, call); + self.ret_void(); + } else { + self.ret(call) + } } fn zext(&mut self, value: RValue<'gcc>, dest_typ: Type<'gcc>) -> RValue<'gcc> { @@ -2388,11 +2425,31 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { self.bitcast_if_needed(res, result_type) } + /// Create a temporary variable. + /// + /// GCC will use more stack space with a local variable than with a temporary variable in debug mode, + /// so in order to avoid having the stack probe test fail in CI, we avoid creating local variables for temporaries. + pub fn new_temp( + &self, + function: Function<'gcc>, + location: Option>, + typ: Type<'gcc>, + ) -> LValue<'gcc> { + #[cfg(feature = "master")] + { + function.new_temp(location, typ) + } + #[cfg(not(feature = "master"))] + { + function.new_local(location, typ, format!("temp{}", self.next_value_counter())) + } + } + // GCC doesn't like deeply nested expressions. // By assigning intermediate expressions to a variable, this allow us to avoid deeply nested // expressions and GCC will use much less RAM. fn assign_to_var(&self, value: RValue<'gcc>) -> RValue<'gcc> { - let var = self.current_func().new_local(self.location, value.get_type(), "opResult"); + let var = self.new_temp(self.current_func(), self.location, value.get_type()); self.llbb().add_assignment(self.location, var, value); var.to_rvalue() } diff --git a/compiler/rustc_codegen_gcc/src/callee.rs b/compiler/rustc_codegen_gcc/src/callee.rs index 00f095ed54371..d3f412180da55 100644 --- a/compiler/rustc_codegen_gcc/src/callee.rs +++ b/compiler/rustc_codegen_gcc/src/callee.rs @@ -70,7 +70,7 @@ pub fn get_fn<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, instance: Instance<'tcx>) cx.linkage.set(FunctionType::Extern); let func = cx.declare_fn(sym, fn_abi); - attributes::from_fn_attrs(cx, func, instance); + attributes::from_fn_attrs(cx, func, instance, Some(fn_abi)); #[cfg(feature = "master")] { diff --git a/compiler/rustc_codegen_gcc/src/common.rs b/compiler/rustc_codegen_gcc/src/common.rs index 6bd186f1121fc..d979c8b7ed094 100644 --- a/compiler/rustc_codegen_gcc/src/common.rs +++ b/compiler/rustc_codegen_gcc/src/common.rs @@ -143,9 +143,9 @@ pub fn bytes_in_context<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, bytes: &[u8]) -> let context = &cx.context; let byte_type = context.new_type::(); let typ = new_array_type(context, None, byte_type, bytes.len() as u64 / 8); - let elements: Vec<_> = bytes - .as_chunks::<8>() - .0 + let (arrays, remainder) = bytes.as_chunks::<8>(); + debug_assert!(remainder.is_empty()); + let elements: Vec<_> = arrays .iter() .map(|&arr| { context.new_rvalue_from_long( @@ -170,9 +170,9 @@ pub fn bytes_in_context<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, bytes: &[u8]) -> let context = &cx.context; let byte_type = context.new_type::(); let typ = new_array_type(context, None, byte_type, bytes.len() as u64 / 4); - let elements: Vec<_> = bytes - .as_chunks::<4>() - .0 + let (arrays, remainder) = bytes.as_chunks::<4>(); + debug_assert!(remainder.is_empty()); + let elements: Vec<_> = arrays .iter() .map(|&arr| { context.new_rvalue_from_int( diff --git a/compiler/rustc_codegen_gcc/src/consts.rs b/compiler/rustc_codegen_gcc/src/consts.rs index 42ff930968501..5ebdf91fe20b6 100644 --- a/compiler/rustc_codegen_gcc/src/consts.rs +++ b/compiler/rustc_codegen_gcc/src/consts.rs @@ -1,6 +1,6 @@ #[cfg(feature = "master")] -use gccjit::{FnAttribute, VarAttribute, Visibility}; -use gccjit::{Function, GlobalKind, LValue, RValue, ToRValue, Type}; +use gccjit::{FnAttribute, ToRValue, VarAttribute, Visibility}; +use gccjit::{Function, GlobalKind, LValue, RValue, Type}; use rustc_abi::{self as abi, Align, HasDataLayout, Primitive, Size, WrappingRange}; use rustc_codegen_ssa::traits::{ BaseTypeCodegenMethods, ConstCodegenMethods, StaticCodegenMethods, @@ -160,29 +160,52 @@ impl<'gcc, 'tcx> StaticCodegenMethods for CodegenCx<'gcc, 'tcx> { } // Wasm statics with custom link sections get special treatment as they - // go into custom sections of the wasm executable. - if self.tcx.sess.target.is_like_wasm { + // go into custom sections of the wasm executable. The exception to this + // is the `.init_array` section which are treated specially by the wasm linker. + if self.tcx.sess.target.is_like_wasm + && attrs + .link_section + .map(|link_section| !link_section.as_str().starts_with(".init_array")) + .unwrap_or(true) + { if let Some(_section) = attrs.link_section { unimplemented!(); } - } else { - // FIXME(antoyo): set link section. + } else if let Some(_section) = attrs.link_section { + #[cfg(feature = "master")] + global.add_attribute(VarAttribute::Section(_section.as_str())); } - if attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER) - || attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) - { - self.add_used_global(global.to_rvalue()); + if attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER) { + // To copy the conditions from the LLVM backend... + assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)); + self.add_used_global(global); + } + if attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) { + // To copy the conditions from the LLVM backend... + assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)); + self.add_retained_global(global); } } } impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { - /// Add a global value to a list to be stored in the `llvm.used` variable, an array of i8*. - pub fn add_used_global(&mut self, _global: RValue<'gcc>) { - // FIXME(antoyo) + /// Need to have the `SHF_GNU_RETAIN` flag, so needs to use the `retain` attribute instead of + /// `used`. This is used by `#[used(linker)]`. + pub fn add_retained_global(&mut self, global: LValue<'gcc>) { + // We need to add the `used` C attribute in any case. + self.add_used_global(global); + #[cfg(feature = "master")] + global.add_attribute(VarAttribute::Retain); + } + + /// This is used by `#[used(compiler)]` and `#[used]`. + pub fn add_used_global(&mut self, _global: LValue<'gcc>) { + #[cfg(feature = "master")] + _global.add_attribute(VarAttribute::Used); } + // No need to have the `SHF_GNU_RETAIN` flag, so `used` attribute is ok. #[cfg_attr(not(feature = "master"), expect(unused_variables))] pub fn add_used_function(&self, function: Function<'gcc>) { #[cfg(feature = "master")] diff --git a/compiler/rustc_codegen_gcc/src/declare.rs b/compiler/rustc_codegen_gcc/src/declare.rs index 4174eebcf7b02..9bf57fbf75bc0 100644 --- a/compiler/rustc_codegen_gcc/src/declare.rs +++ b/compiler/rustc_codegen_gcc/src/declare.rs @@ -1,12 +1,12 @@ #[cfg(feature = "master")] -use gccjit::{FnAttribute, ToRValue}; +use gccjit::{FnAttribute, ToRValue, VarAttribute}; use gccjit::{Function, FunctionType, GlobalKind, LValue, RValue, Type}; use rustc_codegen_ssa::traits::BaseTypeCodegenMethods; use rustc_middle::ty::Ty; use rustc_span::Symbol; use rustc_target::callconv::FnAbi; -use crate::abi::{FnAbiGcc, FnAbiGccExt}; +use crate::abi::FnAbiGccExt; use crate::context::CodegenCx; impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { @@ -24,6 +24,9 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { global.set_tls_model(self.tls_model); } if let Some(link_section) = link_section { + #[cfg(feature = "master")] + global.add_attribute(VarAttribute::Section(link_section.as_str())); + #[cfg(not(feature = "master"))] global.set_link_section(link_section.as_str()); } global @@ -73,6 +76,9 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { global.set_tls_model(self.tls_model); } if let Some(link_section) = link_section { + #[cfg(feature = "master")] + global.add_attribute(VarAttribute::Section(link_section.as_str())); + #[cfg(not(feature = "master"))] global.set_link_section(link_section.as_str()); } let global_address = global.get_address(None); @@ -110,22 +116,22 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { } pub fn declare_fn(&self, name: &str, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> Function<'gcc> { - let FnAbiGcc { - return_type, - arguments_type, - is_c_variadic, - on_stack_param_indices, - #[cfg(feature = "master")] - fn_attributes, - } = fn_abi.gcc_type(self); + let fn_abi_gcc = fn_abi.gcc_type(self); #[cfg(feature = "master")] let conv = fn_abi.gcc_cconv(self); #[cfg(not(feature = "master"))] let conv = None; - let func = declare_raw_fn(self, name, conv, return_type, &arguments_type, is_c_variadic); - self.on_stack_function_params.borrow_mut().insert(func, on_stack_param_indices); + let func = declare_raw_fn( + self, + name, + conv, + fn_abi_gcc.return_type, + &fn_abi_gcc.arguments_type, + fn_abi_gcc.is_c_variadic, + ); + self.on_stack_function_params.borrow_mut().insert(func, fn_abi_gcc.on_stack_param_indices); #[cfg(feature = "master")] - for fn_attr in fn_attributes { + for fn_attr in fn_abi_gcc.fn_attributes { func.add_attribute(fn_attr); } func diff --git a/compiler/rustc_codegen_gcc/src/diagnostics.rs b/compiler/rustc_codegen_gcc/src/diagnostics.rs index de633d3bdde79..67723ebd2f30b 100644 --- a/compiler/rustc_codegen_gcc/src/diagnostics.rs +++ b/compiler/rustc_codegen_gcc/src/diagnostics.rs @@ -20,10 +20,6 @@ pub(crate) struct LtoBitcodeFromRlib { pub gcc_err: String, } -#[derive(Diagnostic)] -#[diag("explicit tail calls with the 'become' keyword are not implemented in the GCC backend")] -pub(crate) struct ExplicitTailCallsUnsupported; - #[derive(Diagnostic)] #[diag("asm contains a NUL byte")] pub(crate) struct NulBytesInAsm { diff --git a/compiler/rustc_codegen_gcc/src/gcc_util.rs b/compiler/rustc_codegen_gcc/src/gcc_util.rs index a95b4da28eb63..4d7f2cdbb92ed 100644 --- a/compiler/rustc_codegen_gcc/src/gcc_util.rs +++ b/compiler/rustc_codegen_gcc/src/gcc_util.rs @@ -1,10 +1,14 @@ -#[cfg(feature = "master")] +use std::collections::HashSet; +use std::env; + use gccjit::Context; +#[cfg(feature = "master")] +use gccjit::Version; use rustc_codegen_ssa::target_features; use rustc_data_structures::smallvec::{SmallVec, smallvec}; use rustc_session::Session; use rustc_session::config::NATIVE_CPU; -use rustc_target::spec::Arch; +use rustc_target::spec::{Arch, RelocModel, StackProbeType, StackProtector}; fn gcc_features_by_flags(sess: &Session, features: &mut Vec) { target_features::retpoline_features_by_flags(sess, features); @@ -136,3 +140,147 @@ pub fn target_cpu(sess: &Session) -> &str { None => handle_native(sess.target.cpu.as_ref()), } } + +pub fn new_context<'gcc>(sess: &Session) -> Context<'gcc> { + let context = Context::default(); + if matches!(sess.target.arch, Arch::X86 | Arch::X86_64) { + context.add_command_line_option("-masm=intel"); + } + #[cfg(feature = "master")] + { + context.set_special_chars_allowed_in_func_names("$.*"); + let version = Version::get(); + let version = format!("{}.{}.{}", version.major, version.minor, version.patch); + context.set_output_ident(&format!( + "rustc version {} with libgccjit {}", + rustc_interface::util::rustc_version_str().unwrap_or("unknown version"), + version, + )); + } + // FIXME(antoyo): check if this should only be added when using -Cforce-unwind-tables=n. + context.add_command_line_option("-fno-asynchronous-unwind-tables"); + + if sess.panic_strategy().unwinds() { + context.add_command_line_option("-fexceptions"); + context.add_driver_option("-fexceptions"); + } + + let disabled_features: HashSet<_> = sess + .opts + .cg + .target_feature + .split(',') + .filter(|feature| feature.starts_with('-')) + .map(|string| &string[1..]) + .collect(); + + if !disabled_features.contains("avx") && sess.target.arch == Arch::X86_64 { + // NOTE: we always enable AVX because the equivalent of llvm.x86.sse2.cmp.pd in GCC for + // SSE2 is multiple builtins, so we use the AVX __builtin_ia32_cmppd instead. + // FIXME(antoyo): use the proper builtins for llvm.x86.sse2.cmp.pd and similar. + context.add_command_line_option("-mavx"); + } + + for arg in &sess.opts.cg.llvm_args { + context.add_command_line_option(arg); + } + // NOTE: This is needed to compile the file src/intrinsic/archs.rs during a bootstrap of rustc. + context.add_command_line_option("-fno-var-tracking-assignments"); + // NOTE: an optimization (https://github.com/rust-lang/rustc_codegen_gcc/issues/53). + context.add_command_line_option("-fno-semantic-interposition"); + // NOTE: Rust relies on LLVM not doing TBAA (https://github.com/rust-lang/unsafe-code-guidelines/issues/292). + context.add_command_line_option("-fno-strict-aliasing"); + // NOTE: Rust relies on LLVM doing wrapping on overflow. + context.add_command_line_option("-fwrapv"); + + if let Some(model) = sess.code_model() { + use rustc_target::spec::CodeModel; + + context.add_command_line_option(match model { + CodeModel::Tiny => "-mcmodel=tiny", + CodeModel::Small => "-mcmodel=small", + CodeModel::Kernel => "-mcmodel=kernel", + CodeModel::Medium => "-mcmodel=medium", + CodeModel::Large => "-mcmodel=large", + }); + } + + match sess.stack_protector() { + StackProtector::All => context.add_command_line_option("-fstack-protector-all"), + StackProtector::Strong => context.add_command_line_option("-fstack-protector-strong"), + StackProtector::Basic => context.add_command_line_option("-fstack-protector"), + StackProtector::None => (), + } + + match sess.target.stack_probes { + StackProbeType::None => (), + StackProbeType::Inline | StackProbeType::InlineOrCall { .. } => { + context.add_command_line_option("-fstack-clash-protection") + } + // FIXME(antoyo): We should define the stack probe symbol to be __rust_probestack, but it seems GCC cannot do that. + StackProbeType::Call => (), + }; + + add_pic_option(&context, sess.relocation_model()); + + let target_cpu = target_cpu(sess); + if target_cpu != "generic" { + context.add_command_line_option(format!("-march={}", target_cpu)); + } + + if sess.opts.unstable_opts.function_sections.unwrap_or(sess.target.function_sections) { + context.add_command_line_option("-ffunction-sections"); + context.add_command_line_option("-fdata-sections"); + } + + if env::var("CG_GCCJIT_DUMP_RTL").as_deref() == Ok("1") { + context.add_command_line_option("-fdump-rtl-vregs"); + } + if env::var("CG_GCCJIT_DUMP_RTL_ALL").as_deref() == Ok("1") { + context.add_command_line_option("-fdump-rtl-all"); + } + if env::var("CG_GCCJIT_DUMP_TREE_ALL").as_deref() == Ok("1") { + context.add_command_line_option("-fdump-tree-all-eh"); + } + if env::var("CG_GCCJIT_DUMP_IPA_ALL").as_deref() == Ok("1") { + context.add_command_line_option("-fdump-ipa-all-eh"); + } + if env::var("CG_GCCJIT_DUMP_CODE").as_deref() == Ok("1") { + context.set_dump_code_on_compile(true); + } + if env::var("CG_GCCJIT_DUMP_GIMPLE").as_deref() == Ok("1") { + context.set_dump_initial_gimple(true); + } + if env::var("CG_GCCJIT_DUMP_EVERYTHING").as_deref() == Ok("1") { + context.set_dump_everything(true); + } + if env::var("CG_GCCJIT_KEEP_INTERMEDIATES").as_deref() == Ok("1") { + context.set_keep_intermediates(true); + } + if env::var("CG_GCCJIT_VERBOSE").as_deref() == Ok("1") { + context.add_driver_option("-v"); + } + + context +} + +pub fn add_pic_option<'gcc>(context: &Context<'gcc>, relocation_model: RelocModel) { + match relocation_model { + rustc_target::spec::RelocModel::Static => { + context.add_command_line_option("-fno-pie"); + context.add_driver_option("-fno-pie"); + } + rustc_target::spec::RelocModel::Pic => { + context.add_command_line_option("-fPIC"); + // NOTE: we use both add_command_line_option and add_driver_option because the usage in + // base (compile_codegen_unit) requires add_command_line_option while the usage + // in the back::write module (codegen) requires add_driver_option. + context.add_driver_option("-fPIC"); + } + rustc_target::spec::RelocModel::Pie => { + context.add_command_line_option("-fPIE"); + context.add_driver_option("-fPIE"); + } + model => eprintln!("Unsupported relocation model: {:?}", model), + } +} diff --git a/compiler/rustc_codegen_gcc/src/int.rs b/compiler/rustc_codegen_gcc/src/int.rs index dfae4eceebe44..0c9a755694577 100644 --- a/compiler/rustc_codegen_gcc/src/int.rs +++ b/compiler/rustc_codegen_gcc/src/int.rs @@ -432,7 +432,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { if self.is_non_native_int_type(a_type) || self.is_non_native_int_type(b_type) { // This algorithm is based on compiler-rt's __cmpti2: // https://github.com/llvm-mirror/compiler-rt/blob/f0745e8476f069296a7c71accedd061dce4cdf79/lib/builtins/cmpti2.c#L21 - let result = self.current_func().new_local(self.location, self.int_type, "icmp_result"); + let result = self.new_temp(self.current_func(), self.location, self.int_type); let block1 = self.current_func().new_block("block1"); let block2 = self.current_func().new_block("block2"); let block3 = self.current_func().new_block("block3"); @@ -462,9 +462,15 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { lhs_high = self.context.new_cast(self.location, lhs_high, unsigned_type); rhs_high = self.context.new_cast(self.location, rhs_high, unsigned_type); } - // FIXME(antoyo): we probably need to handle signed comparison for unsigned - // integers. - _ => (), + IntPredicate::IntSGT + | IntPredicate::IntSGE + | IntPredicate::IntSLT + | IntPredicate::IntSLE => { + let signed_type = native_int_type.to_signed(self.cx); + lhs_high = self.context.new_cast(self.location, lhs_high, signed_type); + rhs_high = self.context.new_cast(self.location, rhs_high, signed_type); + } + IntPredicate::IntEQ | IntPredicate::IntNE => (), } let condition = self.context.new_comparison( @@ -602,9 +608,17 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { rhs = self.context.new_cast(self.location, rhs, unsigned_type); } } - // FIXME(antoyo): we probably need to handle signed comparison for unsigned - // integers. - _ => (), + IntPredicate::IntSGT + | IntPredicate::IntSGE + | IntPredicate::IntSLT + | IntPredicate::IntSLE => { + if !a_type.is_vector() { + let signed_type = a_type.to_signed(self.cx); + lhs = self.context.new_cast(self.location, lhs, signed_type); + rhs = self.context.new_cast(self.location, rhs, signed_type); + } + } + IntPredicate::IntEQ | IntPredicate::IntNE => (), } self.context.new_comparison(self.location, op.to_gcc_comparison(), lhs, rhs) } @@ -862,7 +876,7 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { self.bitwise_operation(BinaryOp::BitwiseOr, a, b, loc) } - // FIXME(antoyo): can we use https://github.com/rust-lang/compiler-builtins/blob/master/src/int/mod.rs#L379 instead? + // FIXME(antoyo): can we use https://github.com/rust-lang/compiler-builtins/blob/1a99c2aa295bb2d507fa0e67a3b5eef64fba92a0/libm/src/math/support/int_traits.rs#L485 instead? pub fn gcc_int_cast(&self, value: RValue<'gcc>, dest_typ: Type<'gcc>) -> RValue<'gcc> { let value_type = value.get_type(); if self.is_native_int_type_or_bool(dest_typ) && self.is_native_int_type_or_bool(value_type) diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/archs.rs b/compiler/rustc_codegen_gcc/src/intrinsic/archs.rs index 3c1698df6dec2..1856c2468616d 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/archs.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/archs.rs @@ -24,6 +24,7 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "gcsss" => "__builtin_arm_gcsss", "isb" => "__builtin_arm_isb", "prefetch" => "__builtin_arm_prefetch", + "prefetch.ir" => "__builtin_arm_prefetch_ir", "range.prefetch" => "__builtin_arm_range_prefetch", "sme.in.streaming.mode" => "__builtin_arm_in_streaming_mode", "sve.aesd" => "__builtin_sve_svaesd_u8", @@ -53,6 +54,7 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "alignbyte" => "__builtin_amdgcn_alignbyte", "ashr.pk.i8.i32" => "__builtin_amdgcn_ashr_pk_i8_i32", "ashr.pk.u8.i32" => "__builtin_amdgcn_ashr_pk_u8_i32", + "asyncmark" => "__builtin_amdgcn_asyncmark", "buffer.wbinvl1" => "__builtin_amdgcn_buffer_wbinvl1", "buffer.wbinvl1.sc" => "__builtin_amdgcn_buffer_wbinvl1_sc", "buffer.wbinvl1.vol" => "__builtin_amdgcn_buffer_wbinvl1_vol", @@ -270,6 +272,7 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "fdot2c.f32.bf16" => "__builtin_amdgcn_fdot2c_f32_bf16", "flat.prefetch" => "__builtin_amdgcn_flat_prefetch", "fmul.legacy" => "__builtin_amdgcn_fmul_legacy", + "global.load.async.lds" => "__builtin_amdgcn_global_load_async_lds", "global.load.async.to.lds.b128" => { "__builtin_amdgcn_global_load_async_to_lds_b128" } @@ -361,11 +364,7 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "perm.pk16.b4.u4" => "__builtin_amdgcn_perm_pk16_b4_u4", "perm.pk16.b6.u4" => "__builtin_amdgcn_perm_pk16_b6_u4", "perm.pk16.b8.u4" => "__builtin_amdgcn_perm_pk16_b8_u4", - "permlane.bcast" => "__builtin_amdgcn_permlane_bcast", - "permlane.down" => "__builtin_amdgcn_permlane_down", "permlane.idx.gen" => "__builtin_amdgcn_permlane_idx_gen", - "permlane.up" => "__builtin_amdgcn_permlane_up", - "permlane.xor" => "__builtin_amdgcn_permlane_xor", "permlane16.var" => "__builtin_amdgcn_permlane16_var", "permlanex16.var" => "__builtin_amdgcn_permlanex16_var", "pk.add.max.i16" => "__builtin_amdgcn_pk_add_max_i16", @@ -375,6 +374,9 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "prng.b32" => "__builtin_amdgcn_prng_b32", "qsad.pk.u16.u8" => "__builtin_amdgcn_qsad_pk_u16_u8", "queue.ptr" => "__builtin_amdgcn_queue_ptr", + "raw.ptr.buffer.load.async.lds" => { + "__builtin_amdgcn_raw_ptr_buffer_load_async_lds" + } "raw.ptr.buffer.load.lds" => "__builtin_amdgcn_raw_ptr_buffer_load_lds", "rcp.legacy" => "__builtin_amdgcn_rcp_legacy", "rsq.legacy" => "__builtin_amdgcn_rsq_legacy", @@ -386,6 +388,7 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "s.barrier.signal.isfirst" => "__builtin_amdgcn_s_barrier_signal_isfirst", "s.barrier.signal.var" => "__builtin_amdgcn_s_barrier_signal_var", "s.barrier.wait" => "__builtin_amdgcn_s_barrier_wait", + "s.bitreplicate" => "__builtin_amdgcn_s_bitreplicate", "s.buffer.prefetch.data" => "__builtin_amdgcn_s_buffer_prefetch_data", "s.cluster.barrier" => "__builtin_amdgcn_s_cluster_barrier", "s.dcache.inv" => "__builtin_amdgcn_s_dcache_inv", @@ -412,6 +415,7 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "s.ttracedata" => "__builtin_amdgcn_s_ttracedata", "s.ttracedata.imm" => "__builtin_amdgcn_s_ttracedata_imm", "s.wait.asynccnt" => "__builtin_amdgcn_s_wait_asynccnt", + "s.wait.event" => "__builtin_amdgcn_s_wait_event", "s.wait.event.export.ready" => "__builtin_amdgcn_s_wait_event_export_ready", "s.wait.tensorcnt" => "__builtin_amdgcn_s_wait_tensorcnt", "s.waitcnt" => "__builtin_amdgcn_s_waitcnt", @@ -462,16 +466,18 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "smfmac.i32.16x16x64.i8" => "__builtin_amdgcn_smfmac_i32_16x16x64_i8", "smfmac.i32.32x32x32.i8" => "__builtin_amdgcn_smfmac_i32_32x32x32_i8", "smfmac.i32.32x32x64.i8" => "__builtin_amdgcn_smfmac_i32_32x32x64_i8", + "struct.ptr.buffer.load.async.lds" => { + "__builtin_amdgcn_struct_ptr_buffer_load_async_lds" + } "struct.ptr.buffer.load.lds" => "__builtin_amdgcn_struct_ptr_buffer_load_lds", "sudot4" => "__builtin_amdgcn_sudot4", "sudot8" => "__builtin_amdgcn_sudot8", "tensor.load.to.lds" => "__builtin_amdgcn_tensor_load_to_lds", - "tensor.load.to.lds.d2" => "__builtin_amdgcn_tensor_load_to_lds_d2", "tensor.store.from.lds" => "__builtin_amdgcn_tensor_store_from_lds", - "tensor.store.from.lds.d2" => "__builtin_amdgcn_tensor_store_from_lds_d2", "udot2" => "__builtin_amdgcn_udot2", "udot4" => "__builtin_amdgcn_udot4", "udot8" => "__builtin_amdgcn_udot8", + "wait.asyncmark" => "__builtin_amdgcn_wait_asyncmark", "wave.barrier" => "__builtin_amdgcn_wave_barrier", "wavefrontsize" => "__builtin_amdgcn_wavefrontsize", "workgroup.id.x" => "__builtin_amdgcn_workgroup_id_x", @@ -4844,7 +4850,11 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "add.rn.f" => "__nvvm_add_rn_f", "add.rn.ftz.f" => "__nvvm_add_rn_ftz_f", "add.rn.ftz.sat.f" => "__nvvm_add_rn_ftz_sat_f", + "add.rn.ftz.sat.f16" => "__nvvm_add_rn_ftz_sat_f16", + "add.rn.ftz.sat.v2f16" => "__nvvm_add_rn_ftz_sat_v2f16", "add.rn.sat.f" => "__nvvm_add_rn_sat_f", + "add.rn.sat.f16" => "__nvvm_add_rn_sat_f16", + "add.rn.sat.v2f16" => "__nvvm_add_rn_sat_v2f16", "add.rp.d" => "__nvvm_add_rp_d", "add.rp.f" => "__nvvm_add_rp_f", "add.rp.ftz.f" => "__nvvm_add_rp_ftz_f", @@ -5063,18 +5073,10 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "fma.rn.bf16x2" => "__nvvm_fma_rn_bf16x2", "fma.rn.d" => "__nvvm_fma_rn_d", "fma.rn.f" => "__nvvm_fma_rn_f", - "fma.rn.ftz.bf16" => "__nvvm_fma_rn_ftz_bf16", - "fma.rn.ftz.bf16x2" => "__nvvm_fma_rn_ftz_bf16x2", "fma.rn.ftz.f" => "__nvvm_fma_rn_ftz_f", - "fma.rn.ftz.relu.bf16" => "__nvvm_fma_rn_ftz_relu_bf16", - "fma.rn.ftz.relu.bf16x2" => "__nvvm_fma_rn_ftz_relu_bf16x2", - "fma.rn.ftz.sat.bf16" => "__nvvm_fma_rn_ftz_sat_bf16", - "fma.rn.ftz.sat.bf16x2" => "__nvvm_fma_rn_ftz_sat_bf16x2", "fma.rn.ftz.sat.f" => "__nvvm_fma_rn_ftz_sat_f", "fma.rn.relu.bf16" => "__nvvm_fma_rn_relu_bf16", "fma.rn.relu.bf16x2" => "__nvvm_fma_rn_relu_bf16x2", - "fma.rn.sat.bf16" => "__nvvm_fma_rn_sat_bf16", - "fma.rn.sat.bf16x2" => "__nvvm_fma_rn_sat_bf16x2", "fma.rn.sat.f" => "__nvvm_fma_rn_sat_f", "fma.rp.d" => "__nvvm_fma_rp_d", "fma.rp.f" => "__nvvm_fma_rp_f", @@ -5195,6 +5197,10 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "mul.rn.d" => "__nvvm_mul_rn_d", "mul.rn.f" => "__nvvm_mul_rn_f", "mul.rn.ftz.f" => "__nvvm_mul_rn_ftz_f", + "mul.rn.ftz.sat.f16" => "__nvvm_mul_rn_ftz_sat_f16", + "mul.rn.ftz.sat.v2f16" => "__nvvm_mul_rn_ftz_sat_v2f16", + "mul.rn.sat.f16" => "__nvvm_mul_rn_sat_f16", + "mul.rn.sat.v2f16" => "__nvvm_mul_rn_sat_v2f16", "mul.rp.d" => "__nvvm_mul_rp_d", "mul.rp.f" => "__nvvm_mul_rp_f", "mul.rp.ftz.f" => "__nvvm_mul_rp_ftz_f", @@ -5827,8 +5833,10 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "altivec.vmuleuh" => "__builtin_altivec_vmuleuh", "altivec.vmuleuw" => "__builtin_altivec_vmuleuw", "altivec.vmulhsd" => "__builtin_altivec_vmulhsd", + "altivec.vmulhsh" => "__builtin_altivec_vmulhsh", "altivec.vmulhsw" => "__builtin_altivec_vmulhsw", "altivec.vmulhud" => "__builtin_altivec_vmulhud", + "altivec.vmulhuh" => "__builtin_altivec_vmulhuh", "altivec.vmulhuw" => "__builtin_altivec_vmulhuw", "altivec.vmulosb" => "__builtin_altivec_vmulosb", "altivec.vmulosd" => "__builtin_altivec_vmulosd", @@ -5912,22 +5920,45 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "altivec.vsum4shs" => "__builtin_altivec_vsum4shs", "altivec.vsum4ubs" => "__builtin_altivec_vsum4ubs", "altivec.vsumsws" => "__builtin_altivec_vsumsws", + "altivec.vucmprhb" => "__builtin_altivec_vucmprhb", + "altivec.vucmprhh" => "__builtin_altivec_vucmprhh", + "altivec.vucmprhn" => "__builtin_altivec_vucmprhn", + "altivec.vucmprlb" => "__builtin_altivec_vucmprlb", + "altivec.vucmprlh" => "__builtin_altivec_vucmprlh", + "altivec.vucmprln" => "__builtin_altivec_vucmprln", "altivec.vupkhpx" => "__builtin_altivec_vupkhpx", "altivec.vupkhsb" => "__builtin_altivec_vupkhsb", "altivec.vupkhsh" => "__builtin_altivec_vupkhsh", + "altivec.vupkhsntob" => "__builtin_altivec_vupkhsntob", "altivec.vupkhsw" => "__builtin_altivec_vupkhsw", + "altivec.vupkint4tobf16" => "__builtin_altivec_vupkint4tobf16", + "altivec.vupkint4tofp32" => "__builtin_altivec_vupkint4tofp32", + "altivec.vupkint8tobf16" => "__builtin_altivec_vupkint8tobf16", + "altivec.vupkint8tofp32" => "__builtin_altivec_vupkint8tofp32", "altivec.vupklpx" => "__builtin_altivec_vupklpx", "altivec.vupklsb" => "__builtin_altivec_vupklsb", "altivec.vupklsh" => "__builtin_altivec_vupklsh", + "altivec.vupklsntob" => "__builtin_altivec_vupklsntob", "altivec.vupklsw" => "__builtin_altivec_vupklsw", "amo.ldat" => "__builtin_amo_ldat", + "amo.ldat.cond" => "__builtin_amo_ldat_cond", + "amo.ldat.csne" => "__builtin_amo_ldat_csne", "amo.lwat" => "__builtin_amo_lwat", + "amo.lwat.cond" => "__builtin_amo_lwat_cond", + "amo.lwat.csne" => "__builtin_amo_lwat_csne", + "amo.stdat" => "__builtin_amo_stdat", + "amo.stwat" => "__builtin_amo_stwat", "bcdadd" => "__builtin_ppc_bcdadd", "bcdadd.p" => "__builtin_ppc_bcdadd_p", "bcdcopysign" => "__builtin_ppc_bcdcopysign", "bcdsetsign" => "__builtin_ppc_bcdsetsign", + "bcdshift" => "__builtin_ppc_bcdshift", + "bcdshiftround" => "__builtin_ppc_bcdshiftround", "bcdsub" => "__builtin_ppc_bcdsub", "bcdsub.p" => "__builtin_ppc_bcdsub_p", + "bcdtruncate" => "__builtin_ppc_bcdtruncate", + "bcdunsignedshift" => "__builtin_ppc_bcdunsignedshift", + "bcdunsignedtruncate" => "__builtin_ppc_bcdunsignedtruncate", "bpermd" => "__builtin_bpermd", "cbcdtd" => "__builtin_cbcdtd", "cbcdtdd" => "__builtin_ppc_cbcdtd", @@ -6126,6 +6157,27 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "vsx.xxinsertw" => "__builtin_vsx_xxinsertw", "vsx.xxleqv" => "__builtin_vsx_xxleqv", "vsx.xxpermx" => "__builtin_vsx_xxpermx", + "xsaddaddsuqm" => "__builtin_xsaddaddsuqm", + "xsaddadduqm" => "__builtin_xsaddadduqm", + "xsaddsubsuqm" => "__builtin_xsaddsubsuqm", + "xsaddsubuqm" => "__builtin_xsaddsubuqm", + "xsmerge2t1uqm" => "__builtin_xsmerge2t1uqm", + "xsmerge2t2uqm" => "__builtin_xsmerge2t2uqm", + "xsmerge2t3uqm" => "__builtin_xsmerge2t3uqm", + "xsmerge3t1uqm" => "__builtin_xsmerge3t1uqm", + "xsrebase2t1uqm" => "__builtin_xsrebase2t1uqm", + "xsrebase2t2uqm" => "__builtin_xsrebase2t2uqm", + "xsrebase2t3uqm" => "__builtin_xsrebase2t3uqm", + "xsrebase2t4uqm" => "__builtin_xsrebase2t4uqm", + "xsrebase3t1uqm" => "__builtin_xsrebase3t1uqm", + "xsrebase3t2uqm" => "__builtin_xsrebase3t2uqm", + "xsrebase3t3uqm" => "__builtin_xsrebase3t3uqm", + "xxmulmul" => "__builtin_xxmulmul", + "xxmulmulhiadd" => "__builtin_xxmulmulhiadd", + "xxmulmulloadd" => "__builtin_xxmulmulloadd", + "xxssumudm" => "__builtin_xxssumudm", + "xxssumudmc" => "__builtin_xxssumudmc", + "xxssumudmcext" => "__builtin_xxssumudmcext", "zoned2packed" => "__builtin_ppc_zoned2packed", _ => unimplemented!("***** unsupported LLVM intrinsic {full_name}"), } @@ -6388,13 +6440,13 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { // spv "group.memory.barrier.with.group.sync" => "__builtin_spirv_group_barrier", "num.subgroups" => "__builtin_spirv_num_subgroups", + "subgroup.ballot" => "__builtin_spirv_subgroup_ballot", "subgroup.id" => "__builtin_spirv_subgroup_id", "subgroup.local.invocation.id" => { "__builtin_spirv_subgroup_local_invocation_id" } "subgroup.max.size" => "__builtin_spirv_subgroup_max_size", "subgroup.size" => "__builtin_spirv_subgroup_size", - "wave.ballot" => "__builtin_spirv_subgroup_ballot", _ => unimplemented!("***** unsupported LLVM intrinsic {full_name}"), } } @@ -8661,10 +8713,6 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "bmi.bextr.64" => "__builtin_ia32_bextr_u64", "bmi.bzhi.32" => "__builtin_ia32_bzhi_si", "bmi.bzhi.64" => "__builtin_ia32_bzhi_di", - "bmi.pdep.32" => "__builtin_ia32_pdep_si", - "bmi.pdep.64" => "__builtin_ia32_pdep_di", - "bmi.pext.32" => "__builtin_ia32_pext_si", - "bmi.pext.64" => "__builtin_ia32_pext_di", "cldemote" => "__builtin_ia32_cldemote", "clflushopt" => "__builtin_ia32_clflushopt", "clrssbsy" => "__builtin_ia32_clrssbsy", diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs b/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs index 41efe3e8209bf..6ad19d5af095e 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs @@ -1,5 +1,7 @@ use std::borrow::Cow; +#[cfg(feature = "master")] +use gccjit::TypeAttribute; use gccjit::{CType, Context, Field, Function, FunctionPtrType, RValue, ToRValue, Type}; use rustc_codegen_ssa::traits::BuilderMethods; @@ -23,7 +25,7 @@ fn encode_key_128_type<'a, 'gcc, 'tcx>( &[field1, field2, field3, field4, field5, field6, field7], ); #[cfg(feature = "master")] - encode_type.as_type().set_packed(); + encode_type.as_type().add_attribute(TypeAttribute::Packed); (encode_type.as_type(), field1, field2) } @@ -45,7 +47,7 @@ fn encode_key_256_type<'a, 'gcc, 'tcx>( &[field1, field2, field3, field4, field5, field6, field7, field8], ); #[cfg(feature = "master")] - encode_type.as_type().set_packed(); + encode_type.as_type().add_attribute(TypeAttribute::Packed); (encode_type.as_type(), field1, field2) } @@ -58,7 +60,7 @@ fn aes_output_type<'a, 'gcc, 'tcx>( let aes_output_type = builder.context.new_struct_type(None, "AesOutput", &[field1, field2]); let typ = aes_output_type.as_type(); #[cfg(feature = "master")] - typ.set_packed(); + typ.add_attribute(TypeAttribute::Packed); (typ, field1, field2) } @@ -81,7 +83,7 @@ fn wide_aes_output_type<'a, 'gcc, 'tcx>( &[field1, field2, field3, field4, field5, field6, field7, field8, field9], ); #[cfg(feature = "master")] - aes_output_type.as_type().set_packed(); + aes_output_type.as_type().add_attribute(TypeAttribute::Packed); (aes_output_type.as_type(), field1, field2) } @@ -478,6 +480,26 @@ pub fn adjust_intrinsic_arguments<'a, 'b, 'gcc, 'tcx>( new_args.push(variable.get_address(None)); args = new_args.into(); } + "__builtin_ia32_2intersectd128" + | "__builtin_ia32_2intersectq128" + | "__builtin_ia32_2intersectd256" + | "__builtin_ia32_2intersectq256" + | "__builtin_ia32_2intersectd512" + | "__builtin_ia32_2intersectq512" => { + let old_args = args.to_vec(); + let mut new_args = vec![]; + let arg1_type = gcc_func.get_param_type(0); + let first_mask = + builder.current_func().new_local(None, arg1_type, "return_2intersect_arg1"); + let arg2_type = gcc_func.get_param_type(1); + let second_mask = + builder.current_func().new_local(None, arg2_type, "return_2intersect_arg2"); + new_args.push(first_mask.get_address(None)); + new_args.push(second_mask.get_address(None)); + new_args.push(old_args[0]); + new_args.push(old_args[1]); + args = new_args.into(); + } "__builtin_ia32_vpermt2varqi512_mask" | "__builtin_ia32_vpermt2varqi256_mask" | "__builtin_ia32_vpermt2varqi128_mask" @@ -489,6 +511,23 @@ pub fn adjust_intrinsic_arguments<'a, 'b, 'gcc, 'tcx>( let minus_one = builder.context.new_rvalue_from_int(arg4_type, -1); args = vec![new_args[1], new_args[0], new_args[2], minus_one].into(); } + "__builtin_ia32_fpclassph128_mask" + | "__builtin_ia32_fpclassph256_mask" + | "__builtin_ia32_fpclassph512_mask" + | "__builtin_ia32_fpclasspd128_mask" + | "__builtin_ia32_fpclassps128_mask" + | "__builtin_ia32_fpclasspd256_mask" + | "__builtin_ia32_fpclassps256_mask" + | "__builtin_ia32_fpclasspd512_mask" + | "__builtin_ia32_fpclassps512_mask" + | "__builtin_ia32_vpshufbitqmb128_mask" + | "__builtin_ia32_vpshufbitqmb256_mask" + | "__builtin_ia32_vpshufbitqmb512_mask" => { + let new_args = args.to_vec(); + let arg3_type = gcc_func.get_param_type(2); + let minus_one = builder.context.new_rvalue_from_int(arg3_type, -1); + args = vec![new_args[0], new_args[1], minus_one].into(); + } "__builtin_ia32_xrstor" | "__builtin_ia32_xrstor64" | "__builtin_ia32_xsavec" @@ -840,7 +879,7 @@ pub fn adjust_intrinsic_return_value<'a, 'gcc, 'tcx>( "__builtin_ia32_rdrand64_step" => { let random_number = args[0].dereference(None).to_rvalue(); let success_variable = - builder.current_func().new_local(None, return_value.get_type(), "success"); + builder.new_temp(builder.current_func(), None, return_value.get_type()); builder.llbb().add_assignment(None, success_variable, return_value); let field1 = builder.context.new_field(None, random_number.get_type(), "random_number"); @@ -854,6 +893,25 @@ pub fn adjust_intrinsic_return_value<'a, 'gcc, 'tcx>( &[random_number, success_variable.to_rvalue()], ); } + "__builtin_ia32_2intersectd128" + | "__builtin_ia32_2intersectq128" + | "__builtin_ia32_2intersectd256" + | "__builtin_ia32_2intersectq256" + | "__builtin_ia32_2intersectd512" + | "__builtin_ia32_2intersectq512" => { + let first_mask = args[0].dereference(None).to_rvalue(); + let second_mask = args[1].dereference(None).to_rvalue(); + let field1 = builder.context.new_field(None, first_mask.get_type(), "first_mask"); + let field2 = builder.context.new_field(None, second_mask.get_type(), "second_mask"); + let struct_type = + builder.context.new_struct_type(None, "vp2intersect_result", &[field1, field2]); + return_value = builder.context.new_struct_constructor( + None, + struct_type.as_type(), + None, + &[first_mask, second_mask], + ); + } "fma" => { let f16_type = builder.context.new_c_type(CType::Float16); return_value = builder.context.new_cast(None, return_value, f16_type); @@ -1182,6 +1240,9 @@ pub fn intrinsic<'gcc, 'tcx>(name: &str, cx: &CodegenCx<'gcc, 'tcx>) -> Function "llvm.x86.avx512.mask.vpshufbitqmb.512" => "__builtin_ia32_vpshufbitqmb512_mask", "llvm.x86.avx512.mask.vpshufbitqmb.256" => "__builtin_ia32_vpshufbitqmb256_mask", "llvm.x86.avx512.mask.vpshufbitqmb.128" => "__builtin_ia32_vpshufbitqmb128_mask", + "llvm.x86.avx512.vpshufbitqmb.512" => "__builtin_ia32_vpshufbitqmb512_mask", + "llvm.x86.avx512.vpshufbitqmb.256" => "__builtin_ia32_vpshufbitqmb256_mask", + "llvm.x86.avx512.vpshufbitqmb.128" => "__builtin_ia32_vpshufbitqmb128_mask", "llvm.x86.avx512.mask.ucmp.w.512" => "__builtin_ia32_ucmpw512_mask", "llvm.x86.avx512.mask.ucmp.w.256" => "__builtin_ia32_ucmpw256_mask", "llvm.x86.avx512.mask.ucmp.w.128" => "__builtin_ia32_ucmpw128_mask", @@ -1339,11 +1400,20 @@ pub fn intrinsic<'gcc, 'tcx>(name: &str, cx: &CodegenCx<'gcc, 'tcx>) -> Function "llvm.x86.avx512bf16.cvtne2ps2bf16.128" => "__builtin_ia32_cvtne2ps2bf16_v8bf", "llvm.x86.avx512bf16.cvtne2ps2bf16.256" => "__builtin_ia32_cvtne2ps2bf16_v16bf", "llvm.x86.avx512bf16.cvtne2ps2bf16.512" => "__builtin_ia32_cvtne2ps2bf16_v32bf", + "llvm.x86.vcvtneps2bf16128" => "__builtin_ia32_cvtneps2bf16_v4sf", + "llvm.x86.vcvtneps2bf16256" => "__builtin_ia32_cvtneps2bf16_v8sf", + "llvm.x86.avx512bf16.mask.cvtneps2bf16.128" => "__builtin_ia32_cvtneps2bf16_v4sf_mask", "llvm.x86.avx512bf16.cvtneps2bf16.256" => "__builtin_ia32_cvtneps2bf16_v8sf", "llvm.x86.avx512bf16.cvtneps2bf16.512" => "__builtin_ia32_cvtneps2bf16_v16sf", "llvm.x86.avx512bf16.dpbf16ps.128" => "__builtin_ia32_dpbf16ps_v4sf", "llvm.x86.avx512bf16.dpbf16ps.256" => "__builtin_ia32_dpbf16ps_v8sf", "llvm.x86.avx512bf16.dpbf16ps.512" => "__builtin_ia32_dpbf16ps_v16sf", + "llvm.x86.avx512.vp2intersect.d.128" => "__builtin_ia32_2intersectd128", + "llvm.x86.avx512.vp2intersect.q.128" => "__builtin_ia32_2intersectq128", + "llvm.x86.avx512.vp2intersect.d.256" => "__builtin_ia32_2intersectd256", + "llvm.x86.avx512.vp2intersect.q.256" => "__builtin_ia32_2intersectq256", + "llvm.x86.avx512.vp2intersect.d.512" => "__builtin_ia32_2intersectd512", + "llvm.x86.avx512.vp2intersect.q.512" => "__builtin_ia32_2intersectq512", "llvm.x86.pclmulqdq.512" => "__builtin_ia32_vpclmulqdq_v8di", "llvm.x86.pclmulqdq.256" => "__builtin_ia32_vpclmulqdq_v4di", "llvm.x86.avx512.pmulhu.w.512" => "__builtin_ia32_pmulhuw512_mask", @@ -1577,38 +1647,79 @@ pub fn intrinsic<'gcc, 'tcx>(name: &str, cx: &CodegenCx<'gcc, 'tcx>) -> Function "llvm.x86.avx512.uitofp.round.v4f64.v4i64" => "__builtin_ia32_cvtuqq2pd256_mask", "llvm.x86.avx512.uitofp.round.v8f32.v8i64" => "__builtin_ia32_cvtuqq2ps512_mask", "llvm.x86.avx512.uitofp.round.v4f32.v4i64" => "__builtin_ia32_cvtuqq2ps256_mask", + "llvm.x86.avx512fp16.fpclass.ph.128" => "__builtin_ia32_fpclassph128_mask", + "llvm.x86.avx512fp16.mask.cmp.ph.128" => "__builtin_ia32_cmpph128_mask", + "llvm.x86.avx512fp16.fpclass.ph.256" => "__builtin_ia32_fpclassph256_mask", + "llvm.x86.avx512fp16.fpclass.ph.512" => "__builtin_ia32_fpclassph512_mask", + "llvm.x86.avx512fp16.mask.cmp.ph.256" => "__builtin_ia32_cmpph256_mask", + "llvm.x86.avx512fp16.mask.cmp.ph.512" => "__builtin_ia32_cmpph512_mask_round", + "llvm.x86.avx512.fpclass.pd.128" => "__builtin_ia32_fpclasspd128_mask", + "llvm.x86.avx512.fpclass.ps.128" => "__builtin_ia32_fpclassps128_mask", + "llvm.x86.avx512.fpclass.pd.256" => "__builtin_ia32_fpclasspd256_mask", + "llvm.x86.avx512.fpclass.ps.256" => "__builtin_ia32_fpclassps256_mask", + "llvm.x86.avx512.fpclass.pd.512" => "__builtin_ia32_fpclasspd512_mask", + "llvm.x86.avx512.fpclass.ps.512" => "__builtin_ia32_fpclassps512_mask", // FIXME: support the tile builtins: "llvm.x86.ldtilecfg" => "__builtin_trap", "llvm.x86.sttilecfg" => "__builtin_trap", "llvm.x86.tileloadd64" => "__builtin_trap", + "llvm.x86.tileloadd64.internal" => "__builtin_trap", "llvm.x86.tilerelease" => "__builtin_trap", "llvm.x86.tilestored64" => "__builtin_trap", + "llvm.x86.tilestored64.internal" => "__builtin_trap", "llvm.x86.tileloaddrs64" => "__builtin_trap", + "llvm.x86.tileloaddrs64.internal" => "__builtin_trap", "llvm.x86.tileloaddt164" => "__builtin_trap", + "llvm.x86.tileloaddt164.internal" => "__builtin_trap", "llvm.x86.tileloaddrst164" => "__builtin_trap", + "llvm.x86.tileloaddrst164.internal" => "__builtin_trap", "llvm.x86.tilezero" => "__builtin_trap", + "llvm.x86.tilezero.internal" => "__builtin_trap", "llvm.x86.tilemovrow" => "__builtin_trap", + "llvm.x86.tilemovrow.internal" => "__builtin_trap", "llvm.x86.tilemovrowi" => "__builtin_trap", "llvm.x86.tdpbhf8ps" => "__builtin_trap", + "llvm.x86.tdpbhf8ps.internal" => "__builtin_trap", "llvm.x86.tdphbf8ps" => "__builtin_trap", + "llvm.x86.tdphbf8ps.internal" => "__builtin_trap", "llvm.x86.tdpbf8ps" => "__builtin_trap", + "llvm.x86.tdpbf8ps.internal" => "__builtin_trap", "llvm.x86.tdphf8ps" => "__builtin_trap", + "llvm.x86.tdphf8ps.internal" => "__builtin_trap", "llvm.x86.tdpbf16ps" => "__builtin_trap", + "llvm.x86.tdpbf16ps.internal" => "__builtin_trap", "llvm.x86.tdpbssd" => "__builtin_trap", + "llvm.x86.tdpbssd.internal" => "__builtin_trap", "llvm.x86.tdpbsud" => "__builtin_trap", + "llvm.x86.tdpbsud.internal" => "__builtin_trap", "llvm.x86.tdpbusd" => "__builtin_trap", + "llvm.x86.tdpbusd.internal" => "__builtin_trap", "llvm.x86.tdpbuud" => "__builtin_trap", + "llvm.x86.tdpbuud.internal" => "__builtin_trap", "llvm.x86.tdpfp16ps" => "__builtin_trap", + "llvm.x86.tdpfp16ps.internal" => "__builtin_trap", "llvm.x86.tmmultf32ps" => "__builtin_trap", + "llvm.x86.tmmultf32ps.internal" => "__builtin_trap", "llvm.x86.tcvtrowps2phh" => "__builtin_trap", + "llvm.x86.tcvtrowps2phh.internal" => "__builtin_trap", "llvm.x86.tcvtrowps2phl" => "__builtin_trap", + "llvm.x86.tcvtrowps2phl.internal" => "__builtin_trap", "llvm.x86.tcvtrowd2ps" => "__builtin_trap", + "llvm.x86.tcvtrowd2ps.internal" => "__builtin_trap", "llvm.x86.tcvtrowd2psi" => "__builtin_trap", "llvm.x86.tcvtrowps2phhi" => "__builtin_trap", "llvm.x86.tcvtrowps2phli" => "__builtin_trap", + "llvm.x86.tcvtrowps2bf16h" => "__builtin_trap", + "llvm.x86.tcvtrowps2bf16h.internal" => "__builtin_trap", + "llvm.x86.tcvtrowps2bf16hi" => "__builtin_trap", + "llvm.x86.tcvtrowps2bf16l" => "__builtin_trap", + "llvm.x86.tcvtrowps2bf16l.internal" => "__builtin_trap", + "llvm.x86.tcvtrowps2bf16li" => "__builtin_trap", "llvm.x86.tcmmimfp16ps" => "__builtin_trap", + "llvm.x86.tcmmimfp16ps.internal" => "__builtin_trap", "llvm.x86.tcmmrlfp16ps" => "__builtin_trap", + "llvm.x86.tcmmrlfp16ps.internal" => "__builtin_trap", // NOTE: this file is generated by https://github.com/GuillaumeGomez/llvmint/blob/master/generate_list.py _ => map_arch_intrinsic(name), diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index 09ad3254e5714..bbf5acf702e21 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -4,7 +4,7 @@ mod simd; #[cfg(feature = "master")] use std::iter; -use gccjit::{ComparisonOp, Function, FunctionType, RValue, ToRValue, Type, UnaryOp}; +use gccjit::{CType, ComparisonOp, Function, FunctionType, RValue, ToRValue, Type, UnaryOp}; use rustc_abi::{Align, BackendRepr, HasDataLayout, WrappingRange}; use rustc_codegen_ssa::base::wants_msvc_seh; use rustc_codegen_ssa::common::IntPredicate; @@ -95,7 +95,6 @@ fn get_simple_intrinsic<'gcc, 'tcx>( sym::floorf64 => "floor", sym::ceilf32 => "ceilf", sym::ceilf64 => "ceil", - sym::powf128 => return float_intrinsic(cx, cx.type_f128(), "powf128"), sym::truncf32 => "truncf", sym::truncf64 => "trunc", // We match the LLVM backend and lower this to `rint`. @@ -118,12 +117,7 @@ fn get_simple_function_f128<'gcc, 'tcx>( let func_name = match name { sym::ceilf128 => "ceilf128", sym::fabs => "fabsf128", - sym::expf128 => "expf128", - sym::exp2f128 => "exp2f128", sym::floorf128 => "floorf128", - sym::logf128 => "logf128", - sym::log2f128 => "log2f128", - sym::log10f128 => "log10f128", sym::truncf128 => "truncf128", sym::roundf128 => "roundf128", sym::round_ties_even_f128 => "roundevenf128", @@ -167,15 +161,8 @@ fn f16_builtin<'gcc, 'tcx>( let builtin_name = match name { sym::ceilf16 => "__builtin_ceilf", sym::copysignf16 => "__builtin_copysignf", - sym::expf16 => "expf", - sym::exp2f16 => "exp2f", - sym::fabs => "fabsf", sym::floorf16 => "__builtin_floorf", sym::fmaf16 => "fmaf", - sym::logf16 => "logf", - sym::log2f16 => "log2f", - sym::log10f16 => "log10f", - sym::powf16 => "__builtin_powf", sym::roundf16 => "__builtin_roundf", sym::round_ties_even_f16 => "__builtin_rintf", sym::sqrtf16 => "__builtin_sqrtf", @@ -210,14 +197,11 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc let simple = get_simple_intrinsic(self, name); let value = match name { - _ if simple.is_some() => { - let func = simple.expect("simple intrinsic function"); - self.cx.context.new_call( - self.location, - func, - &args.iter().map(|arg| arg.immediate()).collect::>(), - ) - } + _ if let Some(func) = simple => self.cx.context.new_call( + self.location, + func, + &args.iter().map(|arg| arg.immediate()).collect::>(), + ), // FIXME(antoyo): We can probably remove these and use the fallback intrinsic implementation. sym::minimumf32 | sym::minimumf64 | sym::maximumf32 | sym::maximumf64 => { let (ty, func_name) = match name { @@ -246,14 +230,8 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc } sym::ceilf16 | sym::copysignf16 - | sym::expf16 - | sym::exp2f16 | sym::floorf16 | sym::fmaf16 - | sym::logf16 - | sym::log2f16 - | sym::log10f16 - | sym::powf16 | sym::roundf16 | sym::round_ties_even_f16 | sym::sqrtf16 @@ -264,11 +242,6 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc | sym::roundf128 | sym::round_ties_even_f128 | sym::sqrtf128 - | sym::expf128 - | sym::exp2f128 - | sym::logf128 - | sym::log2f128 - | sym::log10f128 if self.cx.supports_f128_type => { let func = get_simple_function_f128(span, self, name); @@ -363,7 +336,9 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc unimplemented!(); } sym::va_arg => { - unimplemented!(); + let va_list = args[0].immediate(); + let gcc_type = self.immediate_backend_type(result.layout); + self.va_arg(va_list, gcc_type) } sym::volatile_load | sym::unaligned_volatile_load => { @@ -613,7 +588,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc self.on_stack_function_params.borrow_mut().insert(func, FxHashSet::default()); - crate::attributes::from_fn_attrs(self, func, instance); + crate::attributes::from_fn_attrs(self, func, instance, None); func }; @@ -692,8 +667,18 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc self.context.new_rvalue_from_int(self.int_type, 0) } - fn va_start(&mut self, _va_list: RValue<'gcc>) { - unimplemented!(); + fn va_start(&mut self, va_list: RValue<'gcc>) { + let func = self.context.get_builtin_function("__builtin_va_start"); + + let va_list_type = self.context.new_c_type(CType::VaList); + let va_list = self.context.new_cast(self.location, va_list, va_list_type.make_pointer()); + + // Pre-C23 requires that the last "normal" argument was passed to va_start. + // Just pass 0, this appears to be handled correctly. + let last_normal_arg = self.context.new_rvalue_from_int(self.int_type, 0); + + let call = self.context.new_call(self.location, func, &[va_list, last_normal_arg]); + self.block.add_eval(self.location, call); } fn retag_reg(&mut self, _ptr: Self::Value, _info: &RetagInfo) -> Self::Value { @@ -951,7 +936,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let else_block = func.new_block("else"); let after_block = func.new_block("after"); - let result = func.new_local(None, self.u32_type, "zeros"); + let result = self.new_temp(func, None, self.u32_type); let zero = self.cx.gcc_zero(arg.get_type()); let cond = self.gcc_icmp(IntPredicate::IntEQ, arg, zero); self.llbb().end_with_conditional(None, cond, then_block, else_block); @@ -1032,7 +1017,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { // else call it on the 64 high bits and add 64. In the else case, 64 high bits can't be 0 // because arg is not 0. - let result = self.current_func().new_local(None, result_type, "count_zeroes_results"); + let result = self.new_temp(self.current_func(), None, result_type); let cz_then_block = self.current_func().new_block("cz_then"); let cz_else_block = self.current_func().new_block("cz_else"); @@ -1147,8 +1132,8 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let loop_tail = func.new_block("tail"); let counter_type = self.int_type; - let counter = self.current_func().new_local(None, counter_type, "popcount_counter"); - let val = self.current_func().new_local(None, value_type, "popcount_value"); + let counter = self.new_temp(self.current_func(), None, counter_type); + let val = self.new_temp(self.current_func(), None, value_type); let zero = self.gcc_zero(counter_type); self.llbb().add_assignment(self.location, counter, zero); self.llbb().add_assignment(self.location, val, value); diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/old_archs.rs b/compiler/rustc_codegen_gcc/src/intrinsic/old_archs.rs index 8d3e3487b5cb4..1aac52c28d220 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/old_archs.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/old_archs.rs @@ -1240,6 +1240,10 @@ pub(crate) fn old_archs(arch: &str, name: &str) -> ArchCheckResult { "avx512.vbroadcast.sd.pd.512" => "__builtin_ia32_vbroadcastsd_pd512", "avx512.vbroadcast.ss.512" => "__builtin_ia32_vbroadcastss512", "avx512.vbroadcast.ss.ps.512" => "__builtin_ia32_vbroadcastss_ps512", + "bmi.pdep.32" => "__builtin_ia32_pdep_si", + "bmi.pdep.64" => "__builtin_ia32_pdep_di", + "bmi.pext.32" => "__builtin_ia32_pext_si", + "bmi.pext.64" => "__builtin_ia32_pext_di", "fma.mask.vfmadd.pd.512" => "__builtin_ia32_vfmaddpd512_mask", "fma.mask.vfmadd.ps.512" => "__builtin_ia32_vfmaddps512_mask", "fma.mask.vfmaddsub.pd.512" => "__builtin_ia32_vfmaddsubpd512_mask", diff --git a/compiler/rustc_codegen_gcc/src/lib.rs b/compiler/rustc_codegen_gcc/src/lib.rs index 55c721a9706a6..436f8a1176300 100644 --- a/compiler/rustc_codegen_gcc/src/lib.rs +++ b/compiler/rustc_codegen_gcc/src/lib.rs @@ -76,9 +76,9 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; -use gccjit::{CType, Context, OptimizationLevel}; #[cfg(feature = "master")] -use gccjit::{TargetInfo, Version}; +use gccjit::TargetInfo; +use gccjit::{CType, Context, OptimizationLevel}; use rustc_ast::expand::allocator::AllocatorMethod; use rustc_codegen_ssa::back::lto::ThinModule; use rustc_codegen_ssa::back::write::{ @@ -97,7 +97,7 @@ use rustc_middle::util::Providers; use rustc_session::Session; use rustc_session::config::{OptLevel, OutputFilenames}; use rustc_span::{Symbol, sym}; -use rustc_target::spec::{Arch, RelocModel}; +use rustc_target::spec::RelocModel; use tempfile::TempDir; use crate::back::lto::ModuleBuffer; @@ -197,8 +197,10 @@ impl CodegenBackend for GccCodegenBackend { fn init(&self, sess: &Session) { fn file_path(sysroot_path: &Path, sess: &Session) -> PathBuf { - let rustlib_path = - rustc_target::relative_target_rustlib_path(sysroot_path, &sess.host.llvm_target); + let rustlib_path = rustc_target::relative_target_rustlib_path( + sysroot_path, + rustc_session::config::host_tuple(), + ); sysroot_path .join(rustlib_path) .join("codegen-backends") @@ -315,27 +317,6 @@ impl CodegenBackend for GccCodegenBackend { } } -fn new_context<'gcc, 'tcx>(tcx: TyCtxt<'tcx>) -> Context<'gcc> { - let context = Context::default(); - if matches!(tcx.sess.target.arch, Arch::X86 | Arch::X86_64) { - context.add_command_line_option("-masm=intel"); - } - #[cfg(feature = "master")] - { - context.set_special_chars_allowed_in_func_names("$.*"); - let version = Version::get(); - let version = format!("{}.{}.{}", version.major, version.minor, version.patch); - context.set_output_ident(&format!( - "rustc version {} with libgccjit {}", - rustc_interface::util::rustc_version_str().unwrap_or("unknown version"), - version, - )); - } - // FIXME(antoyo): check if this should only be added when using -Cforce-unwind-tables=n. - context.add_command_line_option("-fno-asynchronous-unwind-tables"); - context -} - impl ExtraBackendMethods for GccCodegenBackend { type Module = GccContext; @@ -347,7 +328,7 @@ impl ExtraBackendMethods for GccCodegenBackend { ) -> Self::Module { let lto_supported = self.lto_supported.load(Ordering::SeqCst); let mut mods = GccContext { - context: Arc::new(SyncContext::new(new_context(tcx))), + context: Arc::new(SyncContext::new(gcc_util::new_context(tcx.sess))), relocation_model: tcx.sess.relocation_model(), lto_mode: LtoMode::None, lto_supported, @@ -444,7 +425,7 @@ impl WriteBackendMethods for GccCodegenBackend { each_linked_rlib_for_lto: &[PathBuf], modules: Vec>, ) -> CompiledModule { - back::lto::run_fat(cgcx, &sess.prof, shared_emitter, each_linked_rlib_for_lto, modules) + back::lto::run_fat(sess, cgcx, shared_emitter, each_linked_rlib_for_lto, modules) } fn run_thin_lto( diff --git a/compiler/rustc_codegen_gcc/src/mono_item.rs b/compiler/rustc_codegen_gcc/src/mono_item.rs index d5874779021d2..7513978b12272 100644 --- a/compiler/rustc_codegen_gcc/src/mono_item.rs +++ b/compiler/rustc_codegen_gcc/src/mono_item.rs @@ -1,11 +1,12 @@ +use gccjit::Function; #[cfg(feature = "master")] -use gccjit::{FnAttribute, VarAttribute}; +use gccjit::{FnAttribute, LValue, ToRValue, VarAttribute}; use rustc_codegen_ssa::traits::PreDefineCodegenMethods; use rustc_hir::attrs::Linkage; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_middle::bug; -use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; +use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs}; use rustc_middle::mono::Visibility; use rustc_middle::ty::layout::{FnAbiOf, HasTypingEnv, LayoutOf}; use rustc_middle::ty::{self, Instance, TypeVisitableExt}; @@ -21,7 +22,7 @@ impl<'gcc, 'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { def_id: DefId, _linkage: Linkage, visibility: Visibility, - symbol_name: &str, + global_name: &str, ) { let attrs = self.tcx.codegen_fn_attrs(def_id); let instance = Instance::mono(self.tcx, def_id); @@ -33,11 +34,20 @@ impl<'gcc, 'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { let gcc_type = self.layout_of(ty).gcc_type(self); let is_tls = attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL); - let global = self.define_global(symbol_name, gcc_type, is_tls, attrs.link_section); + + let create_global = |this: &CodegenCx<'gcc, 'tcx>, name: &str, visibility: Visibility| { + let global = this.define_global(name, gcc_type, is_tls, attrs.link_section); + #[cfg(feature = "master")] + global.add_attribute(VarAttribute::Visibility(base::visibility_to_gcc(visibility))); + // FIXME(antoyo): set linkage. + global + }; + let global = create_global(self, global_name, visibility); + + let attrs = self.tcx.codegen_instance_attrs(instance.def); #[cfg(feature = "master")] - global.add_attribute(VarAttribute::Visibility(base::visibility_to_gcc(visibility))); + self.add_static_aliases(&attrs.foreign_item_symbol_aliases, global_name, &create_global); - // FIXME(antoyo): set linkage. self.instances.borrow_mut().insert(instance, global); } @@ -50,12 +60,98 @@ impl<'gcc, 'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { ) { assert!(!instance.args.has_infer()); + let attrs = self.tcx.codegen_instance_attrs(instance.def); + + let decl = + self.predefine_without_aliases(instance, &attrs, linkage, visibility, symbol_name); + + #[cfg(feature = "master")] + self.add_function_aliases(instance, decl, &attrs, &attrs.foreign_item_symbol_aliases); + + self.functions.borrow_mut().insert(symbol_name.to_string(), decl); + self.function_instances.borrow_mut().insert(instance, decl); + } +} + +impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { + #[cfg(feature = "master")] + fn add_static_aliases( + &self, + aliases: &[(DefId, Linkage, Visibility)], + aliased: &str, + create_global: &F, + ) where + F: Fn(&CodegenCx<'gcc, 'tcx>, &str, Visibility) -> LValue<'gcc>, + { + for &(alias, _linkage, visibility) in aliases { + let instance = Instance::mono(self.tcx, alias); + let symbol_name = self.tcx.symbol_name(instance); + + let alias = create_global(self, symbol_name.name, visibility); + alias.add_attribute(VarAttribute::Alias(aliased)); + + // Add the alias name to the set of cached items, so there is no duplicate + // instance added to it during the normal `external static` codegen + let prev_entry = self.instances.borrow_mut().insert(instance, alias); + + // If there already was a previous entry, then `add_static_aliases` was called multiple times for the same `alias` + // which would result in incorrect codegen + assert!(prev_entry.is_none(), "An instance was already present for {instance:?}"); + } + } + + #[cfg(feature = "master")] + fn add_function_aliases( + &self, + aliased_instance: Instance<'tcx>, + aliased: Function<'gcc>, + attrs: &CodegenFnAttrs, + aliases: &[(DefId, Linkage, Visibility)], + ) { + for &(alias, linkage, visibility) in aliases { + let symbol_name = self.tcx.symbol_name(Instance::mono(self.tcx, alias)); + + // predefine another copy of the original instance + // with a new symbol name + let alias_fn_decl = self.predefine_without_aliases( + aliased_instance, + attrs, + linkage, + visibility, + symbol_name.name, + ); + + let block = alias_fn_decl.new_block("start"); + let nb_params = alias_fn_decl.get_param_count(); + let mut args = Vec::with_capacity(nb_params); + for idx in 0..nb_params { + args.push(alias_fn_decl.get_param(idx as _).to_rvalue()); + } + + let void_type = self.context.new_type::<()>(); + let call = self.context.new_call(None, aliased, &args); + if alias_fn_decl.get_return_type() == void_type { + block.add_eval(None, call); + block.end_with_void_return(None); + } else { + block.end_with_return(None, call); + } + } + } + + fn predefine_without_aliases( + &self, + instance: Instance<'tcx>, + _attrs: &CodegenFnAttrs, + linkage: Linkage, + visibility: Visibility, + symbol_name: &str, + ) -> Function<'gcc> { let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty()); self.linkage.set(base::linkage_to_gcc(linkage)); - let decl = self.declare_fn(symbol_name, fn_abi); - //let attrs = self.tcx.codegen_instance_attrs(instance.def); + let fn_decl = self.declare_fn(symbol_name, fn_abi); - attributes::from_fn_attrs(self, decl, instance); + attributes::from_fn_attrs(self, fn_decl, instance, Some(fn_abi)); // If we're compiling the compiler-builtins crate, e.g., the equivalent of // compiler-rt, then we want to implicitly compile everything with hidden @@ -63,17 +159,21 @@ impl<'gcc, 'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { // don't want the symbols to get exported. if linkage != Linkage::Internal && self.tcx.is_compiler_builtins(LOCAL_CRATE) { #[cfg(feature = "master")] - decl.add_attribute(FnAttribute::Visibility(gccjit::Visibility::Hidden)); + fn_decl.add_attribute(FnAttribute::Visibility(gccjit::Visibility::Hidden)); } else if visibility != Visibility::Default { #[cfg(feature = "master")] - decl.add_attribute(FnAttribute::Visibility(base::visibility_to_gcc(visibility))); + fn_decl.add_attribute(FnAttribute::Visibility(base::visibility_to_gcc(visibility))); + } + + #[cfg(feature = "master")] + if let Some(section) = _attrs.link_section { + fn_decl.add_attribute(FnAttribute::Section(section.as_str())); } - // FIXME(antoyo): call set_link_section() to allow initializing argc/argv. // FIXME(antoyo): set unique comdat. // FIXME(antoyo): use inline attribute from there in linkage.set() above. + // FIXME: Should we handle dso? - self.functions.borrow_mut().insert(symbol_name.to_string(), decl); - self.function_instances.borrow_mut().insert(instance, decl); + fn_decl } } diff --git a/compiler/rustc_codegen_gcc/src/type_.rs b/compiler/rustc_codegen_gcc/src/type_.rs index 5252f93a92ebe..f008be67e39cb 100644 --- a/compiler/rustc_codegen_gcc/src/type_.rs +++ b/compiler/rustc_codegen_gcc/src/type_.rs @@ -2,7 +2,7 @@ use std::convert::TryInto; #[cfg(feature = "master")] -use gccjit::CType; +use gccjit::{CType, TypeAttribute}; use gccjit::{RValue, Struct, Type}; use rustc_abi::{AddressSpace, Align, Integer, Size}; use rustc_codegen_ssa::common::TypeKind; @@ -116,7 +116,7 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { let typ = self.context.new_struct_type(None, "struct", &fields).as_type(); if packed { #[cfg(feature = "master")] - typ.set_packed(); + typ.add_attribute(TypeAttribute::Packed); } self.struct_types.borrow_mut().insert(types, typ); typ @@ -153,7 +153,7 @@ impl<'gcc, 'tcx> BaseTypeCodegenMethods for CodegenCx<'gcc, 'tcx> { if self.supports_f16_type { return self.context.new_c_type(CType::Float16); } - bug!("unsupported float width 16") + self.u16_type } fn type_f32(&self) -> Type<'gcc> { @@ -333,7 +333,7 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { typ.set_fields(None, &fields); if packed { #[cfg(feature = "master")] - typ.as_type().set_packed(); + typ.as_type().add_attribute(TypeAttribute::Packed); } } diff --git a/compiler/rustc_codegen_gcc/tests/asm/asm/comments.rs b/compiler/rustc_codegen_gcc/tests/asm/asm/comments.rs new file mode 100644 index 0000000000000..603bb014930c4 --- /dev/null +++ b/compiler/rustc_codegen_gcc/tests/asm/asm/comments.rs @@ -0,0 +1,12 @@ +//@ assembly-output: emit-asm +//@ only-x86_64 +// Check that comments in assembly get passed + +#![crate_type = "lib"] + +// CHECK-LABEL: "test_comments": +#[no_mangle] +pub fn test_comments() { + // CHECK: example comment + unsafe { core::arch::asm!("nop // example comment") }; +} diff --git a/compiler/rustc_codegen_gcc/tests/asm/naked-functions/x86_64-naked-fn-no-cet-prolog.rs b/compiler/rustc_codegen_gcc/tests/asm/naked-functions/x86_64-naked-fn-no-cet-prolog.rs new file mode 100644 index 0000000000000..81ee9b13b4eca --- /dev/null +++ b/compiler/rustc_codegen_gcc/tests/asm/naked-functions/x86_64-naked-fn-no-cet-prolog.rs @@ -0,0 +1,24 @@ +//@ compile-flags: -C no-prepopulate-passes -Zcf-protection=full +//@ assembly-output: emit-asm +//@ needs-asm-support +//@ only-x86_64 + +#![crate_type = "lib"] + +use std::arch::naked_asm; + +// The problem at hand: Rust has adopted a fairly strict meaning for "naked functions", +// meaning "no prologue whatsoever, no, really, not one instruction." +// Unfortunately, x86's control-flow enforcement, specifically indirect branch protection, +// works by using an instruction for each possible landing site, +// and LLVM implements this via making sure of that. +#[no_mangle] +#[unsafe(naked)] +pub extern "sysv64" fn will_halt() -> ! { + // CHECK-NOT: endbr{{32|64}} + // CHECK: hlt + naked_asm!("hlt") +} + +// what about aarch64? +// "branch-protection"=false diff --git a/compiler/rustc_codegen_gcc/tests/asm/panic-no-unwind-no-uwtable.rs b/compiler/rustc_codegen_gcc/tests/asm/panic-no-unwind-no-uwtable.rs new file mode 100644 index 0000000000000..b51b173e9616e --- /dev/null +++ b/compiler/rustc_codegen_gcc/tests/asm/panic-no-unwind-no-uwtable.rs @@ -0,0 +1,8 @@ +//@ assembly-output: emit-asm +//@ only-x86_64-unknown-linux-gnu +//@ compile-flags: -C panic=unwind -C force-unwind-tables=n -Copt-level=3 + +#![crate_type = "lib"] + +// CHECK-NOT: .cfi_startproc +pub fn foo() {} diff --git a/compiler/rustc_codegen_gcc/tests/asm/used.rs b/compiler/rustc_codegen_gcc/tests/asm/used.rs new file mode 100644 index 0000000000000..deb0c69dc48fa --- /dev/null +++ b/compiler/rustc_codegen_gcc/tests/asm/used.rs @@ -0,0 +1,14 @@ +//@ assembly-output: emit-asm +//@ only-x86_64-unknown-linux-gnu + +#![feature(used_with_arg)] +#![crate_type = "lib"] + +// CHECK: .section .rodata.X,"a" +#[used(compiler)] +#[no_mangle] +pub static X: u32 = 12; +// CHECK: .section .rodata.Y,"aR" +#[used(linker)] +#[no_mangle] +pub static Y: u32 = 12; diff --git a/compiler/rustc_codegen_gcc/tests/asm/x86_64-sse_crc.rs b/compiler/rustc_codegen_gcc/tests/asm/x86_64-sse_crc.rs new file mode 100644 index 0000000000000..bde58955a2146 --- /dev/null +++ b/compiler/rustc_codegen_gcc/tests/asm/x86_64-sse_crc.rs @@ -0,0 +1,12 @@ +//@ only-x86_64 +//@ assembly-output: emit-asm +//@ compile-flags: --crate-type staticlib -Ctarget-feature=+sse4.2 + +// CHECK-LABEL: banana +// CHECK: crc32 +#[no_mangle] +pub unsafe fn banana(v: u8) -> u32 { + use std::arch::x86_64::*; + let out = !0u32; + _mm_crc32_u8(out, v) +} diff --git a/compiler/rustc_codegen_gcc/tests/compile/x86_interrupt_first_arg_byval.rs b/compiler/rustc_codegen_gcc/tests/compile/x86_interrupt_first_arg_byval.rs new file mode 100644 index 0000000000000..4b6bbd48f7ad5 --- /dev/null +++ b/compiler/rustc_codegen_gcc/tests/compile/x86_interrupt_first_arg_byval.rs @@ -0,0 +1,16 @@ +// Compiler: + +// Test that `x86-interrupt` functions whose first argument is passed by value +// emit pointer-shaped GCC parameters and compile with interrupt-safe target features. + +#![feature(abi_x86_interrupt)] +#![crate_type = "lib"] + +#[repr(C)] +pub struct Frame { + ip: u64, +} + +pub extern "x86-interrupt" fn scalar(_a: i64) {} + +pub extern "x86-interrupt" fn aggregate(_frame: Frame) {} diff --git a/compiler/rustc_codegen_gcc/tests/cpuid.def b/compiler/rustc_codegen_gcc/tests/cpuid.def new file mode 100644 index 0000000000000..05fe8e94a8282 --- /dev/null +++ b/compiler/rustc_codegen_gcc/tests/cpuid.def @@ -0,0 +1,27 @@ +# Input => Output +# EAX ECX => EAX EBX ECX EDX +00000000 ******** => 00000024 756e6547 6c65746e 49656e69 #Processor ID and Manufacturer +00000001 ******** => 00400f10 00100800 7ffaf3ff bfebfbff +00000007 00000000 => 00000002 f3bfbfbf bac05ffe 03d54130 #Extended Features +00000007 00000001 => 98ee00bf 00000002 00000020 1d29cd3e +0000000d 00000000 => 000e02e7 00002b00 00002b00 00000000 #xcr0 +0000000d 00000001 => 0000001f 00000240 00000100 00000000 #Supervisor State +0000000d 00000002 => 00000100 00000240 00000000 00000000 +0000000d 00000005 => 00000040 00000440 00000000 00000000 #zmasks +0000000d 00000006 => 00000200 00000480 00000000 00000000 #zmmh +0000000d 00000007 => 00000400 00000680 00000000 00000000 #zmm +0000000d 00000011 => 00000040 00000ac0 00000002 00000000 #tileconfig +0000000d 00000012 => 00002000 00000b00 00000006 00000000 #tiles +0000000d 00000013 => 00000080 000003c0 00000000 00000000 #APX +00000019 ******** => 00000000 00000005 00000000 00000000 #Key Locker +0000001d 00000000 => 00000001 00000000 00000000 00000000 #AMX Tile +0000001d 00000001 => 04002000 00080040 00000010 00000000 #AMX Palette1 +0000001e 00000000 => 00000001 00004010 00000000 00000000 #AMX Tmul +0000001e 00000001 => 000001ff 00000000 00000000 00000000 +00000024 00000000 => 00000001 00070002 00000000 00000000 #AVX10 +00000024 00000001 => 00000000 00000000 00000004 00000000 +80000000 ******** => 80000004 00000000 00000000 00000000 +80000001 ******** => 00000000 00000000 00000121 2c100000 +80000002 ******** => 00000000 00000000 00000000 00000000 +80000003 ******** => 00000000 00000000 00000000 00000000 +80000004 ******** => 00000000 00000000 00000000 00000000 diff --git a/compiler/rustc_codegen_gcc/tests/failing-lto-tests.txt b/compiler/rustc_codegen_gcc/tests/failing-lto-tests.txt index 4c62c35a512c1..e98d2aab9361b 100644 --- a/compiler/rustc_codegen_gcc/tests/failing-lto-tests.txt +++ b/compiler/rustc_codegen_gcc/tests/failing-lto-tests.txt @@ -4,3 +4,7 @@ tests/ui/uninhabited/uninhabited-transparent-return-abi.rs tests/ui/coroutine/panic-drops-resume.rs tests/ui/coroutine/panic-drops.rs tests/ui/coroutine/panic-safe.rs +tests/ui/panic-handler/catch-unwind-during-unwind-68696.rs +tests/ui/threads-sendsync/task-stderr.rs +tests/ui/extern/issue-64655-allow-unwind-when-calling-panic-directly.rs +tests/ui/extern/issue-64655-extern-rust-must-allow-unwind.rs diff --git a/compiler/rustc_codegen_gcc/tests/failing-run-make-tests.txt b/compiler/rustc_codegen_gcc/tests/failing-run-make-tests.txt index 528ee1df9f583..1feb2c7cc6edc 100644 --- a/compiler/rustc_codegen_gcc/tests/failing-run-make-tests.txt +++ b/compiler/rustc_codegen_gcc/tests/failing-run-make-tests.txt @@ -12,3 +12,4 @@ tests/run-make/glibc-staticlib-args/ tests/run-make/lto-smoke-c/ tests/run-make/return-non-c-like-enum/ tests/run-make/short-ice +tests/run-make/embed-source-dwarf diff --git a/compiler/rustc_codegen_gcc/tests/failing-ui-tests.txt b/compiler/rustc_codegen_gcc/tests/failing-ui-tests.txt index e8a26a90890c1..2b2f21904abb5 100644 --- a/compiler/rustc_codegen_gcc/tests/failing-ui-tests.txt +++ b/compiler/rustc_codegen_gcc/tests/failing-ui-tests.txt @@ -11,27 +11,22 @@ tests/ui/mir/mir_match_guard_let_chains_drop_order.rs tests/ui/panic-runtime/abort-link-to-unwinding-crates.rs tests/ui/panic-runtime/abort.rs tests/ui/panic-runtime/link-to-abort.rs -tests/ui/parser/unclosed-delimiter-in-dep.rs tests/ui/consts/missing_span_in_backtrace.rs tests/ui/drop/dynamic-drop.rs tests/ui/simd/issue-17170.rs tests/ui/simd/issue-39720.rs tests/ui/drop/panic-during-drop-14875.rs -tests/ui/issues/issue-29948.rs +tests/ui/drop/move-closure-drop-on-unwind.rs tests/ui/process/println-with-broken-pipe.rs tests/ui/lto/thin-lto-inlines2.rs tests/ui/panic-runtime/lto-abort.rs tests/ui/lto/lto-thin-rustc-loads-linker-plugin.rs tests/ui/async-await/deep-futures-are-freeze.rs tests/ui/coroutine/resume-after-return.rs -tests/ui/simd/masked-load-store.rs tests/ui/simd/repr_packed.rs tests/ui/async-await/in-trait/dont-project-to-specializable-projection.rs tests/ui/coroutine/unwind-abort-mix.rs -tests/ui/consts/issue-miri-1910.rs tests/ui/consts/const_cmp_type_id.rs -tests/ui/consts/issue-94675.rs -tests/ui/traits/const-traits/const-drop-fail.rs tests/ui/runtime/on-broken-pipe/child-processes.rs tests/ui/sanitizer/cfi/assoc-ty-lifetime-issue-123053.rs tests/ui/sanitizer/cfi/async-closures.rs @@ -47,7 +42,6 @@ tests/ui/sanitizer/cfi/virtual-auto.rs tests/ui/sanitizer/cfi/sized-associated-ty.rs tests/ui/sanitizer/cfi/can-reveal-opaques.rs tests/ui/sanitizer/kcfi-mangling.rs -tests/ui/delegation/fn-header.rs tests/ui/consts/const-eval/parse_ints.rs tests/ui/simd/intrinsic/generic-as.rs tests/ui/runtime/rt-explody-panic-payloads.rs @@ -67,47 +61,53 @@ tests/ui/simd/simd-bitmask-notpow2.rs tests/ui/codegen/StackColoring-not-blowup-stack-issue-40883.rs tests/ui/numbers-arithmetic/u128-as-f32.rs tests/ui/process/nofile-limit.rs -tests/ui/linking/no-gc-encapsulation-symbols.rs tests/ui/panics/unwind-force-no-unwind-tables.rs tests/ui/attributes/fn-align-dyn.rs tests/ui/linkage-attr/raw-dylib/elf/glibc-x86_64.rs -tests/ui/explicit-tail-calls/recursion-etc.rs -tests/ui/explicit-tail-calls/indexer.rs -tests/ui/explicit-tail-calls/drop-order.rs -tests/ui/c-variadic/valid.rs -tests/ui/c-variadic/inherent-method.rs -tests/ui/c-variadic/trait-method.rs -tests/ui/explicit-tail-calls/become-cast-return.rs -tests/ui/explicit-tail-calls/become-indirect-return.rs tests/ui/panics/panic-abort-backtrace-without-debuginfo.rs tests/ui/sanitizer/kcfi-c-variadic.rs tests/ui/sanitizer/kcfi/fn-trait-objects.rs tests/ui/statics/const_generics.rs tests/ui/test-attrs/test-panic-while-printing.rs tests/ui/thir-print/offset_of.rs -tests/ui/iterators/rangefrom-overflow-debug.rs -tests/ui/iterators/rangefrom-overflow-overflow-checks.rs tests/ui/iterators/iter-filter-count-debug-check.rs -tests/ui/eii/linking/codegen_single_crate.rs -tests/ui/eii/linking/codegen_cross_crate.rs -tests/ui/eii/default/local_crate.rs -tests/ui/eii/duplicate/multiple_impls.rs -tests/ui/eii/default/call_default.rs -tests/ui/eii/linking/same-symbol.rs -tests/ui/eii/privacy1.rs tests/ui/eii/default/call_impl.rs -tests/ui/c-variadic/copy.rs tests/ui/asm/x86_64/global_asm_escape.rs tests/ui/lto/all-crates.rs -tests/ui/consts/const-eval/c-variadic.rs -tests/ui/eii/default/call_default_panics.rs -tests/ui/explicit-tail-calls/indirect.rs -tests/ui/traits/inheritance/self-in-supertype.rs -tests/ui/fmt/fmt_debug/shallow.rs -tests/ui/c-variadic/roundtrip.rs -tests/ui/eii/eii_impl_with_contract.rs tests/ui/eii/static/cross_crate_decl.rs tests/ui/eii/static/cross_crate_def.rs tests/ui/eii/static/same_address.rs tests/ui/eii/static/simple.rs -tests/ui/explicit-tail-calls/default-trait-method.rs +tests/ui/eii/static/default.rs +tests/ui/eii/static/default_cross_crate.rs +tests/ui/eii/static/default_explicit.rs +tests/ui/eii/static/default_cross_crate_explicit.rs +tests/ui/explicit-tail-calls/tailcc-no-signature-restriction.rs +tests/ui/abi/rust-tail-cc.rs +tests/ui/abi/rust-preserve-none-cc.rs +tests/ui/extern/extern-types-field-offset.rs +tests/ui/numbers-arithmetic/int-abs-overflow.rs +tests/ui/numbers-arithmetic/issue-8460.rs +tests/ui/panics/panic-handler-chain-update-hook.rs +tests/ui/panics/panic-handler-chain.rs +tests/ui/panics/panic-handler-set-twice.rs +tests/ui/panics/panic-recover-propagate.rs +tests/ui/panics/panic-in-dtor-drops-fields.rs +tests/ui/panics/panic-handler-flail-wildly.rs +tests/ui/panics/rvalue-cleanup-during-box-panic.rs +tests/ui/process/multi-panic.rs +tests/ui/sepcomp/sepcomp-unwind.rs +tests/ui/structs/unit-like-struct-drop-run.rs +tests/ui/threads-sendsync/unwind-resource.rs +tests/ui/array-slice-vec/box-of-array-of-drop-2.rs +tests/ui/array-slice-vec/box-of-array-of-drop-1.rs +tests/ui/array-slice-vec/nested-vec-3.rs +tests/ui/array-slice-vec/slice-panic-1.rs +tests/ui/array-slice-vec/slice-panic-2.rs +tests/ui/backtrace/synchronized-panic-handler.rs +tests/ui/cross-crate/mut-ref-write-visible-after-unwind.rs +tests/ui/drop/drop-once-on-panic.rs +tests/ui/drop/enum-destructor-on-unwind.rs +tests/ui/drop/drop-trait-enum.rs +tests/ui/drop/panic-during-slice-init.rs +tests/ui/drop/terminate-in-initializer.rs diff --git a/compiler/rustc_codegen_gcc/tests/lang_tests.rs b/compiler/rustc_codegen_gcc/tests/lang_tests.rs index 6afd54e1c3fe0..f3b4ad34bc9c4 100644 --- a/compiler/rustc_codegen_gcc/tests/lang_tests.rs +++ b/compiler/rustc_codegen_gcc/tests/lang_tests.rs @@ -172,6 +172,16 @@ fn build_test_runner( } } + // Extra flags passed at run time (as opposed to the compile-time + // `TEST_FLAGS`). This lets a single test opt into flags like + // `-Zmir-preserve-ub` via an `ignore-if` directive that checks + // whether `CARGO_TEST_FLAGS` is set. + if let Ok(flags) = std::env::var("CARGO_TEST_FLAGS") { + for flag in flags.split_whitespace() { + compiler_args.push(flag.into()); + } + } + if build_mode.is_debug() { compiler_args .extend_from_slice(&["-C".to_string(), "llvm-args=sanitize-undefined".into()]); @@ -201,7 +211,13 @@ fn compile_tests(tempdir: PathBuf, current_dir: String) { "lang compile", "tests/compile", TestMode::Compile, - &["simd-ffi.rs", "asm_nul_byte.rs", "global_asm_nul_byte.rs", "naked_asm_nul_byte.rs"], + &[ + "simd-ffi.rs", + "asm_nul_byte.rs", + "global_asm_nul_byte.rs", + "naked_asm_nul_byte.rs", + "x86_interrupt_first_arg_byval.rs", + ], ); } diff --git a/compiler/rustc_codegen_gcc/tests/run/asm.rs b/compiler/rustc_codegen_gcc/tests/run/asm.rs index 01775c92ffc8a..42141c671b596 100644 --- a/compiler/rustc_codegen_gcc/tests/run/asm.rs +++ b/compiler/rustc_codegen_gcc/tests/run/asm.rs @@ -3,6 +3,8 @@ // Run-time: // status: 0 +#![feature(asm_goto_with_outputs)] + #[cfg(target_arch = "x86_64")] use std::arch::{asm, global_asm}; @@ -32,6 +34,20 @@ pub unsafe fn mem_cpy(dst: *mut u8, src: *const u8, len: usize) { ); } +#[cfg(target_arch = "x86_64")] +#[unsafe(no_mangle)] +pub fn asm_goto_test(mut a: i16) -> i16 { + unsafe { + std::arch::asm!( + "jmp {op}", + inout("eax") a, + op = label { a = 7; }, + options(nostack,nomem) + ); + a + } +} + #[cfg(target_arch = "x86_64")] fn asm() { unsafe { @@ -190,6 +206,14 @@ fn asm() { } assert_eq!((x, y), (8, 8)); + // Regression test for + // typed pointer inputs to explicit registers need a cast. + let mut x = 123_i32; + unsafe { + asm!("", in("rdi") &mut x, options(nostack, preserves_flags)); + } + assert_eq!(x, 123); + // sysv64 is the default calling convention on unix systems. The rdi register is // used to pass arguments in the sysv64 calling convention, so this register will be clobbered #[cfg(unix)] @@ -227,6 +251,24 @@ fn asm() { out("r15b") _, ); } + + // Make sure the input value from inout is assigned to the input value + unsafe { + // Use a very distinctive value unlikely to live in any register. + let input: u64 = 0x1234567890ABCDEF; + let mut output: u64; + + asm!( + "push {1}", + "pop {0}", + out(reg) output, + inout(reg) input => _, + ); + + assert_eq!(output, 0x1234567890ABCDEF); + } + + asm_goto_test(0); } #[cfg(not(target_arch = "x86_64"))] diff --git a/compiler/rustc_codegen_gcc/tests/run/int.rs b/compiler/rustc_codegen_gcc/tests/run/int.rs index 78675acb5447b..ef825b4d80185 100644 --- a/compiler/rustc_codegen_gcc/tests/run/int.rs +++ b/compiler/rustc_codegen_gcc/tests/run/int.rs @@ -319,4 +319,29 @@ fn main() { const VAL5: T = 73236519889708027473620326106273939584_i128; check_ops128!(); } + + { + #[allow(dead_code)] + #[repr(u8)] + enum Inner { + L0 = 0, + H255 = 255, + } + #[allow(dead_code)] + enum O { + A(Inner), + B, + C, + } + + #[inline(never)] + fn which(o: &O) -> &'static str { + match o { + O::A(_) => "a", + O::B => "b", + O::C => "c", + } + } + assert_eq!(which(black_box(&O::A(Inner::H255))), "a"); + } } diff --git a/compiler/rustc_codegen_gcc/tests/run/mir_preserve_ub_empty_switch.rs b/compiler/rustc_codegen_gcc/tests/run/mir_preserve_ub_empty_switch.rs new file mode 100644 index 0000000000000..26056360b9212 --- /dev/null +++ b/compiler/rustc_codegen_gcc/tests/run/mir_preserve_ub_empty_switch.rs @@ -0,0 +1,35 @@ +// ignore-if: test -z "$CARGO_TEST_FLAGS" +// Compiler: +// +// Run-time: +// status: 0 + +// Regression test for https://github.com/rust-lang/rustc_codegen_gcc/issues/881 +// +// This needs `-Zmir-preserve-ub`, so it is skipped unless that flag is passed +// through `CARGO_TEST_FLAGS` (see the `ignore-if` directive above). Run it with: +// CARGO_TEST_FLAGS="-Zmir-preserve-ub" ./y.sh test --cargo-tests -- mir_preserve_ub_empty_switch + +#![feature(no_core)] +#![no_std] +#![no_core] +#![no_main] + +extern crate mini_core; +use intrinsics::black_box; +use mini_core::*; + +#[no_mangle] +extern "C" fn main(argc: i32, _argv: *const *const u8) -> i32 { + // With `-Zmir-preserve-ub`, the range pattern below is lowered to a pair of + // comparisons and the second one becomes a `SwitchInt` with no cases (only + // an `otherwise` target) whose discriminant is the `bool` comparison + // result. `gcc_jit_block_end_with_switch` rejects a non-integer + // discriminant, so the backend must emit a plain jump for it instead. + let value = black_box(argc); + match value { + 0..=9 => (), + _ => (), + } + 0 +} diff --git a/compiler/rustc_codegen_gcc/tools/cspell_dicts/rust.txt b/compiler/rustc_codegen_gcc/tools/cspell_dicts/rust.txt index 379cbd77eef01..15faacd53d5a0 100644 --- a/compiler/rustc_codegen_gcc/tools/cspell_dicts/rust.txt +++ b/compiler/rustc_codegen_gcc/tools/cspell_dicts/rust.txt @@ -1,2 +1,3 @@ lateout repr +rmeta diff --git a/compiler/rustc_codegen_gcc/tools/cspell_dicts/rustc_codegen_gcc.txt b/compiler/rustc_codegen_gcc/tools/cspell_dicts/rustc_codegen_gcc.txt index 4fb018b3ecd87..bae8edc9ffdf9 100644 --- a/compiler/rustc_codegen_gcc/tools/cspell_dicts/rustc_codegen_gcc.txt +++ b/compiler/rustc_codegen_gcc/tools/cspell_dicts/rustc_codegen_gcc.txt @@ -60,10 +60,12 @@ nvptx pointee powitf reassoc +retag riscv rlib roundevenf rustc +sgpr sitofp sizet spir @@ -74,5 +76,8 @@ uitofp unord uninlined utrunc +vgpr xabort +xreg +xtensa zext diff --git a/compiler/rustc_codegen_gcc/tools/generate_intrinsics.py b/compiler/rustc_codegen_gcc/tools/generate_intrinsics.py index 5390323407779..06425f682a88b 100644 --- a/compiler/rustc_codegen_gcc/tools/generate_intrinsics.py +++ b/compiler/rustc_codegen_gcc/tools/generate_intrinsics.py @@ -84,6 +84,10 @@ def update_intrinsics(llvm_path): # This speeds up the comparison, and makes our code considerably smaller. # Since all intrinsic names start with "llvm.", we skip that prefix. print("Updating content of `{}`...".format(output_file)) + indent4 = " " + indent8 = indent4 + indent4 + indent12 = indent8 + indent4 + indent16 = indent12 + indent4 with open(output_file, "w", encoding="utf8") as out: out.write("""// File generated by `rustc_codegen_gcc/tools/generate_intrinsics.py` // DO NOT EDIT IT! @@ -95,33 +99,35 @@ def update_intrinsics(llvm_path): if let ArchCheckResult::Ok(res) = old_arch_res { return res; } -match arch {""") + match arch { +""") for arch in archs: if len(intrinsics[arch]) == 0: continue attribute = "#[expect(non_snake_case)]" if arch[0].isupper() else "" - out.write("\"{}\" => {{ {} fn {}(name: &str,full_name:&str) -> &'static str {{ match name {{".format(arch, attribute, arch)) + out.write(f"""{indent4}"{arch}" => {{ +{indent8}{attribute} fn {arch}(name: &str,full_name:&str) -> &'static str {{ +{indent12}match name {{""") intrinsics[arch].sort(key=lambda x: (x[0], x[1])) - out.write(' // {}\n'.format(arch)) + out.write(f'{indent16}// {arch}\n') for entry in intrinsics[arch]: llvm_name = entry[0].removeprefix("llvm."); llvm_name = llvm_name.removeprefix(arch); llvm_name = llvm_name.removeprefix("."); if "_round_mask" in entry[1]: - out.write(' // [INVALID CONVERSION]: "{}" => "{}",\n'.format(llvm_name, entry[1])) + out.write(f'{indent16}// [INVALID CONVERSION]: "{llvm_name}" => "{entry[1]}",\n') else: - out.write(' "{}" => "{}",\n'.format(llvm_name, entry[1])) - out.write(' _ => unimplemented!("***** unsupported LLVM intrinsic {full_name}"),\n') - out.write("}} }} {}(name,full_name) }}\n,".format(arch)) - out.write(""" _ => { - match old_arch_res { - ArchCheckResult::UnknownIntrinsic => unimplemented!("***** unsupported LLVM intrinsic {full_name}"), - ArchCheckResult::UnknownArch => unimplemented!("***** unsupported LLVM architecture {arch}, intrinsic: {full_name}"), - ArchCheckResult::Ok(_) => unreachable!(), - } - }""") + out.write(f'{indent16}"{llvm_name}" => "{entry[1]}",\n') + out.write(f'{indent16}_ => unimplemented!("***** unsupported LLVM intrinsic {{full_name}}"),\n') + out.write(f"{indent16}}}\n{indent12}}}\n{indent8}{arch}(name,full_name)\n{indent8}}}\n,") + out.write(f"""{indent4}_ => {{ +{indent8}match old_arch_res {{ +{indent8}ArchCheckResult::UnknownIntrinsic => unimplemented!("***** unsupported LLVM intrinsic {{full_name}}"), +{indent8}ArchCheckResult::UnknownArch => unimplemented!("***** unsupported LLVM architecture {{arch}}, intrinsic: {{full_name}}"), +{indent8}ArchCheckResult::Ok(_) => unreachable!(), +{indent4}}} +}}""") out.write("}\n}") - subprocess.call(["rustfmt", output_file]) print("Done!") diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 0389aa56bafd6..3e24b62125fea 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -219,32 +219,31 @@ fn process_builtin_attrs( AttributeKind::RustcEiiForeignItem => { codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM; } - AttributeKind::EiiImpls(impls) => { - for i in impls { - let foreign_item = match i.resolution { - EiiImplResolution::Macro(def_id) => { - let Some(extern_item) = find_attr!(tcx, def_id, EiiDeclaration(target) => target.foreign_item - ) else { - tcx.dcx().span_delayed_bug( - i.span, - "resolved to something that's not an EII", - ); - continue; - }; - extern_item - } - EiiImplResolution::Known(def_id) => def_id, - EiiImplResolution::Error(_eg) => continue, - }; + AttributeKind::EiiImpl(i) => { + let foreign_item = match i.resolution { + EiiImplResolution::Macro(def_id) => { + let Some(extern_item) = find_attr!(tcx, def_id, EiiDeclaration(target) => target.foreign_item + ) else { + tcx.dcx().span_delayed_bug( + i.span, + "resolved to something that's not an EII", + ); + continue; + }; + extern_item + } + EiiImplResolution::Known(def_id) => def_id, + EiiImplResolution::Error(_eg) => continue, + }; - // this is to prevent a bug where a single crate defines both the default and explicit implementation - // for an EII. In that case, both of them may be part of the same final object file. I'm not 100% sure - // what happens, either rustc deduplicates the symbol or llvm, or it's random/order-dependent. - // However, the fact that the default one of has weak linkage isn't considered and you sometimes get that - // the default implementation is used while an explicit implementation is given. - if - // if this is a default impl - i.is_default + // this is to prevent a bug where a single crate defines both the default and explicit implementation + // for an EII. In that case, both of them may be part of the same final object file. I'm not 100% sure + // what happens, either rustc deduplicates the symbol or llvm, or it's random/order-dependent. + // However, the fact that the default one of has weak linkage isn't considered and you sometimes get that + // the default implementation is used while an explicit implementation is given. + if + // if this is a default impl + i.is_default // iterate over all implementations *in the current crate* // (this is ok since we generate codegen fn attrs in the local crate) // if any of them is *not default* then don't emit the alias. @@ -252,28 +251,27 @@ fn process_builtin_attrs( let (_, impls) = tcx.externally_implementable_items(LOCAL_CRATE).get(&foreign_item).unwrap_or_else(|| bug!("EII impl should have an entry")); impls.iter().any(|(_, imp)| !imp.is_default) } - { - continue; - } + { + continue; + } - codegen_fn_attrs.foreign_item_symbol_aliases.push(( - foreign_item, - if i.is_default { Linkage::WeakAny } else { Linkage::External }, - Visibility::Default, - )); - codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM; - - // If the declaration is `#[track_caller]`, derive it onto the implementation - // too. The shim that forwards to this impl (see `add_function_aliases`) takes - // its ABI from the impl's `fn_abi`, so every impl must agree on whether the - // caller-location argument is present, otherwise it would be silently dropped. - if tcx - .codegen_fn_attrs(foreign_item) - .flags - .contains(CodegenFnAttrFlags::TRACK_CALLER) - { - codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER; - } + codegen_fn_attrs.foreign_item_symbol_aliases.push(( + foreign_item, + if i.is_default { Linkage::WeakAny } else { Linkage::External }, + Visibility::Default, + )); + codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM; + + // If the declaration is `#[track_caller]`, derive it onto the implementation + // too. The shim that forwards to this impl (see `add_function_aliases`) takes + // its ABI from the impl's `fn_abi`, so every impl must agree on whether the + // caller-location argument is present, otherwise it would be silently dropped. + if tcx + .codegen_fn_attrs(foreign_item) + .flags + .contains(CodegenFnAttrFlags::TRACK_CALLER) + { + codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER; } } AttributeKind::ThreadLocal => { diff --git a/compiler/rustc_expand/src/build.rs b/compiler/rustc_expand/src/build.rs index b87dfd0198efc..4a8541ed4c6b7 100644 --- a/compiler/rustc_expand/src/build.rs +++ b/compiler/rustc_expand/src/build.rs @@ -707,7 +707,7 @@ impl<'a> ExtCtxt<'a> { mutability, expr: Some(expr), define_opaque: None, - eii_impls: Default::default(), + eii_impl: None, } .into(), ), diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 187dcea4f91a5..045233c0c4d21 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -804,7 +804,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { None, ) } - // When a function has EII implementations attached (via `eii_impls`), + // When a function has EII implementations attached (via `eii_impl`), // use fake tokens so the pretty-printer re-emits the EII attribute // (e.g. `#[hello]`) in the token stream. Without this, the EII // attribute is lost during the token roundtrip performed by @@ -812,7 +812,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { // breaking the EII link on the resulting re-parsed item. Annotatable::Item(item_inner) if matches!(&item_inner.kind, - ItemKind::Fn(f) if !f.eii_impls.is_empty()) => + ItemKind::Fn(f) if f.eii_impl.is_some()) => { rustc_parse::fake_token_stream_for_item( &self.cx.sess.psess, diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 165f06d2fde8b..78a15eeb923a5 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -1076,7 +1076,7 @@ pub enum AttributeKind { EiiDeclaration(EiiDecl), /// Implementation detail of `#[eii]` - EiiImpls(ThinVec), + EiiImpl(Box), /// Represents [`#[export_name]`](https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute). ExportName { diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index dded70ccd08ef..a5a1fc2482b4e 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -40,7 +40,7 @@ impl AttributeKind { Doc(_) => Yes, DocComment { .. } => Yes, EiiDeclaration(_) => Yes, - EiiImpls(..) => No, + EiiImpl(..) => No, ExportName { .. } => Yes, ExportStable => No, Feature(..) => No, diff --git a/compiler/rustc_hir_analysis/src/check/compare_eii.rs b/compiler/rustc_hir_analysis/src/check/compare_eii.rs index 57824a91a680f..d9fc3bbcf08c2 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_eii.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_eii.rs @@ -301,8 +301,7 @@ fn check_no_generics<'tcx>( // since in that case it looks like a duplicate error: the declaration of the EII already can't contain generics. // So, we check here if at least one of the eii impls has ImplResolution::Macro, which indicates it's // not generated as part of the declaration. - && find_attr!(tcx, external_impl, EiiImpls(impls) if impls.iter().any(|i| matches!(i.resolution, EiiImplResolution::Macro(_))) - ) + && find_attr!(tcx, external_impl, EiiImpl(i) if matches!(i.resolution, EiiImplResolution::Macro(_))) { tcx.dcx().emit_err(EiiWithGenerics { span: tcx.def_span(external_impl), diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 35628e54769b4..caf64fd6894f7 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -1153,9 +1153,7 @@ fn check_item_fn( fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) { // does the function have an EiiImpl attribute? that contains the defid of a *macro* // that was used to mark the implementation. This is a two step process. - for EiiImpl { resolution, span, .. } in - find_attr!(tcx, def_id, EiiImpls(impls) => impls).into_flat_iter() - { + if let Some(EiiImpl { resolution, span, .. }) = find_attr!(tcx, def_id, EiiImpl(i) => &**i) { let (foreign_item, name) = match resolution { EiiImplResolution::Macro(def_id) => { // we expect this macro to have the `EiiMacroFor` attribute, that points to a function @@ -1166,11 +1164,11 @@ fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) { (foreign_item, tcx.item_name(*def_id)) } else { tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII"); - continue; + return; } } EiiImplResolution::Known(def_id) => (*def_id, tcx.item_name(*def_id)), - EiiImplResolution::Error(_eg) => continue, + EiiImplResolution::Error(_eg) => return, }; let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span); @@ -1180,9 +1178,7 @@ fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) { fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) { // does the function have an EiiImpl attribute? that contains the defid of a *macro* // that was used to mark the implementation. This is a two step process. - for EiiImpl { resolution, span, .. } in - find_attr!(tcx, def_id, EiiImpls(impls) => impls).into_flat_iter() - { + if let Some(EiiImpl { resolution, span, .. }) = find_attr!(tcx, def_id, EiiImpl(i) => &**i) { let (foreign_item, name) = match resolution { EiiImplResolution::Macro(def_id) => { // we expect this macro to have the `EiiMacroFor` attribute, that points to a function @@ -1193,11 +1189,11 @@ fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) (foreign_item, tcx.item_name(*def_id)) } else { tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII"); - continue; + return; } } EiiImplResolution::Known(def_id) => (*def_id, tcx.item_name(*def_id)), - EiiImplResolution::Error(_eg) => continue, + EiiImplResolution::Error(_eg) => return, }; let _ = compare_eii_statics(tcx, def_id, ty, foreign_item, name, *span); diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index a986ae3964e26..dcc5579e14339 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -140,7 +140,8 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { // // This has some implications for how we get the clauses available to the anon const // see `explicit_clauses_of` for more information on this - let generics = tcx.generics_of(parent_did); + let parent_def_id = tcx.local_parent(param_id); + let generics = tcx.generics_of(parent_def_id); let param_def_idx = generics.param_def_id_to_index[¶m_id.to_def_id()]; // In the above example this would be .params[..N#0] let own_params = generics.params_to(param_def_idx as usize, tcx).to_owned(); diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index 1473b0d108fb3..ebbf63b947a93 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -60,7 +60,6 @@ This API is completely unstable and subject to change. #![feature(gen_blocks)] #![feature(iter_intersperse)] #![feature(never_type)] -#![feature(option_into_flat_iter)] #![feature(slice_partition_dedup)] #![feature(try_blocks)] #![feature(unwrap_infallible)] diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index eab4e1990455c..51b7d1b0c3e49 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -2526,23 +2526,21 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { if applicable_close_candidates.is_empty() { Ok(None) } else { - let best_name = { - let names = applicable_close_candidates - .iter() - .map(|cand| cand.name()) - .collect::>(); - find_best_match_for_name_with_substrings( - &names, - self.method_name.unwrap().name, - None, - ) - } - .or_else(|| { - applicable_close_candidates - .iter() - .find(|cand| self.matches_by_doc_alias(cand.def_id)) - .map(|cand| cand.name()) - }); + let best_name = applicable_close_candidates + .iter() + .find(|cand| self.matches_by_doc_alias(cand.def_id)) + .map(|cand| cand.name()) + .or_else(|| { + let names = applicable_close_candidates + .iter() + .map(|cand| cand.name()) + .collect::>(); + find_best_match_for_name_with_substrings( + &names, + self.method_name.unwrap().name, + None, + ) + }); Ok(best_name.and_then(|best_name| { applicable_close_candidates .into_iter() diff --git a/compiler/rustc_incremental/src/persist/clean.rs b/compiler/rustc_incremental/src/persist/clean.rs index d3a04ab5946b7..a311832e62d96 100644 --- a/compiler/rustc_incremental/src/persist/clean.rs +++ b/compiler/rustc_incremental/src/persist/clean.rs @@ -27,7 +27,7 @@ use rustc_hir::{ Attribute, ImplItemKind, ItemKind as HirItem, Node as HirNode, TraitItemKind, find_attr, intravisit, }; -use rustc_middle::dep_graph::{DepNode, dep_kind_from_label, label_strs}; +use rustc_middle::dep_graph::{DepKind, DepNode, dep_kind_from_label}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; use rustc_span::{Span, Symbol}; @@ -38,81 +38,78 @@ use crate::diagnostics; // Base and Extra labels to build up the labels /// For typedef, constants, and statics -const BASE_CONST: &[&str] = &[label_strs::type_of]; +const BASE_CONST: &[DepKind] = &[DepKind::type_of]; /// DepNodes for functions + methods -const BASE_FN: &[&str] = &[ +const BASE_FN: &[DepKind] = &[ // Callers will depend on the signature of these items, so we better test - label_strs::fn_sig, - label_strs::generics_of, - label_strs::clauses_of, - label_strs::type_of, + DepKind::fn_sig, + DepKind::generics_of, + DepKind::clauses_of, + DepKind::type_of, // And a big part of compilation (that we eventually want to cache) is type inference // information: - label_strs::typeck_root, + DepKind::typeck_root, ]; /// DepNodes for Hir, which is pretty much everything -const BASE_HIR: &[&str] = &[ +const BASE_HIR: &[DepKind] = &[ // hir_owner should be computed for all nodes - label_strs::hir_owner, + DepKind::hir_owner, ]; /// `impl` implementation of struct/trait -const BASE_IMPL: &[&str] = - &[label_strs::associated_item_def_ids, label_strs::generics_of, label_strs::impl_trait_header]; +const BASE_IMPL: &[DepKind] = + &[DepKind::associated_item_def_ids, DepKind::generics_of, DepKind::impl_trait_header]; /// DepNodes for exported mir bodies, which is relevant in "executable" /// code, i.e., functions+methods -const BASE_MIR: &[&str] = &[label_strs::optimized_mir, label_strs::promoted_mir]; +const BASE_MIR: &[DepKind] = &[DepKind::optimized_mir, DepKind::promoted_mir]; /// Struct, Enum and Union DepNodes /// /// Note that changing the type of a field does not change the type of the struct or enum, but /// adding/removing fields or changing a fields name or visibility does. -const BASE_STRUCT: &[&str] = - &[label_strs::generics_of, label_strs::clauses_of, label_strs::type_of]; +const BASE_STRUCT: &[DepKind] = &[DepKind::generics_of, DepKind::clauses_of, DepKind::type_of]; /// Trait definition `DepNode`s. /// Extra `DepNode`s for functions and methods. -const EXTRA_ASSOCIATED: &[&str] = &[label_strs::associated_item]; +const EXTRA_ASSOCIATED: &[DepKind] = &[DepKind::associated_item]; -const EXTRA_TRAIT: &[&str] = &[]; +const EXTRA_TRAIT: &[DepKind] = &[]; // Fully Built Labels -const LABELS_CONST: &[&[&str]] = &[BASE_HIR, BASE_CONST]; +const LABELS_CONST: &[&[DepKind]] = &[BASE_HIR, BASE_CONST]; /// Constant/Typedef in an impl -const LABELS_CONST_IN_IMPL: &[&[&str]] = &[BASE_HIR, BASE_CONST, EXTRA_ASSOCIATED]; +const LABELS_CONST_IN_IMPL: &[&[DepKind]] = &[BASE_HIR, BASE_CONST, EXTRA_ASSOCIATED]; /// Trait-Const/Typedef DepNodes -const LABELS_CONST_IN_TRAIT: &[&[&str]] = &[BASE_HIR, BASE_CONST, EXTRA_ASSOCIATED, EXTRA_TRAIT]; +const LABELS_CONST_IN_TRAIT: &[&[DepKind]] = &[BASE_HIR, BASE_CONST, EXTRA_ASSOCIATED, EXTRA_TRAIT]; /// Function `DepNode`s. -const LABELS_FN: &[&[&str]] = &[BASE_HIR, BASE_MIR, BASE_FN]; +const LABELS_FN: &[&[DepKind]] = &[BASE_HIR, BASE_MIR, BASE_FN]; /// Method `DepNode`s. -const LABELS_FN_IN_IMPL: &[&[&str]] = &[BASE_HIR, BASE_MIR, BASE_FN, EXTRA_ASSOCIATED]; +const LABELS_FN_IN_IMPL: &[&[DepKind]] = &[BASE_HIR, BASE_MIR, BASE_FN, EXTRA_ASSOCIATED]; /// Trait method `DepNode`s. -const LABELS_FN_IN_TRAIT: &[&[&str]] = +const LABELS_FN_IN_TRAIT: &[&[DepKind]] = &[BASE_HIR, BASE_MIR, BASE_FN, EXTRA_ASSOCIATED, EXTRA_TRAIT]; /// For generic cases like inline-assembly, modules, etc. -const LABELS_HIR_ONLY: &[&[&str]] = &[BASE_HIR]; +const LABELS_HIR_ONLY: &[&[DepKind]] = &[BASE_HIR]; /// Impl `DepNode`s. -const LABELS_TRAIT: &[&[&str]] = &[ - BASE_HIR, - &[label_strs::associated_item_def_ids, label_strs::clauses_of, label_strs::generics_of], -]; +const LABELS_TRAIT: &[&[DepKind]] = + &[BASE_HIR, &[DepKind::associated_item_def_ids, DepKind::clauses_of, DepKind::generics_of]]; /// Impl `DepNode`s. -const LABELS_IMPL: &[&[&str]] = &[BASE_HIR, BASE_IMPL]; +const LABELS_IMPL: &[&[DepKind]] = &[BASE_HIR, BASE_IMPL]; /// Abstract data type (struct, enum, union) `DepNode`s. -const LABELS_ADT: &[&[&str]] = &[BASE_HIR, BASE_STRUCT]; +const LABELS_ADT: &[&[DepKind]] = &[BASE_HIR, BASE_STRUCT]; // FIXME: Struct/Enum/Unions Fields (there is currently no way to attach these) // @@ -289,7 +286,7 @@ impl<'tcx> CleanVisitor<'tcx> { .emit_fatal(diagnostics::UndefinedCleanDirty { span, kind: format!("{node:?}") }), }; let labels = - Labels::from_iter(labels.iter().flat_map(|s| s.iter().map(|l| (*l).to_string()))); + Labels::from_iter(labels.iter().flat_map(|s| s.iter().map(|l| format!("{l:?}")))); (name, labels) } diff --git a/compiler/rustc_interface/src/interface.rs b/compiler/rustc_interface/src/interface.rs index 2ad6fb6450a16..18f869d24cbfb 100644 --- a/compiler/rustc_interface/src/interface.rs +++ b/compiler/rustc_interface/src/interface.rs @@ -15,7 +15,7 @@ use rustc_parse::lexer::StripTokens; use rustc_parse::new_parser_from_source_str; use rustc_parse::parser::Recovery; use rustc_query_impl::print_query_stack; -use rustc_session::config::{self, BackendJobs, Cfg, CheckCfg, ExpectedValues, Input, OutFileName}; +use rustc_session::config::{self, Cfg, CheckCfg, ExpectedValues, Input, OutFileName}; use rustc_session::parse::ParseSess; use rustc_session::{CompilerIO, EarlyDiagCtxt, Session, lint}; use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMapInputs}; @@ -375,9 +375,7 @@ pub fn run_compiler(config: Config, f: impl FnOnce(&Compiler) -> R + Se // Initialize jobserver as early as possible. let early_dcx = EarlyDiagCtxt::new(config.opts.error_format); - if let Some(limit) = - config.opts.jobs.frontend.max(config.opts.jobs.backend.map(BackendJobs::value)) - { + if let Some(limit) = config.opts.jobs.frontend.max(config.opts.jobs.backend) { jobserver::initialize(limit.get(), |err| { let note = "the build environment is likely misconfigured"; early_dcx.early_struct_warn(err).with_note(note).emit() diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index bb91d855feaeb..28879fc78c2ae 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -57,7 +57,6 @@ pub struct CStore { metadata_loader: Box, metas: IndexVec>>, - injected_panic_runtime: Option, /// This crate needs an allocator and either provides it itself, or finds it in a dependency. /// If the above is true, then this field denotes the kind of the found allocator. allocator_kind: Option, @@ -291,10 +290,6 @@ impl CStore { deps } - pub(crate) fn injected_panic_runtime(&self) -> Option { - self.injected_panic_runtime - } - pub(crate) fn allocator_kind(&self) -> Option { self.allocator_kind } @@ -541,7 +536,6 @@ impl CStore { // corresponding `CrateNum`. This first entry will always remain // `None`. metas: IndexVec::from_iter(iter::once(None)), - injected_panic_runtime: None, allocator_kind: None, alloc_error_handler_kind: None, has_global_allocator: false, @@ -954,74 +948,69 @@ impl CStore { } fn inject_panic_runtime(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) { - // If we're only compiling an rlib, then there's no need to select a - // panic runtime, so we just skip this section entirely. - let only_rlib = tcx.crate_types().iter().all(|ct| *ct == CrateType::Rlib); - if only_rlib { - info!("panic runtime injection skipped, only generating rlib"); - return; - } - - // If we need a panic runtime, we try to find an existing one here. At - // the same time we perform some general validation of the DAG we've got - // going such as ensuring everything has a compatible panic strategy. - let mut needs_panic_runtime = attr::contains_name(&krate.attrs, sym::needs_panic_runtime); - for (_cnum, data) in self.iter_crate_data() { - needs_panic_runtime |= data.needs_panic_runtime(); - } - - // If we just don't need a panic runtime at all, then we're done here - // and there's nothing else to do. - if !needs_panic_runtime { + // Panic runtimes are only injected when building std. We don't want to + // inject them as direct dependencies, because Cargo relies on loading + // panic runtimes via `-Ldependency` search paths, as per RFC 3874 + // (build-std=always). + if !attr::contains_name(&krate.attrs, sym::needs_panic_runtime) { return; } - // By this point we know that we need a panic runtime. Here we just load - // an appropriate default runtime for our panic strategy. + // Here we just load `panic_unwind` and `panic_abort`. // // We may resolve to an already loaded crate (as the crate may not have // been explicitly linked prior to this), but this is fine. // // Also note that we have yet to perform validation of the crate graph // in terms of everyone has a compatible panic runtime format, that's - // performed later as part of the `dependency_format` module. - let desired_strategy = tcx.sess.panic_strategy(); - let name = match desired_strategy { - PanicStrategy::Unwind => sym::panic_unwind, - PanicStrategy::Abort => sym::panic_abort, - PanicStrategy::ImmediateAbort => { - // Immediate-aborting panics don't use a runtime. + // performed later as part of the `dependency_format` module along with + // the activation of only one runtime for the desired strategy. + let mut resolve_panic_runtime = |desired_strategy: PanicStrategy| { + let name = match desired_strategy { + PanicStrategy::Unwind => sym::panic_unwind, + PanicStrategy::Abort => sym::panic_abort, + PanicStrategy::ImmediateAbort => unreachable!(), + }; + + info!("loading panic runtime, name = `{}`", name); + + // This has to be conditional as both `panic_unwind` and `panic_abort` may be present in the + // crate graph at the same time. One of them will later be activated in dependency_formats. + let Some(cnum) = self.resolve_crate( + tcx, + name, + DUMMY_SP, + CrateDepKind::Conditional, + CrateOrigin::Injected, + ) else { return; + }; + let cdata = self.get_crate_data(cnum); + + // Sanity check the loaded crate to ensure it is indeed a panic runtime. + if !cdata.is_panic_runtime() { + tcx.dcx().emit_err(diagnostics::CrateNotPanicRuntime { crate_name: name }); } - }; - info!("panic runtime not found -- loading {}", name); - // This has to be conditional as both panic_unwind and panic_abort may be present in the - // crate graph at the same time. One of them will later be activated in dependency_formats. - let Some(cnum) = self.resolve_crate( - tcx, - name, - DUMMY_SP, - CrateDepKind::Conditional, - CrateOrigin::Injected, - ) else { - return; + // Sanity check the panic strategy is indeed what we thought it was. + // Note: Both `panic_unwind` and `panic_abort` might be compiled with + // `ImmediateAbort` strategy. + if cdata.required_panic_strategy() != Some(PanicStrategy::ImmediateAbort) + && cdata.required_panic_strategy() != Some(desired_strategy) + { + tcx.dcx().emit_err(diagnostics::NoPanicStrategy { + crate_name: name, + strategy: desired_strategy, + }); + } }; - let cdata = self.get_crate_data(cnum); - // Sanity check the loaded crate to ensure it is indeed a panic runtime - // and the panic strategy is indeed what we thought it was. - if !cdata.is_panic_runtime() { - tcx.dcx().emit_err(diagnostics::CrateNotPanicRuntime { crate_name: name }); - } - if cdata.required_panic_strategy() != Some(desired_strategy) { - tcx.dcx().emit_err(diagnostics::NoPanicStrategy { - crate_name: name, - strategy: desired_strategy, - }); + // Always resolve `panic_abort` as it is a non-optional dependency of `std`. + resolve_panic_runtime(PanicStrategy::Abort); + // Conditionally resolve `panic_unwind` as it is an optional dependency of `std`. + if tcx.sess.panic_strategy() == PanicStrategy::Unwind { + resolve_panic_runtime(PanicStrategy::Unwind); } - - self.injected_panic_runtime = Some(cnum); } fn inject_profiler_runtime(&mut self, tcx: TyCtxt<'_>) { diff --git a/compiler/rustc_metadata/src/dependency_format.rs b/compiler/rustc_metadata/src/dependency_format.rs index 257b2a9b03884..d42c190660289 100644 --- a/compiler/rustc_metadata/src/dependency_format.rs +++ b/compiler/rustc_metadata/src/dependency_format.rs @@ -64,7 +64,6 @@ use rustc_span::sym; use rustc_target::spec::PanicStrategy; use tracing::info; -use crate::creader::CStore; use crate::diagnostics::{ BadPanicStrategy, CrateDepMultiple, IncompatiblePanicInDropStrategy, IncompatibleWithImmediateAbort, IncompatibleWithImmediateAbortCore, LibRequired, @@ -250,14 +249,8 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList { } } - // We've gotten this far because we're emitting some form of a final - // artifact which means that we may need to inject dependencies of some - // form. - // - // Things like panic runtimes may not have been activated quite yet, so do so here. - activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| { - tcx.is_panic_runtime(cnum) - }); + // Panic runtimes may not have been activated quite yet, so do so here. + activate_panic_runtime(tcx, &mut ret); // When dylib B links to dylib A, then when using B we must also link to A. // It could be the case, however, that the rlib for A is present (hence we @@ -364,39 +357,44 @@ fn attempt_static(tcx: TyCtxt<'_>, unavailable: &mut Vec) -> Option, - list: &mut DependencyList, - replaces_injected: &dyn Fn(CrateNum) -> bool, -) { +/// Both `panic_unwind` and `panic_abort` were injected during the `std` build. +/// Here we need to activate only one, based on the desired strategy. +fn activate_panic_runtime(tcx: TyCtxt<'_>, list: &mut DependencyList) { + let desired_strategy = tcx.sess.panic_strategy(); + let desired_name = match desired_strategy { + PanicStrategy::Unwind => sym::panic_unwind, + PanicStrategy::Abort => sym::panic_abort, + PanicStrategy::ImmediateAbort => { + // Immediate-aborting panics don't use a runtime. + return; + } + }; + let mut activated = None; for (cnum, slot) in list.iter_enumerated() { - if !replaces_injected(cnum) { + if !tcx.is_panic_runtime(cnum) { continue; } if *slot != Linkage::NotLinked { return; } + if tcx.crate_name(cnum) == desired_name { + activated = Some(cnum); + } } - if let Some(injected) = injected { - assert_eq!(list[injected], Linkage::NotLinked); - list[injected] = Linkage::Static; - } + if let Some(activated) = activated { + assert_eq!(list[activated], Linkage::NotLinked); + info!("panic runtime activated (cnum = {:?}) (name = {})", activated, desired_name); + list[activated] = Linkage::Static; + }; } /// After the linkage for a crate has been determined we need to verify that diff --git a/compiler/rustc_metadata/src/eii.rs b/compiler/rustc_metadata/src/eii.rs index 4328e8de901d8..da6d9e85bc4fa 100644 --- a/compiler/rustc_metadata/src/eii.rs +++ b/compiler/rustc_metadata/src/eii.rs @@ -35,7 +35,12 @@ pub(crate) fn collect<'tcx>(tcx: TyCtxt<'tcx>, LocalCrate: LocalCrate) -> EiiMap // iterate over all items in the current crate for id in tcx.hir_crate_items(()).eiis() { - for i in find_attr!(tcx, id, EiiImpls(e) => e).into_flat_iter() { + // if we find a new declaration, add it to the list without a known implementation + if let Some(decl) = find_attr!(tcx, id, EiiDeclaration(d) => *d) { + eiis.entry(decl.foreign_item).or_insert((decl, Default::default())); + } + + if let Some(i) = find_attr!(tcx, id, EiiImpl(i) => i) { let (foreign_item, decl) = match i.resolution { EiiImplResolution::Macro(macro_defid) => { // find the decl for this one if it wasn't in yet (maybe it's from the local crate? not very useful but not illegal) @@ -63,12 +68,7 @@ pub(crate) fn collect<'tcx>(tcx: TyCtxt<'tcx>, LocalCrate: LocalCrate) -> EiiMap eiis.entry(foreign_item) .or_insert_with(|| (decl, Default::default())) .1 - .insert(id.into(), *i); - } - - // if we find a new declaration, add it to the list without a known implementation - if let Some(decl) = find_attr!(tcx, id, EiiDeclaration(d) => *d) { - eiis.entry(decl.foreign_item).or_insert((decl, Default::default())); + .insert(id.into(), **i); } } diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index 09d6290fcd2fc..0d5c4314973f2 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -789,10 +789,9 @@ impl MetadataBlob { )?; writeln!( out, - "compiler_builtins {} needs_allocator {} needs_panic_runtime {} no_builtins {} panic_runtime {} profiler_runtime {}", + "compiler_builtins {} needs_allocator {} no_builtins {} panic_runtime {} profiler_runtime {}", root.compiler_builtins, root.needs_allocator, - root.needs_panic_runtime, root.no_builtins, root.panic_runtime, root.profiler_runtime @@ -2047,10 +2046,6 @@ impl CrateMetadata { self.root.required_panic_strategy } - pub(crate) fn needs_panic_runtime(&self) -> bool { - self.root.needs_panic_runtime - } - pub(crate) fn is_private_dep(&self) -> bool { self.private_dep } diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 2c59b10fd8be6..9f08f59fb23b5 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -747,7 +747,6 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { debugger_visualizers, compiler_builtins: find_attr!(attrs, CompilerBuiltins), needs_allocator: find_attr!(attrs, NeedsAllocator), - needs_panic_runtime: find_attr!(attrs, NeedsPanicRuntime), no_builtins: find_attr!(attrs, NoBuiltins), panic_runtime: find_attr!(attrs, PanicRuntime), profiler_runtime: find_attr!(attrs, ProfilerRuntime), diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index f4180af492345..9bdf0989b3fa5 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -298,7 +298,6 @@ pub(crate) struct CrateRoot { compiler_builtins: bool, needs_allocator: bool, - needs_panic_runtime: bool, no_builtins: bool, panic_runtime: bool, profiler_runtime: bool, diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index b6fda22775c2a..6abec9a4ff465 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -69,7 +69,8 @@ impl DepKind { if u > Self::MAX { panic!("Invalid DepKind {u}"); } - // SAFETY: See comment on DEP_KIND_NUM_VARIANTS + // SAFETY: `DepKind` is `repr(u16)`, its variants are `0..=MAX`, and `u` was checked + // against `MAX` above. unsafe { std::mem::transmute(u) } } @@ -83,9 +84,16 @@ impl DepKind { *self as usize } + /// The number of dep kind variants. + pub(crate) const NUM_VARIANTS: usize = std::mem::variant_count::(); + /// This is the highest value a `DepKind` can have. It's used during encoding to - /// pack information into the unused bits. - pub(crate) const MAX: u16 = DEP_KIND_NUM_VARIANTS - 1; + /// pack information into the unused bits. u16 matches the `repr(u16)` on `DepKind`. + pub(crate) const MAX: u16 = { + let max = Self::NUM_VARIANTS - 1; + assert!(max < u16::MAX as usize); + max as u16 + }; } /// Combination of a [`DepKind`] and a key fingerprint that uniquely identifies @@ -279,40 +287,15 @@ macro_rules! define_dep_nodes { $( $(#[$q_attr])* $q_name, )* } - // This computes the number of dep kind variants. Along the way, it sanity-checks that the - // discriminants of the variants have been assigned consecutively from 0 so that they can - // be used as a dense index, and that all discriminants fit in a `u16`. - pub(crate) const DEP_KIND_NUM_VARIANTS: u16 = { - let deps = &[ - $(DepKind::$nq_name,)* - $(DepKind::$q_name,)* - ]; - let mut i = 0; - while i < deps.len() { - if i != deps[i].as_usize() { - panic!(); - } - i += 1; - } - assert!(deps.len() <= u16::MAX as usize); - deps.len() as u16 - }; - - pub(super) fn dep_kind_from_label_string(label: &str) -> Result { + /// Converts a string to a `DepKind`. Used for handling attributes like `rustc_clean` that + /// name dep kinds. + fn dep_kind_from_label_string(label: &str) -> Result { match label { $( stringify!($nq_name) => Ok(self::DepKind::$nq_name), )* $( stringify!($q_name) => Ok(self::DepKind::$q_name), )* _ => Err(()), } } - - /// Contains variant => str representations for constructing - /// DepNode groups for tests. - #[expect(non_upper_case_globals)] - pub mod label_strs { - $( pub const $nq_name: &str = stringify!($nq_name); )* - $( pub const $q_name: &str = stringify!($q_name); )* - } }; } diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index 4f9cb03ff663e..3389c3ec91a5a 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -2,9 +2,7 @@ use std::panic; use tracing::instrument; -pub use self::dep_node::{ - DepKind, DepKindVTable, DepNode, WorkProductId, dep_kind_from_label, label_strs, -}; +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, diff --git a/compiler/rustc_middle/src/dep_graph/serialized.rs b/compiler/rustc_middle/src/dep_graph/serialized.rs index daebc887055ac..1c476fc91697e 100644 --- a/compiler/rustc_middle/src/dep_graph/serialized.rs +++ b/compiler/rustc_middle/src/dep_graph/serialized.rs @@ -387,9 +387,9 @@ impl SerializedDepGraph { // Read the number of nodes of each dep kind, and perform // counting sort for `LazyNodeIndex`. - let mut kinds = Vec::with_capacity(DepKind::MAX as usize + 1); + let mut kinds = Vec::with_capacity(DepKind::NUM_VARIANTS); let mut offset = 0u32; - for _ in 0..(DepKind::MAX + 1) { + for _ in 0..(DepKind::NUM_VARIANTS) { let len = d.read_u32(); kinds.push(LazyKindIndex { start: offset, len, map: OnceLock::new() }); offset += len; @@ -654,7 +654,7 @@ impl EncoderState { edge_count: 0, node_count: 0, encoder: MemEncoder::new(), - kind_stats: iter::repeat_n(0, DepKind::MAX as usize + 1).collect(), + kind_stats: iter::repeat_n(0, DepKind::NUM_VARIANTS).collect(), }) }), } @@ -792,7 +792,7 @@ impl EncoderState { let mut encoder = self.file.lock().take().unwrap(); - let mut kind_stats: Vec = iter::repeat_n(0, DepKind::MAX as usize + 1).collect(); + let mut kind_stats: Vec = iter::repeat_n(0, DepKind::NUM_VARIANTS).collect(); let mut node_max = 0; let mut node_count = 0; diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index 69c2e099080c9..ed1a2f7a831b1 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -56,6 +56,7 @@ #![feature(try_trait_v2_residual)] #![feature(try_trait_v2_yeet)] #![feature(type_alias_impl_trait)] +#![feature(variant_count)] #![feature(yeet_expr)] #![recursion_limit = "256"] // tidy-alphabetical-end diff --git a/compiler/rustc_middle/src/mir/statement.rs b/compiler/rustc_middle/src/mir/statement.rs index 17eeb7c3c12aa..e0c8789a8d8b3 100644 --- a/compiler/rustc_middle/src/mir/statement.rs +++ b/compiler/rustc_middle/src/mir/statement.rs @@ -442,7 +442,7 @@ impl<'tcx> Place<'tcx> { pub fn project_to_field( self, idx: FieldIdx, - local_decls: &impl HasLocalDecls<'tcx>, + local_decls: &(impl HasLocalDecls<'tcx> + ?Sized), tcx: TyCtxt<'tcx>, ) -> Self { let ty = self.ty(local_decls, tcx).ty; diff --git a/compiler/rustc_mir_transform/src/elaborate_box_derefs.rs b/compiler/rustc_mir_transform/src/elaborate_box_derefs.rs index 5c925b9ecaa42..6ce39aac6a0db 100644 --- a/compiler/rustc_mir_transform/src/elaborate_box_derefs.rs +++ b/compiler/rustc_mir_transform/src/elaborate_box_derefs.rs @@ -26,18 +26,8 @@ fn build_ptr_tys<'tcx>( (unique_ty, nonnull_ty, ptr_ty) } -/// Constructs the projection needed to access a Box's pointer -pub(super) fn build_projection<'tcx>( - unique_ty: Ty<'tcx>, - nonnull_ty: Ty<'tcx>, -) -> [PlaceElem<'tcx>; 2] { - [PlaceElem::Field(FieldIdx::ZERO, unique_ty), PlaceElem::Field(FieldIdx::ZERO, nonnull_ty)] -} - struct ElaborateBoxDerefVisitor<'a, 'tcx> { tcx: TyCtxt<'tcx>, - unique_def: ty::AdtDef<'tcx>, - nonnull_def: ty::AdtDef<'tcx>, local_decls: &'a mut LocalDecls<'tcx>, patch: MirPatch<'tcx>, } @@ -63,22 +53,18 @@ impl<'a, 'tcx> MutVisitor<'tcx> for ElaborateBoxDerefVisitor<'a, 'tcx> { { let source_info = self.local_decls[place.local].source_info; - let (unique_ty, nonnull_ty, ptr_ty) = - build_ptr_tys(tcx, boxed_ty, self.unique_def, self.nonnull_def); + let ptr_ty = Ty::new_imm_ptr(tcx, boxed_ty); let ptr_local = self.patch.new_temp(ptr_ty, source_info.span); + // Project to the first field (a `Unique`), then transmute that. We could project one + // further but in the end we'd hit a pattern type so we'd always have to transmute. + let field_place = + Place::from(place.local).project_to_field(FieldIdx::ZERO, &*self.local_decls, tcx); self.patch.add_assign( location, Place::from(ptr_local), - Rvalue::Cast( - CastKind::BoxDerefTransmute, - Operand::Copy( - Place::from(place.local) - .project_deeper(&build_projection(unique_ty, nonnull_ty), tcx), - ), - ptr_ty, - ), + Rvalue::Cast(CastKind::BoxDerefTransmute, Operand::Copy(field_place), ptr_ty), ); place.local = ptr_local; @@ -115,8 +101,7 @@ impl<'tcx> crate::MirPass<'tcx> for ElaborateBoxDerefs { let local_decls = &mut body.local_decls; - let mut visitor = - ElaborateBoxDerefVisitor { tcx, unique_def, nonnull_def, local_decls, patch }; + let mut visitor = ElaborateBoxDerefVisitor { tcx, local_decls, patch }; for (block, data) in body.basic_blocks.as_mut_preserves_cfg().iter_enumerated_mut() { visitor.visit_basic_block_data(block, data); @@ -141,7 +126,10 @@ impl<'tcx> crate::MirPass<'tcx> for ElaborateBoxDerefs { let (unique_ty, nonnull_ty, ptr_ty) = build_ptr_tys(tcx, boxed_ty, unique_def, nonnull_def); - new_projections.extend_from_slice(&build_projection(unique_ty, nonnull_ty)); + new_projections.extend_from_slice(&[ + PlaceElem::Field(FieldIdx::ZERO, unique_ty), + PlaceElem::Field(FieldIdx::ZERO, nonnull_ty), + ]); // While we can't project into a pattern type in a basic block, // this is debug info where it's fine. let pat_ty = Ty::new_pat(tcx, ptr_ty, tcx.mk_pat(PatternKind::NotNull)); diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 0fa592459167a..1306f1fcfb1ce 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -283,7 +283,7 @@ impl<'a> Parser<'a> { contract, body, define_opaque: None, - eii_impls: ThinVec::new(), + eii_impl: None, })) } else if self.eat_keyword_case(exp!(Extern), case) { if self.eat_keyword_case(exp!(Crate), case) { @@ -1257,7 +1257,7 @@ impl<'a> Parser<'a> { mutability: _, expr, define_opaque, - eii_impls: _, + eii_impl: _, }) => { self.dcx() .emit_err(diagnostics::AssociatedStaticItemNotAllowed { span }); @@ -1523,7 +1523,7 @@ impl<'a> Parser<'a> { expr: body, safety: Safety::Default, define_opaque: None, - eii_impls: ThinVec::default(), + eii_impl: None, })) } _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"), @@ -1661,15 +1661,8 @@ impl<'a> Parser<'a> { self.expect_semi()?; - let item = StaticItem { - ident, - ty, - safety, - mutability, - expr, - define_opaque: None, - eii_impls: ThinVec::default(), - }; + let item = + StaticItem { ident, ty, safety, mutability, expr, define_opaque: None, eii_impl: None }; Ok(ItemKind::Static(Box::new(item))) } diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 6489167afcdac..d1d82b2ed43e0 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -211,7 +211,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { self.check_rustc_legacy_const_generics(item, *attr_span, fn_indexes) } AttributeKind::Doc(attr) => self.check_doc_attrs(attr, hir_id, target), - AttributeKind::EiiImpls(impls) => self.check_eii_impl(impls), + AttributeKind::EiiImpl(eii_impl) => self.check_eii_impl(eii_impl), AttributeKind::RustcMustImplementOneOf { attr_span, fn_names } => { self.check_rustc_must_implement_one_of(*attr_span, fn_names, hir_id, target) } @@ -474,51 +474,50 @@ impl<'tcx> CheckAttrVisitor<'tcx> { /// Checks that each externally implementable item (EII) implementation uses `unsafe` /// exactly when its declaration requires it. - fn check_eii_impl(&self, impls: &[EiiImpl]) { - for EiiImpl { span, inner_span, resolution, impl_unsafe_span, is_default: _ } in impls { - let impl_unsafe = match resolution { - EiiImplResolution::Macro(eii_macro) => find_attr!( - self.tcx, - *eii_macro, - EiiDeclaration(EiiDecl { impl_unsafe, .. }) => *impl_unsafe - ), - EiiImplResolution::Known(foreign_item_did) => self - .tcx - .externally_implementable_items(foreign_item_did.krate) - .get(foreign_item_did) - .map(|(decl, _)| decl.impl_unsafe), - EiiImplResolution::Error(_) => None, - }; - let Some(needs_unsafe) = impl_unsafe else { - continue; - }; + fn check_eii_impl(&self, eii_impl: &EiiImpl) { + let EiiImpl { span, inner_span, resolution, impl_unsafe_span, is_default: _ } = eii_impl; + let impl_unsafe = match resolution { + EiiImplResolution::Macro(eii_macro) => find_attr!( + self.tcx, + *eii_macro, + EiiDeclaration(EiiDecl { impl_unsafe, .. }) => *impl_unsafe + ), + EiiImplResolution::Known(foreign_item_did) => self + .tcx + .externally_implementable_items(foreign_item_did.krate) + .get(foreign_item_did) + .map(|(decl, _)| decl.impl_unsafe), + EiiImplResolution::Error(_) => None, + }; + let Some(needs_unsafe) = impl_unsafe else { + return; + }; - let name = match resolution { - EiiImplResolution::Macro(eii_macro) => self.tcx.item_name(*eii_macro), - EiiImplResolution::Known(def_id) => self.tcx.item_name(*def_id), - EiiImplResolution::Error(_) => unreachable!(), - }; + let name = match resolution { + EiiImplResolution::Macro(eii_macro) => self.tcx.item_name(*eii_macro), + EiiImplResolution::Known(def_id) => self.tcx.item_name(*def_id), + EiiImplResolution::Error(_) => unreachable!(), + }; - match (needs_unsafe, *impl_unsafe_span) { - (true, None) => { - self.dcx().emit_err(diagnostics::EiiImplRequiresUnsafe { - span: *span, - name, - suggestion: diagnostics::EiiImplRequiresUnsafeSuggestion { - left: inner_span.shrink_to_lo(), - right: inner_span.shrink_to_hi(), - }, - }); - } - (false, Some(unsafe_span)) => { - self.dcx().emit_err(diagnostics::EiiImplCannotBeUnsafe { - impl_span: *span, - unsafe_span, - name, - }); - } - _ => {} + match (needs_unsafe, *impl_unsafe_span) { + (true, None) => { + self.dcx().emit_err(diagnostics::EiiImplRequiresUnsafe { + span: *span, + name, + suggestion: diagnostics::EiiImplRequiresUnsafeSuggestion { + left: inner_span.shrink_to_lo(), + right: inner_span.shrink_to_hi(), + }, + }); + } + (false, Some(unsafe_span)) => { + self.dcx().emit_err(diagnostics::EiiImplCannotBeUnsafe { + impl_span: *span, + unsafe_span, + name, + }); } + _ => {} } } diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index 63bff7a3f4498..97ca994c37540 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -303,7 +303,7 @@ impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> { expr: _, safety, define_opaque: _, - eii_impls: _, + eii_impl: _, }) => { let safety = match safety { ast::Safety::Unsafe(_) | ast::Safety::Default => hir::Safety::Unsafe, diff --git a/compiler/rustc_resolve/src/diagnostics/impls.rs b/compiler/rustc_resolve/src/diagnostics/impls.rs index cc2c72ad59906..ad6c9cea18126 100644 --- a/compiler/rustc_resolve/src/diagnostics/impls.rs +++ b/compiler/rustc_resolve/src/diagnostics/impls.rs @@ -2032,8 +2032,16 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { // Don't confuse the user with tool modules or open modules. continue; } - Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => { - "only a trait, without a derive macro".to_string() + Res::Def(DefKind::Trait, trait_def_id) if macro_kind == MacroKind::Derive => { + if let crate::DeclKind::Import { import, .. } = binding.kind + && !import.span.is_dummy() + { + self.record_use(ident, binding, Used::Other); + } + let trait_span = self.def_span(trait_def_id); + err.span_note(trait_span, format!("`{ident}` is a trait, not a derive macro")); + err.help(format!("consider implementing `{ident}` for your type manually")); + return; } res => format!( "{} {}, not {} {}", @@ -2065,6 +2073,29 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { return; } + // Not in scope: check if the name refers to a trait importable from elsewhere. + if macro_kind == MacroKind::Derive { + let trait_candidates = + self.lookup_import_candidates(ident, TypeNS, parent_scope, |res| { + matches!(res, Res::Def(DefKind::Trait, _)) + }); + let mut seen = FxHashSet::default(); + for candidate in &trait_candidates { + if let Some(def_id) = candidate.did + && seen.insert(def_id) + { + err.span_note( + self.def_span(def_id), + format!("`{ident}` is a trait, not a derive macro"), + ); + } + } + if !seen.is_empty() { + err.help(format!("consider implementing `{ident}` for your type manually")); + return; + } + } + if self.macro_names.contains(&IdentKey::new(ident)) { err.subdiagnostic(AddedMacroUse); return; diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index f30e6844c861c..fc723586c1acc 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -1147,7 +1147,7 @@ impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tc debug!("(resolving function) entering function"); if let FnKind::Fn(_, _, f) = fn_kind { - self.resolve_eii(&f.eii_impls); + self.resolve_eii(f.eii_impl.as_deref()); } // Create a value rib for the function. @@ -2940,7 +2940,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { } ItemKind::Static(ast::StaticItem { - ident, ty, expr, define_opaque, eii_impls, .. + ident, ty, expr, define_opaque, eii_impl, .. }) => { self.with_static_rib(def_kind, |this| { this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Static), |this| { @@ -2953,7 +2953,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { } }); self.resolve_define_opaques(define_opaque); - self.resolve_eii(&eii_impls); + self.resolve_eii(eii_impl.as_deref()); } ItemKind::Const(ast::ConstItem { @@ -5568,8 +5568,9 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { } } - fn resolve_eii(&mut self, eii_impls: &[EiiImpl]) { - for EiiImpl { node_id, eii_macro_path, known_eii_macro_resolution, .. } in eii_impls { + fn resolve_eii(&mut self, eii_impl: Option<&EiiImpl>) { + if let Some(EiiImpl { node_id, eii_macro_path, known_eii_macro_resolution, .. }) = eii_impl + { // See docs on the `known_eii_macro_resolution` field: // if we already know the resolution statically, don't bother resolving it. if let Some(target) = known_eii_macro_resolution { diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 022784b56d4ce..1cfd03288a417 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -1649,26 +1649,6 @@ impl PointerAuthOption { } } -#[derive(Clone, Copy)] -pub enum BackendJobs { - /// The number of backend jobs has a static limit. - Limited(NonZero), - /// The number of backend jobs is either unlimited if there's an inherited jobserver, - /// or limited to 32 if there's no inherited jobserver. - /// This variant exists only to preserve the historical behavior. - /// FIXME: Just use `thread::available_parallelism` as the default static limit. - UnlimitedOr32, -} - -impl BackendJobs { - pub fn value(self) -> NonZero { - match self { - BackendJobs::Limited(n) => n, - BackendJobs::UnlimitedOr32 => NonZero::new(32).unwrap(), - } - } -} - #[derive(Clone, Copy)] pub enum LinkerJobs { /// Do not pass anything to the linker, use it's default behavior. @@ -1682,7 +1662,7 @@ pub enum LinkerJobs { #[derive(Clone, Copy)] pub struct Jobs { pub frontend: Option>, - pub backend: Option, + pub backend: Option>, pub linker: LinkerJobs, } @@ -1735,11 +1715,12 @@ fn parse_jobs_all( let backend = parse_jobs_one(early_dcx, opt_name, &jobs_backend, unstable, &mut available); check_upper_limit(backend, opt_name); - backend.map(BackendJobs::Limited) + backend } None => match jobs { - Some(n) => n.map(BackendJobs::Limited), - None => Some(BackendJobs::UnlimitedOr32), + Some(n) => n, + // Use all available parallelism as the default. + None => parse_jobs_one(early_dcx, "", "0", unstable, &mut available), }, }; let linker = match matches.opt_str("jobs-linker") { diff --git a/compiler/rustc_target/src/spec/targets/loongarch32_unknown_none.rs b/compiler/rustc_target/src/spec/targets/loongarch32_unknown_none.rs index 7e074b73919f3..cbf8cec1e6865 100644 --- a/compiler/rustc_target/src/spec/targets/loongarch32_unknown_none.rs +++ b/compiler/rustc_target/src/spec/targets/loongarch32_unknown_none.rs @@ -8,7 +8,7 @@ pub(crate) fn target() -> Target { llvm_target: "loongarch32-unknown-none".into(), metadata: TargetMetadata { description: Some("Freestanding/bare-metal LoongArch32".into()), - tier: Some(3), + tier: Some(2), host_tools: Some(false), std: Some(false), }, diff --git a/compiler/rustc_target/src/spec/targets/loongarch32_unknown_none_softfloat.rs b/compiler/rustc_target/src/spec/targets/loongarch32_unknown_none_softfloat.rs index 4e6807012e891..3fd12e50d0ae3 100644 --- a/compiler/rustc_target/src/spec/targets/loongarch32_unknown_none_softfloat.rs +++ b/compiler/rustc_target/src/spec/targets/loongarch32_unknown_none_softfloat.rs @@ -8,7 +8,7 @@ pub(crate) fn target() -> Target { llvm_target: "loongarch32-unknown-none".into(), metadata: TargetMetadata { description: Some("Freestanding/bare-metal LoongArch32 softfloat".into()), - tier: Some(3), + tier: Some(2), host_tools: Some(false), std: Some(false), }, diff --git a/library/alloc/src/io/read.rs b/library/alloc/src/io/read.rs index fe1a8d11ccefe..1fe8417d90761 100644 --- a/library/alloc/src/io/read.rs +++ b/library/alloc/src/io/read.rs @@ -433,6 +433,7 @@ pub trait Read { /// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof #[unstable(feature = "read_buf", issue = "78485")] + #[doc(alias("read_exact_buf"))] fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_, u8>) -> Result<()> { default_read_buf_exact(self, cursor) } diff --git a/library/core/src/os/darwin/objc.rs b/library/core/src/os/darwin/objc.rs index df3aab867e83d..7be07891085a3 100644 --- a/library/core/src/os/darwin/objc.rs +++ b/library/core/src/os/darwin/objc.rs @@ -67,7 +67,8 @@ pub type SEL = *mut objc_selector; /// /// # Example /// -/// ```no_run +#[cfg_attr(target_os = "macos", doc = "```no_run")] +#[cfg_attr(not(target_os = "macos"), doc = "```ignore (needs macos)")] /// #![feature(darwin_objc)] /// use core::os::darwin::objc; /// @@ -93,7 +94,8 @@ pub macro class($classname:expr) {{ /// /// # Examples /// -/// ```no_run +#[cfg_attr(target_os = "macos", doc = "```no_run")] +#[cfg_attr(not(target_os = "macos"), doc = "```ignore (needs macos)")] /// #![feature(darwin_objc)] /// use core::os::darwin::objc; /// diff --git a/library/core/src/slice/cmp.rs b/library/core/src/slice/cmp.rs index 10a0088477162..3a62e7f61b2b4 100644 --- a/library/core/src/slice/cmp.rs +++ b/library/core/src/slice/cmp.rs @@ -391,10 +391,16 @@ where } } -impl SliceContains for u8 { +impl SliceContains for T { #[inline] fn slice_contains(&self, x: &[Self]) -> bool { - memchr::memchr(*self, x).is_some() + // SAFETY: `UnsignedBytewiseOrd` guarantees that `Self` has the same + // layout as `u8` and is initialized, so both the value and slice can + // be read as bytes. + let (byte, bytes) = unsafe { + (*(self as *const Self).cast::(), from_raw_parts(x.as_ptr().cast::(), x.len())) + }; + memchr::memchr(byte, bytes).is_some() } } diff --git a/library/coretests/tests/slice.rs b/library/coretests/tests/slice.rs index a4db7304fff90..22b1ba7738af9 100644 --- a/library/coretests/tests/slice.rs +++ b/library/coretests/tests/slice.rs @@ -5,6 +5,39 @@ use core::num::NonZero; use core::ops::{Range, RangeInclusive}; use core::slice; +#[test] +fn test_contains_bytewise_types() { + let mut bools = [false; 64]; + assert!(bools.contains(&false)); + assert!(!bools.contains(&true)); + bools[31] = true; + assert!(bools.contains(&true)); + + let one = NonZero::new(1_u8).unwrap(); + let two = NonZero::new(2_u8).unwrap(); + let three = NonZero::new(3_u8).unwrap(); + let mut nonzeros = [one; 64]; + nonzeros[31] = two; + assert!(nonzeros.contains(&one)); + assert!(nonzeros.contains(&two)); + assert!(!nonzeros.contains(&three)); + + let mut optional_nonzeros = [Some(one); 64]; + optional_nonzeros[31] = None; + assert!(optional_nonzeros.contains(&Some(one))); + assert!(optional_nonzeros.contains(&None)); + assert!(!optional_nonzeros.contains(&Some(two))); + + let a = core::ascii::Char::CapitalA; + let q = core::ascii::Char::CapitalQ; + let z = core::ascii::Char::CapitalZ; + let mut ascii = [a; 64]; + ascii[31] = z; + assert!(ascii.contains(&a)); + assert!(ascii.contains(&z)); + assert!(!ascii.contains(&q)); +} + #[test] fn test_position() { let b = [1, 2, 3, 5, 5]; diff --git a/library/std/src/os/unix/fs.rs b/library/std/src/os/unix/fs.rs index c119912c3b022..9b08f0cb3829f 100644 --- a/library/std/src/os/unix/fs.rs +++ b/library/std/src/os/unix/fs.rs @@ -198,6 +198,7 @@ pub trait FileExt { /// } /// ``` #[unstable(feature = "read_buf_at", issue = "140771")] + #[doc(alias("read_exact_buf_at"))] fn read_buf_exact_at( &self, mut buf: BorrowedCursor<'_, u8>, diff --git a/library/std/src/os/wasi/mod.rs b/library/std/src/os/wasi/mod.rs index 2ee6aa4660094..1db9ec906726f 100644 --- a/library/std/src/os/wasi/mod.rs +++ b/library/std/src/os/wasi/mod.rs @@ -11,7 +11,8 @@ //! //! # Examples //! -//! ```no_run +#![cfg_attr(target_os = "wasi", doc = "```no_run")] +#![cfg_attr(not(target_os = "wasi"), doc = "```ignore (needs wasi)")] //! use std::fs::File; //! use std::os::wasi::prelude::*; //! diff --git a/library/std/src/os/windows/ffi.rs b/library/std/src/os/windows/ffi.rs index ed933975bd5a5..3cda3e25fb544 100644 --- a/library/std/src/os/windows/ffi.rs +++ b/library/std/src/os/windows/ffi.rs @@ -72,7 +72,8 @@ pub impl(self) trait OsStringExt { /// /// # Examples /// - /// ``` + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::ffi::OsString; /// use std::os::windows::prelude::*; /// @@ -104,7 +105,8 @@ pub impl(self) trait OsStrExt { /// /// # Examples /// - /// ``` + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::ffi::OsString; /// use std::os::windows::prelude::*; /// diff --git a/library/std/src/os/windows/fs.rs b/library/std/src/os/windows/fs.rs index dfa9236a7e428..7b4f5e7a40055 100644 --- a/library/std/src/os/windows/fs.rs +++ b/library/std/src/os/windows/fs.rs @@ -31,7 +31,8 @@ pub trait FileExt { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::io; /// use std::fs::File; /// use std::os::windows::prelude::*; @@ -59,7 +60,8 @@ pub trait FileExt { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(core_io_borrowed_buf)] /// #![feature(read_buf_at)] /// @@ -104,7 +106,8 @@ pub trait FileExt { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::fs::File; /// use std::os::windows::prelude::*; /// @@ -151,7 +154,8 @@ pub trait OpenOptionsExt { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::fs::OpenOptions; /// use std::os::windows::prelude::*; /// @@ -176,7 +180,8 @@ pub trait OpenOptionsExt { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::fs::OpenOptions; /// use std::os::windows::prelude::*; /// @@ -202,7 +207,8 @@ pub trait OpenOptionsExt { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// # #![allow(unexpected_cfgs)] /// # #[cfg(for_demonstration_only)] /// extern crate winapi; @@ -240,7 +246,8 @@ pub trait OpenOptionsExt { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// # #![allow(unexpected_cfgs)] /// # #[cfg(for_demonstration_only)] /// extern crate winapi; @@ -282,7 +289,8 @@ pub trait OpenOptionsExt { /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// # #![allow(unexpected_cfgs)] /// # #[cfg(for_demonstration_only)] /// extern crate winapi; @@ -377,7 +385,8 @@ impl OpenOptionsExt2 for OpenOptions { /// /// # Example /// -/// ```no_run +#[cfg_attr(windows, doc = "```no_run")] +#[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_permissions_ext)] /// use std::fs::Permissions; /// use std::os::windows::fs::PermissionsExt; @@ -440,7 +449,8 @@ pub trait MetadataExt { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::io; /// use std::fs; /// use std::os::windows::prelude::*; @@ -470,7 +480,8 @@ pub trait MetadataExt { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::io; /// use std::fs; /// use std::os::windows::prelude::*; @@ -505,7 +516,8 @@ pub trait MetadataExt { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::io; /// use std::fs; /// use std::os::windows::prelude::*; @@ -538,7 +550,8 @@ pub trait MetadataExt { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::io; /// use std::fs; /// use std::os::windows::prelude::*; @@ -561,7 +574,8 @@ pub trait MetadataExt { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::io; /// use std::fs; /// use std::os::windows::prelude::*; @@ -700,7 +714,8 @@ impl FileTimesExt for fs::FileTimes { /// /// # Examples /// -/// ```no_run +#[cfg_attr(windows, doc = "```no_run")] +#[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::os::windows::fs; /// /// fn main() -> std::io::Result<()> { @@ -739,7 +754,8 @@ pub fn symlink_file, Q: AsRef>(original: P, link: Q) -> io: /// /// # Examples /// -/// ```no_run +#[cfg_attr(windows, doc = "```no_run")] +#[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::os::windows::fs; /// /// fn main() -> std::io::Result<()> { diff --git a/library/std/src/os/windows/io/handle.rs b/library/std/src/os/windows/io/handle.rs index e58f94253bdf7..29697bbb5f8fc 100644 --- a/library/std/src/os/windows/io/handle.rs +++ b/library/std/src/os/windows/io/handle.rs @@ -424,7 +424,8 @@ pub trait AsHandle { /// /// # Example /// - /// ```rust,no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// use std::fs::File; /// # use std::io; /// use std::os::windows::io::{AsHandle, BorrowedHandle}; diff --git a/library/std/src/os/windows/io/mod.rs b/library/std/src/os/windows/io/mod.rs index db0ec8f2fbb2e..bf0605aa08a95 100644 --- a/library/std/src/os/windows/io/mod.rs +++ b/library/std/src/os/windows/io/mod.rs @@ -83,7 +83,8 @@ pub impl(self) trait StdioExt { /// (e.g. C stdio) or libraries that acquire a clone of the file handle /// will not be aware of this change. /// - /// ``` + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(stdio_swap)] /// use std::io::{self, Read, Write}; /// use std::os::windows::io::StdioExt; diff --git a/library/std/src/os/windows/mod.rs b/library/std/src/os/windows/mod.rs index 53c33d17a9f65..a7e032dbf4d4d 100644 --- a/library/std/src/os/windows/mod.rs +++ b/library/std/src/os/windows/mod.rs @@ -8,7 +8,8 @@ //! //! # Examples //! -//! ```no_run +#![cfg_attr(windows, doc = "```no_run")] +#![cfg_attr(not(windows), doc = "```ignore (needs windows)")] //! use std::fs::File; //! use std::os::windows::prelude::*; //! diff --git a/library/std/src/os/windows/net/addr.rs b/library/std/src/os/windows/net/addr.rs index ef2263edcf617..c330432039a8f 100644 --- a/library/std/src/os/windows/net/addr.rs +++ b/library/std/src/os/windows/net/addr.rs @@ -79,7 +79,8 @@ impl SocketAddr { /// /// With a pathname: /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixListener; /// use std::path::Path; @@ -104,7 +105,8 @@ impl SocketAddr { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::SocketAddr; /// use std::path::Path; @@ -118,7 +120,8 @@ impl SocketAddr { /// /// Creating a `SocketAddr` with a NULL byte results in an error. /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::SocketAddr; /// @@ -151,7 +154,8 @@ impl SocketAddr { /// /// A named address: /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixListener; /// diff --git a/library/std/src/os/windows/net/listener.rs b/library/std/src/os/windows/net/listener.rs index 345cfe8d22ba9..19f5254e08bf9 100644 --- a/library/std/src/os/windows/net/listener.rs +++ b/library/std/src/os/windows/net/listener.rs @@ -16,7 +16,8 @@ use crate::{fmt, io}; /// /// # Examples /// -/// ```no_run +#[cfg_attr(windows, doc = "```no_run")] +#[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::thread; /// use std::os::windows::net::{UnixStream, UnixListener}; @@ -61,7 +62,8 @@ impl UnixListener { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixListener; /// @@ -84,7 +86,8 @@ impl UnixListener { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::{UnixListener}; /// @@ -122,7 +125,8 @@ impl UnixListener { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixListener; /// @@ -148,7 +152,8 @@ impl UnixListener { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixListener; /// @@ -170,7 +175,8 @@ impl UnixListener { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixListener; /// @@ -194,7 +200,8 @@ impl UnixListener { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixListener; /// @@ -212,7 +219,8 @@ impl UnixListener { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixListener; /// @@ -236,7 +244,8 @@ impl UnixListener { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::thread; /// use std::os::windows::net::{UnixStream, UnixListener}; @@ -272,7 +281,8 @@ impl UnixListener { /// /// # Examples /// -/// ```no_run +#[cfg_attr(windows, doc = "```no_run")] +#[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::thread; /// use std::os::windows::net::{UnixStream, UnixListener}; diff --git a/library/std/src/os/windows/net/stream.rs b/library/std/src/os/windows/net/stream.rs index f2d0f7c09e9f1..c0f32e75411e9 100644 --- a/library/std/src/os/windows/net/stream.rs +++ b/library/std/src/os/windows/net/stream.rs @@ -21,7 +21,8 @@ use crate::{fmt, io}; /// /// # Examples /// -/// ```no_run +#[cfg_attr(windows, doc = "```no_run")] +#[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixStream; /// use std::io::prelude::*; @@ -54,7 +55,8 @@ impl UnixStream { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixStream; /// @@ -77,7 +79,8 @@ impl UnixStream { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::{UnixListener, UnixStream}; /// @@ -112,7 +115,8 @@ impl UnixStream { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixStream; /// @@ -130,7 +134,8 @@ impl UnixStream { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixStream; /// @@ -148,7 +153,8 @@ impl UnixStream { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixStream; /// use std::time::Duration; @@ -168,7 +174,8 @@ impl UnixStream { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixStream; /// @@ -192,7 +199,8 @@ impl UnixStream { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixStream; /// use std::time::Duration; @@ -207,7 +215,8 @@ impl UnixStream { /// An [`Err`] is returned if the zero [`Duration`] is passed to this /// method: /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::io; /// use std::os::windows::net::UnixStream; @@ -235,7 +244,8 @@ impl UnixStream { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixStream; /// use std::time::Duration; @@ -251,7 +261,8 @@ impl UnixStream { /// An [`Err`] is returned if the zero [`Duration`] is passed to this /// method: /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::io; /// use std::os::windows::net::UnixStream; @@ -277,7 +288,8 @@ impl UnixStream { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixStream; /// use std::net::Shutdown; @@ -296,7 +308,8 @@ impl UnixStream { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixStream; /// @@ -321,7 +334,8 @@ impl UnixStream { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixStream; /// @@ -339,7 +353,8 @@ impl UnixStream { /// /// # Examples /// - /// ```no_run + #[cfg_attr(windows, doc = "```no_run")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_unix_domain_sockets)] /// use std::os::windows::net::UnixStream; /// use std::time::Duration; diff --git a/library/std/src/os/windows/process.rs b/library/std/src/os/windows/process.rs index 3332714ae4bb7..41dcb70c59c9f 100644 --- a/library/std/src/os/windows/process.rs +++ b/library/std/src/os/windows/process.rs @@ -273,7 +273,8 @@ pub impl(self) trait CommandExt { /// /// # Example /// - /// ``` + #[cfg_attr(windows, doc = "```")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_process_extensions_async_pipes)] /// use std::os::windows::process::CommandExt; /// use std::process::{Command, Stdio}; @@ -304,7 +305,8 @@ pub impl(self) trait CommandExt { /// /// # Example /// - /// ``` + #[cfg_attr(windows, doc = "```")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_process_extensions_raw_attribute)] /// use std::os::windows::io::AsRawHandle; /// use std::os::windows::process::{CommandExt, ProcThreadAttributeList}; @@ -563,8 +565,9 @@ impl<'a> ProcThreadAttributeListBuilder<'a> { /// /// # Example /// - #[cfg_attr(target_vendor = "win7", doc = "```no_run")] - #[cfg_attr(not(target_vendor = "win7"), doc = "```")] + #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] + #[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)] /// use std::ffi::c_void; /// use std::os::windows::process::{CommandExt, ProcThreadAttributeList}; diff --git a/library/stdarch/crates/core_arch/src/amdgpu/mod.rs b/library/stdarch/crates/core_arch/src/amdgpu/mod.rs index 374f582696947..91dfbd1a16c0f 100644 --- a/library/stdarch/crates/core_arch/src/amdgpu/mod.rs +++ b/library/stdarch/crates/core_arch/src/amdgpu/mod.rs @@ -351,13 +351,13 @@ pub unsafe fn sched_barrier() { /// Combining multiple `sched_group_barrier` intrinsics enables an ordering of specific instruction types during instruction scheduling. /// For example, the following enforces a sequence of 1 VMEM read, followed by 1 VALU instruction, followed by 5 MFMA instructions. /// -/// ```rust +/// ```ignore (only available on AMD) /// // 1 VMEM read -/// sched_group_barrier::<32, 1, 0>() +/// sched_group_barrier::<32, 1, 0>(); /// // 1 VALU -/// sched_group_barrier::<2, 1, 0>() +/// sched_group_barrier::<2, 1, 0>(); /// // 5 MFMA -/// sched_group_barrier::<8, 5, 0>() +/// sched_group_barrier::<8, 5, 0>(); /// ``` /// #[doc = include_str!("intrinsic_is_convergent.md")] diff --git a/library/stdarch/crates/core_arch/src/nvptx/mod.rs b/library/stdarch/crates/core_arch/src/nvptx/mod.rs index d22f3a25bf70e..53d53d1e1ef60 100644 --- a/library/stdarch/crates/core_arch/src/nvptx/mod.rs +++ b/library/stdarch/crates/core_arch/src/nvptx/mod.rs @@ -157,10 +157,13 @@ unsafe extern "C" { /// * `format`: A pointer to the format specifier input (uses common `printf` format). /// * `valist`: A pointer to the valist input. /// - /// ``` + /// ```ignore (available only for nvptx) + /// # use std::mem::transmute; /// #[repr(C)] /// struct PrintArgs(f32, f32, f32, i32); /// + /// let a = 0.1f32; + /// let b = 0.2f32; /// vprintf( /// "int(%f + %f) = int(%f) = %d\n".as_ptr(), /// transmute(&PrintArgs(a, b, a + b, (a + b) as i32)), diff --git a/library/stdarch/crates/core_arch/src/x86/mod.rs b/library/stdarch/crates/core_arch/src/x86/mod.rs index fbf1002eab8ba..589efbcf872d5 100644 --- a/library/stdarch/crates/core_arch/src/x86/mod.rs +++ b/library/stdarch/crates/core_arch/src/x86/mod.rs @@ -39,7 +39,11 @@ types! { /// /// # Examples /// - /// ``` + #[cfg_attr(any(target_arch = "x86", target_arch = "x86_64"), doc = "```")] + #[cfg_attr( + not(any(target_arch = "x86", target_arch = "x86_64")), + doc = "```ignore (only works on x86 targets)", + )] /// #[cfg(target_arch = "x86")] /// use std::arch::x86::*; /// #[cfg(target_arch = "x86_64")] @@ -82,7 +86,11 @@ types! { /// /// # Examples /// - /// ``` + #[cfg_attr(any(target_arch = "x86", target_arch = "x86_64"), doc = "```")] + #[cfg_attr( + not(any(target_arch = "x86", target_arch = "x86_64")), + doc = "```ignore (only works on x86 targets)", + )] /// #[cfg(target_arch = "x86")] /// use std::arch::x86::*; /// #[cfg(target_arch = "x86_64")] @@ -125,7 +133,11 @@ types! { /// /// # Examples /// - /// ``` + #[cfg_attr(any(target_arch = "x86", target_arch = "x86_64"), doc = "```")] + #[cfg_attr( + not(any(target_arch = "x86", target_arch = "x86_64")), + doc = "```ignore (only works on x86 targets)", + )] /// #[cfg(target_arch = "x86")] /// use std::arch::x86::*; /// #[cfg(target_arch = "x86_64")] @@ -172,7 +184,11 @@ types! { /// /// # Examples /// - /// ``` + #[cfg_attr(any(target_arch = "x86", target_arch = "x86_64"), doc = "```")] + #[cfg_attr( + not(any(target_arch = "x86", target_arch = "x86_64")), + doc = "```ignore (only works on x86 targets)", + )] /// #[cfg(target_arch = "x86")] /// use std::arch::x86::*; /// #[cfg(target_arch = "x86_64")] @@ -215,7 +231,11 @@ types! { /// /// # Examples /// - /// ``` + #[cfg_attr(any(target_arch = "x86", target_arch = "x86_64"), doc = "```")] + #[cfg_attr( + not(any(target_arch = "x86", target_arch = "x86_64")), + doc = "```ignore (only works on x86 targets)", + )] /// #[cfg(target_arch = "x86")] /// use std::arch::x86::*; /// #[cfg(target_arch = "x86_64")] @@ -258,7 +278,11 @@ types! { /// /// # Examples /// - /// ``` + #[cfg_attr(any(target_arch = "x86", target_arch = "x86_64"), doc = "```")] + #[cfg_attr( + not(any(target_arch = "x86", target_arch = "x86_64")), + doc = "```ignore (only works on x86 targets)", + )] /// #[cfg(target_arch = "x86")] /// use std::arch::x86::*; /// #[cfg(target_arch = "x86_64")] diff --git a/src/ci/docker/README.md b/src/ci/docker/README.md index b113adc2008cd..8360c8e9d8b48 100644 --- a/src/ci/docker/README.md +++ b/src/ci/docker/README.md @@ -261,9 +261,9 @@ For targets: `loongarch64-unknown-linux-gnu` - Target options > Bitness = 64-bit - Operating System > Target OS = linux - Operating System > Linux kernel version = 5.19.16 -- Binary utilities > Version of binutils = 2.45 +- Binary utilities > Version of binutils = 2.46.1 - C-library > glibc version = 2.36 -- C compiler > gcc version = 15.2.0 +- C compiler > gcc version = 16.1.0 - C compiler > C++ = ENABLE -- to cross compile LLVM ### `loongarch64-unknown-linux-musl.defconfig` @@ -277,9 +277,9 @@ For targets: `loongarch64-unknown-linux-musl` - Target options > Bitness = 64-bit - Operating System > Target OS = linux - Operating System > Linux kernel version = 5.19.16 -- Binary utilities > Version of binutils = 2.45 +- Binary utilities > Version of binutils = 2.46.1 - C-library > musl version = 1.2.5 -- C compiler > gcc version = 15.2.0 +- C compiler > gcc version = 16.1.0 - C compiler > C++ = ENABLE -- to cross compile LLVM ### `mips-linux-gnu.defconfig` diff --git a/src/ci/docker/host-x86_64/dist-loongarch64-linux/Dockerfile b/src/ci/docker/host-x86_64/dist-loongarch64-linux/Dockerfile index f60167b94d071..9b1684bbd2ace 100644 --- a/src/ci/docker/host-x86_64/dist-loongarch64-linux/Dockerfile +++ b/src/ci/docker/host-x86_64/dist-loongarch64-linux/Dockerfile @@ -3,9 +3,9 @@ FROM ubuntu:22.04 COPY scripts/cross-apt-packages.sh /scripts/ RUN sh /scripts/cross-apt-packages.sh -COPY scripts/crosstool-ng.sh /scripts/ +COPY scripts/crosstool-ng-git.sh /scripts/ COPY scripts/crosstool-ng-sha256-20260705.diff /scripts/ -RUN sh /scripts/crosstool-ng.sh +RUN sh /scripts/crosstool-ng-git.sh COPY scripts/rustbuild-setup.sh /scripts/ RUN sh /scripts/rustbuild-setup.sh @@ -39,12 +39,24 @@ ENV CC_loongarch64_unknown_none=loongarch64-unknown-linux-gnu-gcc \ AR_loongarch64_unknown_none_softfloat=loongarch64-unknown-linux-gnu-ar \ CXX_loongarch64_unknown_none_softfloat=loongarch64-unknown-linux-gnu-g++ \ CFLAGS_loongarch64_unknown_none_softfloat="-ffreestanding -mabi=lp64s -mfpu=none" \ - CXXFLAGS_loongarch64_unknown_none_softfloat="-ffreestanding -mabi=lp64s -mfpu=none" + CXXFLAGS_loongarch64_unknown_none_softfloat="-ffreestanding -mabi=lp64s -mfpu=none" \ + CC_loongarch32_unknown_none=loongarch64-unknown-linux-gnu-gcc \ + AR_loongarch32_unknown_none=loongarch64-unknown-linux-gnu-ar \ + CXX_loongarch32_unknown_none=loongarch64-unknown-linux-gnu-g++ \ + CFLAGS_loongarch32_unknown_none="-ffreestanding -march=la32rv1.0 -mabi=ilp32d" \ + CXXFLAGS_loongarch32_unknown_none="-ffreestanding -march=la32rv1.0 -mabi=ilp32d" \ + CC_loongarch32_unknown_none_softfloat=loongarch64-unknown-linux-gnu-gcc \ + AR_loongarch32_unknown_none_softfloat=loongarch64-unknown-linux-gnu-ar \ + CXX_loongarch32_unknown_none_softfloat=loongarch64-unknown-linux-gnu-g++ \ + CFLAGS_loongarch32_unknown_none_softfloat="-ffreestanding -march=la32rv1.0 -mabi=ilp32s -mfpu=none" \ + CXXFLAGS_loongarch32_unknown_none_softfloat="-ffreestanding -march=la32rv1.0 -mabi=ilp32s -mfpu=none" ENV HOSTS=loongarch64-unknown-linux-gnu ENV TARGETS=$HOSTS ENV TARGETS=$TARGETS,loongarch64-unknown-none ENV TARGETS=$TARGETS,loongarch64-unknown-none-softfloat +ENV TARGETS=$TARGETS,loongarch32-unknown-none +ENV TARGETS=$TARGETS,loongarch32-unknown-none-softfloat ENV RUST_CONFIGURE_ARGS="--enable-extended \ --enable-full-tools \ diff --git a/src/ci/docker/host-x86_64/dist-loongarch64-linux/loongarch64-unknown-linux-gnu.defconfig b/src/ci/docker/host-x86_64/dist-loongarch64-linux/loongarch64-unknown-linux-gnu.defconfig index 60c9cc7ef7252..5b3f1a270edfa 100644 --- a/src/ci/docker/host-x86_64/dist-loongarch64-linux/loongarch64-unknown-linux-gnu.defconfig +++ b/src/ci/docker/host-x86_64/dist-loongarch64-linux/loongarch64-unknown-linux-gnu.defconfig @@ -14,7 +14,7 @@ CT_KERNEL_LINUX=y CT_LINUX_V_5_19=y CT_LINUX_VERSION="5.19.16" CT_GLIBC_V_2_36=y -CT_BINUTILS_V_2_45=y -CT_GCC_V_15=y +CT_BINUTILS_V_2_46=y +CT_GCC_V_16=y CT_CC_GCC_ENABLE_DEFAULT_PIE=y CT_CC_LANG_CXX=y diff --git a/src/ci/docker/host-x86_64/dist-loongarch64-musl/Dockerfile b/src/ci/docker/host-x86_64/dist-loongarch64-musl/Dockerfile index 8fdfe7f78b100..f9eac213e5060 100644 --- a/src/ci/docker/host-x86_64/dist-loongarch64-musl/Dockerfile +++ b/src/ci/docker/host-x86_64/dist-loongarch64-musl/Dockerfile @@ -3,9 +3,9 @@ FROM ubuntu:22.04 COPY scripts/cross-apt-packages.sh /scripts/ RUN sh /scripts/cross-apt-packages.sh -COPY scripts/crosstool-ng.sh /scripts/ +COPY scripts/crosstool-ng-git.sh /scripts/ COPY scripts/crosstool-ng-sha256-20260705.diff /scripts/ -RUN sh /scripts/crosstool-ng.sh +RUN sh /scripts/crosstool-ng-git.sh COPY scripts/rustbuild-setup.sh /scripts/ RUN sh /scripts/rustbuild-setup.sh diff --git a/src/ci/docker/host-x86_64/dist-loongarch64-musl/loongarch64-unknown-linux-musl.defconfig b/src/ci/docker/host-x86_64/dist-loongarch64-musl/loongarch64-unknown-linux-musl.defconfig index 73e29d7aca725..07fed33600f29 100644 --- a/src/ci/docker/host-x86_64/dist-loongarch64-musl/loongarch64-unknown-linux-musl.defconfig +++ b/src/ci/docker/host-x86_64/dist-loongarch64-musl/loongarch64-unknown-linux-musl.defconfig @@ -15,8 +15,8 @@ CT_LINUX_V_5_19=y CT_LINUX_VERSION="5.19.16" CT_LIBC_MUSL=y CT_MUSL_V_1_2_5=y -CT_BINUTILS_V_2_45=y -CT_GCC_V_15=y +CT_BINUTILS_V_2_46=y +CT_GCC_V_16=y CT_CC_GCC_ENABLE_DEFAULT_PIE=y CT_CC_LANG_CXX=y CT_GETTEXT_NEEDED=y diff --git a/src/ci/docker/scripts/build-gcc.sh b/src/ci/docker/scripts/build-gcc.sh index ab4cae21e0254..c08c6971f8101 100755 --- a/src/ci/docker/scripts/build-gcc.sh +++ b/src/ci/docker/scripts/build-gcc.sh @@ -3,6 +3,14 @@ set -eux source shared.sh +# We need to install a newer version of `make` to be able to build `gcc`. +curl https://ci-mirrors.rust-lang.org/rustc/gcc/make-4.4.1.tar.gz | tar --extract --gzip +cd make-4.4.1 +hide_output ./configure --prefix=/rustroot +hide_output make +hide_output make install +cd .. + # Note: in the future when bumping to version 10.1.0, also take care of the sed block below. # This version is specified in the Dockerfile GCC=$GCC_VERSION diff --git a/src/ci/docker/scripts/crosstool-ng-git.sh b/src/ci/docker/scripts/crosstool-ng-git.sh new file mode 100644 index 0000000000000..faccd7dc9bbf5 --- /dev/null +++ b/src/ci/docker/scripts/crosstool-ng-git.sh @@ -0,0 +1,30 @@ +#!/bin/sh +set -ex + +# ignore-tidy-file-linelength + +URL=https://github.com/crosstool-ng/crosstool-ng +REV=27cd8380e72bb1cf3e7cf4a06a9cdbdc57df6f72 + +mkdir crosstool-ng +cd crosstool-ng +git init +git fetch --depth=1 ${URL} ${REV} +git reset --hard FETCH_HEAD + +# https://github.com/crosstool-ng/crosstool-ng/issues/1832 +# "download source of zlib is invalid now" +sed -e "s|zlib.net/'|zlib.net/fossils'|" -i packages/zlib/package.desc + +# FIXME(#158718): patch crosstools-ng known-good kernel artifact SHA256 +# checksums to the artifacts we mirror in `ci-mirrors`. +# See +# . +patch -p1 , /// Current computed `cfg`. Each time we enter a new item, this field is updated as well while /// taking into account the `hidden_cfg` information. - current_cfg: Cfg, + pub(crate) current_cfg: Cfg, /// Whether the `doc(auto_cfg())` feature is enabled or not at this point. auto_cfg_active: bool, /// If the parent item used `doc(cfg(...))`, then we don't want to overwrite `current_cfg`, diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 9290555f2ef39..20a466fd3dee9 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -117,18 +117,22 @@ pub(crate) fn clean_middle_generic_args<'tcx>( }; let mut elision_has_failed_once_before = false; + + // Calculates where the parent trait's generic parameters end + let index_offset = generics.count() - args.len(); let clean_arg = |(index, &arg): (usize, &ty::GenericArg<'tcx>)| { // Elide the self type. if has_self && index == 0 { return None; } - let param = generics.param_at(index, cx.tcx); + // Skips over the parent trait's generic parameters + let param = generics.param_at(index + index_offset, cx.tcx); let arg = ty::Binder::bind_with_vars(arg, bound_vars); // Elide arguments that coincide with their default. if !elision_has_failed_once_before && let Some(default) = param.default_value(cx.tcx) { - let default = default.instantiate(cx.tcx, args.as_ref()).skip_norm_wip(); + let default = default.instantiate(cx.tcx, args.as_ref()).skip_normalization(); if can_elide_generic_arg(arg, arg.rebind(default)) { return None; } diff --git a/src/librustdoc/doctest/rust.rs b/src/librustdoc/doctest/rust.rs index d89fb2ae1767b..13f705f9c3f47 100644 --- a/src/librustdoc/doctest/rust.rs +++ b/src/librustdoc/doctest/rust.rs @@ -6,17 +6,18 @@ use std::sync::Arc; use proc_macro2::{TokenStream, TokenTree}; use rustc_attr_parsing::eval_config_entry; -use rustc_hir::attrs::AttributeKind; +use rustc_hir::attrs::{AttributeKind, CfgEntry}; use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId}; -use rustc_hir::{self as hir, Attribute, CRATE_HIR_ID, intravisit}; +use rustc_hir::{self as hir, CRATE_HIR_ID, intravisit}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; use rustc_resolve::rustdoc::span_of_fragments; use rustc_span::source_map::SourceMap; -use rustc_span::{BytePos, DUMMY_SP, FileName, Pos, Span}; +use rustc_span::{BytePos, DUMMY_SP, FileName, Pos, Span, sym}; use super::{DocTestVisitor, ScrapedDocTest}; -use crate::clean::{Attributes, CfgInfo, extract_cfg_from_attrs}; +use crate::clean::cfg::Cfg; +use crate::clean::{Attributes, CfgInfo}; use crate::html::markdown::{self, CodeLineMapping, ErrorCodes, LangString, MdRelLine}; struct RustCollector { @@ -118,58 +119,73 @@ impl HirCollector<'_> { sp: Span, nested: F, ) { - let ast_attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id)); - if let Some(ref cfg) = - extract_cfg_from_attrs(ast_attrs.iter(), self.tcx, &mut CfgInfo::default()) - && !eval_config_entry(&self.tcx.sess, cfg.inner()).as_bool() - { - return; - } + let hir_attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id)); + + let mut cfg_info = CfgInfo::default(); + let mut found_features = 0; let source_map = self.tcx.sess.source_map(); - // Try collecting `#[doc(test(attr(...)))]` let old_global_crate_attrs_len = self.collector.global_crate_attrs.len(); - for attr in ast_attrs { - let Attribute::Parsed(AttributeKind::Doc(d)) = attr else { continue }; - for attr_span in &d.test_attrs { - // FIXME: This is ugly, remove when `test_attrs` has been ported to new attribute API. - if let Ok(snippet) = source_map.span_to_snippet(*attr_span) - && let Ok(stream) = TokenStream::from_str(&snippet) - { - let mut iter = stream.into_iter().peekable(); - while let Some(token) = iter.next() { - if let TokenTree::Ident(i) = token { - let i = i.to_string(); - let peek = iter.peek(); - // From this ident, we can have things like: - // - // * Group: `allow(...)` - // * Name/value: `crate_name = "..."` - // * Tokens: `html_no_url` - // - // So we peek next element to know what case we are in. - match peek { - Some(TokenTree::Group(g)) => { - let g = g.to_string(); - iter.next(); - // Add the additional attributes to the global_crate_attrs vector - self.collector.global_crate_attrs.push(format!("{i}{g}")); - } - // If next item is `=`, it means it's a name value so we will need - // to get the value as well. - Some(TokenTree::Punct(p)) if p.as_char() == '=' => { - let p = p.to_string(); - iter.next(); - if let Some(last) = iter.next() { - // Add the additional attributes to the global_crate_attrs vector - self.collector - .global_crate_attrs - .push(format!("{i}{p}{last}")); + // This loop does two things: + // + // 1. Collect `#[target_feature(...)]`. + // 2. Collect `#[doc(test(attr(...)))]`. + for attr in hir_attrs.iter() { + let hir::Attribute::Parsed(attr) = attr else { continue }; + if let AttributeKind::TargetFeature { features, .. } = attr { + for (feature, _) in features { + found_features += 1; + cfg_info.current_cfg &= Cfg(CfgEntry::NameValue { + name: sym::target_feature, + value: Some(*feature), + span: DUMMY_SP, + }); + } + } else if let AttributeKind::Doc(d) = attr { + for attr_span in &d.test_attrs { + // FIXME: This is ugly, remove when `test_attrs` has been ported to new + // attribute API. + if let Ok(snippet) = source_map.span_to_snippet(*attr_span) + && let Ok(stream) = TokenStream::from_str(&snippet) + { + let mut iter = stream.into_iter().peekable(); + while let Some(token) = iter.next() { + if let TokenTree::Ident(i) = token { + let i = i.to_string(); + let peek = iter.peek(); + // From this ident, we can have things like: + // + // * Group: `allow(...)` + // * Name/value: `crate_name = "..."` + // * Tokens: `html_no_url` + // + // So we peek next element to know what case we are in. + match peek { + Some(TokenTree::Group(g)) => { + let g = g.to_string(); + iter.next(); + // Add the additional attributes to the `global_crate_attrs` + // vector + self.collector.global_crate_attrs.push(format!("{i}{g}")); + } + // If next item is `=`, it means it's a name value so we will + // need to get the value as well. + Some(TokenTree::Punct(p)) if p.as_char() == '=' => { + let p = p.to_string(); + iter.next(); + if let Some(last) = iter.next() { + // Add the additional attributes to the + // `global_crate_attrs` vector. + self.collector + .global_crate_attrs + .push(format!("{i}{p}{last}")); + } + } + _ => { + // Add the additional attributes to the `global_crate_attrs` + // vector. + self.collector.global_crate_attrs.push(i.to_string()); } - } - _ => { - // Add the additional attributes to the global_crate_attrs vector - self.collector.global_crate_attrs.push(i.to_string()); } } } @@ -178,6 +194,14 @@ impl HirCollector<'_> { } } + // We only look at the `target_feature` attributes as the `cfg` attributes have already been + // applied at this point, so no need to take them into account again. + if found_features != 0 + && !eval_config_entry(&self.tcx.sess, &cfg_info.current_cfg.inner()).as_bool() + { + return; + } + let mut has_name = false; if let Some(name) = name { self.collector.cur_path.push(name); @@ -186,7 +210,7 @@ impl HirCollector<'_> { // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with // anything else, this will combine them for us. - let attrs = Attributes::from_hir(ast_attrs); + let attrs = Attributes::from_hir(hir_attrs); if let Some(doc) = attrs.opt_doc_value() { let span = span_of_fragments(&attrs.doc_strings).unwrap_or(sp); self.collector.position = if span.edition().at_least_rust_2024() { @@ -194,7 +218,7 @@ impl HirCollector<'_> { } else { // this span affects filesystem path resolution, // so we need to keep it the same as it was previously - ast_attrs + hir_attrs .iter() .find(|attr| attr.doc_str().is_some()) .map(|attr| { diff --git a/src/tools/clippy/clippy_utils/src/ast_utils/mod.rs b/src/tools/clippy/clippy_utils/src/ast_utils/mod.rs index 3f0b99aa4d780..523e799ef2522 100644 --- a/src/tools/clippy/clippy_utils/src/ast_utils/mod.rs +++ b/src/tools/clippy/clippy_utils/src/ast_utils/mod.rs @@ -332,7 +332,7 @@ fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool { expr: le, safety: ls, define_opaque: _, - eii_impls: _, + eii_impl: _, }), Static(box StaticItem { ident: ri, @@ -341,7 +341,7 @@ fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool { expr: re, safety: rs, define_opaque: _, - eii_impls: _, + eii_impl: _, }), ) => eq_id(*li, *ri) && lm == rm && ls == rs && eq_ty(lt, rt) && eq_expr_opt(le.as_deref(), re.as_deref()), ( @@ -381,7 +381,7 @@ fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool { contract: lc, body: lb, define_opaque: _, - eii_impls: _, + eii_impl: _, }), Fn(box ast::Fn { defaultness: rd, @@ -391,7 +391,7 @@ fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool { contract: rc, body: rb, define_opaque: _, - eii_impls: _, + eii_impl: _, }), ) => { eq_defaultness(*ld, *rd) @@ -539,7 +539,7 @@ fn eq_foreign_item_kind(l: &ForeignItemKind, r: &ForeignItemKind) -> bool { expr: le, safety: ls, define_opaque: _, - eii_impls: _, + eii_impl: _, }), Static(box StaticItem { ident: ri, @@ -548,7 +548,7 @@ fn eq_foreign_item_kind(l: &ForeignItemKind, r: &ForeignItemKind) -> bool { expr: re, safety: rs, define_opaque: _, - eii_impls: _, + eii_impl: _, }), ) => eq_id(*li, *ri) && eq_ty(lt, rt) && lm == rm && eq_expr_opt(le.as_deref(), re.as_deref()) && ls == rs, ( @@ -560,7 +560,7 @@ fn eq_foreign_item_kind(l: &ForeignItemKind, r: &ForeignItemKind) -> bool { contract: lc, body: lb, define_opaque: _, - eii_impls: _, + eii_impl: _, }), Fn(box ast::Fn { defaultness: rd, @@ -570,7 +570,7 @@ fn eq_foreign_item_kind(l: &ForeignItemKind, r: &ForeignItemKind) -> bool { contract: rc, body: rb, define_opaque: _, - eii_impls: _, + eii_impl: _, }), ) => { eq_defaultness(*ld, *rd) @@ -649,7 +649,7 @@ fn eq_assoc_item_kind(l: &AssocItemKind, r: &AssocItemKind) -> bool { contract: lc, body: lb, define_opaque: _, - eii_impls: _, + eii_impl: _, }), Fn(box ast::Fn { defaultness: rd, @@ -659,7 +659,7 @@ fn eq_assoc_item_kind(l: &AssocItemKind, r: &AssocItemKind) -> bool { contract: rc, body: rb, define_opaque: _, - eii_impls: _, + eii_impl: _, }), ) => { eq_defaultness(*ld, *rd) diff --git a/tests/assembly-llvm/indexing-with-bools-no-redundant-instructions.rs b/tests/assembly-llvm/indexing-with-bools-no-redundant-instructions.rs new file mode 100644 index 0000000000000..7397f2ec673b0 --- /dev/null +++ b/tests/assembly-llvm/indexing-with-bools-no-redundant-instructions.rs @@ -0,0 +1,36 @@ +//@ assembly-output: emit-asm +//@ only-x86_64 +//@ ignore-windows CHECK patterns use the SysV x86-64 calling convention +//@ ignore-sgx Test incompatible with LVI mitigations +//@ compile-flags: -Copt-level=3 + +//! Regression test for https://github.com/rust-lang/rust/issues/123216. +//! Indexing with a `bool` should not generate redundant `jmp` or `and` +//! instructions. + +#![crate_type = "lib"] + +#[no_mangle] +pub fn bool_index(a: u32, b: bool, c: bool, d: &mut [u128; 2]) { + // CHECK-LABEL: bool_index: + // CHECK: testl %esi, %esi + // CHECK: je + // CHECK: xorb %dl, %dil + // CHECK: orb $1, (%rcx) + // CHECK-NOT: jmp + // CHECK-NOT: andb $1, %dil + // CHECK: movzbl %dil, %eax + // CHECK: andl $1, %eax + // CHECK: shll $4, %eax + // CHECK: orb $1, (%rcx,%rax) + // CHECK: retq + + let mut a = a & 1 != 0; + + if b { + a ^= c; + d[0] |= 1; + } + + d[a as usize] |= 1; +} diff --git a/tests/codegen-llvm/lib-optimizations/slice-contains.rs b/tests/codegen-llvm/lib-optimizations/slice-contains.rs new file mode 100644 index 0000000000000..ecca007875148 --- /dev/null +++ b/tests/codegen-llvm/lib-optimizations/slice-contains.rs @@ -0,0 +1,36 @@ +// Ensure one-byte slice `contains` specializations use the optimized byte search. +//@ compile-flags: -Copt-level=3 -Zinline-mir=false + +#![crate_type = "lib"] +#![feature(ascii_char)] + +use std::ascii::Char as AsciiChar; +use std::num::NonZeroU8; + +// CHECK-LABEL: @contains_bool +#[no_mangle] +pub fn contains_bool(x: bool, data: &[bool]) -> bool { + // CHECK: call core::slice::memchr + data.contains(&x) +} + +// CHECK-LABEL: @contains_nonzero_u8 +#[no_mangle] +pub fn contains_nonzero_u8(x: NonZeroU8, data: &[NonZeroU8]) -> bool { + // CHECK: call core::slice::memchr + data.contains(&x) +} + +// CHECK-LABEL: @contains_option_nonzero_u8 +#[no_mangle] +pub fn contains_option_nonzero_u8(x: Option, data: &[Option]) -> bool { + // CHECK: call core::slice::memchr + data.contains(&x) +} + +// CHECK-LABEL: @contains_ascii_char +#[no_mangle] +pub fn contains_ascii_char(x: AsciiChar, data: &[AsciiChar]) -> bool { + // CHECK: call core::slice::memchr + data.contains(&x) +} diff --git a/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.32bit.diff b/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.32bit.diff index a6756ba0245c7..f87e33bd69789 100644 --- a/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.32bit.diff +++ b/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.32bit.diff @@ -12,9 +12,9 @@ bb0: { StorageLive(_1); - _1 = const 1_usize as std::boxed::Box (Transmute); -- _2 = copy ((_1.0: std::ptr::Unique).0: std::ptr::NonNull) as *const Never (BoxDerefTransmute); +- _2 = copy (_1.0: std::ptr::Unique) as *const Never (BoxDerefTransmute); + _1 = const Box::(std::ptr::Unique:: {{ pointer: NonNull:: {{ pointer: {0x1 as *const Never} is !null }}, _marker: PhantomData:: }}, std::alloc::Global); -+ _2 = const std::ptr::NonNull:: {{ pointer: {0x1 as *const Never} is !null }} as *const Never (BoxDerefTransmute); ++ _2 = const std::ptr::Unique:: {{ pointer: std::ptr::NonNull:: {{ pointer: {0x1 as *const Never} is !null }}, _marker: std::marker::PhantomData:: }} as *const Never (BoxDerefTransmute); unreachable; } } diff --git a/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.64bit.diff b/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.64bit.diff index a6756ba0245c7..f87e33bd69789 100644 --- a/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.64bit.diff +++ b/tests/mir-opt/const_prop/transmute.unreachable_box.GVN.64bit.diff @@ -12,9 +12,9 @@ bb0: { StorageLive(_1); - _1 = const 1_usize as std::boxed::Box (Transmute); -- _2 = copy ((_1.0: std::ptr::Unique).0: std::ptr::NonNull) as *const Never (BoxDerefTransmute); +- _2 = copy (_1.0: std::ptr::Unique) as *const Never (BoxDerefTransmute); + _1 = const Box::(std::ptr::Unique:: {{ pointer: NonNull:: {{ pointer: {0x1 as *const Never} is !null }}, _marker: PhantomData:: }}, std::alloc::Global); -+ _2 = const std::ptr::NonNull:: {{ pointer: {0x1 as *const Never} is !null }} as *const Never (BoxDerefTransmute); ++ _2 = const std::ptr::Unique:: {{ pointer: std::ptr::NonNull:: {{ pointer: {0x1 as *const Never} is !null }}, _marker: std::marker::PhantomData:: }} as *const Never (BoxDerefTransmute); unreachable; } } diff --git a/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.32bit.diff b/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.32bit.diff index 352d9345eef84..aaa0655d3c60e 100644 --- a/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.32bit.diff +++ b/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.32bit.diff @@ -13,7 +13,7 @@ StorageLive(_1); - _1 = const 1_usize as std::boxed::Box (Transmute); + _1 = const Box::(std::ptr::Unique:: {{ pointer: NonNull:: {{ pointer: {0x1 as *const Never} is !null }}, _marker: PhantomData:: }}, std::alloc::Global); - _2 = copy ((_1.0: std::ptr::Unique).0: std::ptr::NonNull) as *const Never (BoxDerefTransmute); + _2 = copy (_1.0: std::ptr::Unique) as *const Never (BoxDerefTransmute); unreachable; } } diff --git a/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.64bit.diff b/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.64bit.diff index 352d9345eef84..aaa0655d3c60e 100644 --- a/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.64bit.diff +++ b/tests/mir-opt/dataflow-const-prop/transmute.unreachable_box.DataflowConstProp.64bit.diff @@ -13,7 +13,7 @@ StorageLive(_1); - _1 = const 1_usize as std::boxed::Box (Transmute); + _1 = const Box::(std::ptr::Unique:: {{ pointer: NonNull:: {{ pointer: {0x1 as *const Never} is !null }}, _marker: PhantomData:: }}, std::alloc::Global); - _2 = copy ((_1.0: std::ptr::Unique).0: std::ptr::NonNull) as *const Never (BoxDerefTransmute); + _2 = copy (_1.0: std::ptr::Unique) as *const Never (BoxDerefTransmute); unreachable; } } diff --git a/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.32bit.panic-abort.diff b/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.32bit.panic-abort.diff index 8b5ad1519d27c..451d639ca2aa4 100644 --- a/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.32bit.panic-abort.diff +++ b/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.32bit.panic-abort.diff @@ -73,7 +73,7 @@ StorageDead(_2); StorageLive(_5); _10 = no_retag copy (*_1); - _11 = copy ((_10.0: std::ptr::Unique<()>).0: std::ptr::NonNull<()>) as *const () (BoxDerefTransmute); + _11 = copy (_10.0: std::ptr::Unique<()>) as *const () (BoxDerefTransmute); _5 = &raw const (*_11); StorageLive(_6); StorageLive(_7); diff --git a/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.32bit.panic-unwind.diff b/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.32bit.panic-unwind.diff index 14943534b98be..75b00c8885cd0 100644 --- a/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.32bit.panic-unwind.diff +++ b/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.32bit.panic-unwind.diff @@ -53,7 +53,7 @@ StorageDead(_2); StorageLive(_5); _10 = no_retag copy (*_1); - _11 = copy ((_10.0: std::ptr::Unique<()>).0: std::ptr::NonNull<()>) as *const () (BoxDerefTransmute); + _11 = copy (_10.0: std::ptr::Unique<()>) as *const () (BoxDerefTransmute); _5 = &raw const (*_11); StorageLive(_6); StorageLive(_7); diff --git a/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.64bit.panic-abort.diff b/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.64bit.panic-abort.diff index f8d47dcae5b27..3473ceb21a0ab 100644 --- a/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.64bit.panic-abort.diff +++ b/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.64bit.panic-abort.diff @@ -73,7 +73,7 @@ StorageDead(_2); StorageLive(_5); _10 = no_retag copy (*_1); - _11 = copy ((_10.0: std::ptr::Unique<()>).0: std::ptr::NonNull<()>) as *const () (BoxDerefTransmute); + _11 = copy (_10.0: std::ptr::Unique<()>) as *const () (BoxDerefTransmute); _5 = &raw const (*_11); StorageLive(_6); StorageLive(_7); diff --git a/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.64bit.panic-unwind.diff b/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.64bit.panic-unwind.diff index 14943534b98be..75b00c8885cd0 100644 --- a/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.64bit.panic-unwind.diff +++ b/tests/mir-opt/dont_reset_cast_kind_without_updating_operand.test.GVN.64bit.panic-unwind.diff @@ -53,7 +53,7 @@ StorageDead(_2); StorageLive(_5); _10 = no_retag copy (*_1); - _11 = copy ((_10.0: std::ptr::Unique<()>).0: std::ptr::NonNull<()>) as *const () (BoxDerefTransmute); + _11 = copy (_10.0: std::ptr::Unique<()>) as *const () (BoxDerefTransmute); _5 = &raw const (*_11); StorageLive(_6); StorageLive(_7); diff --git a/tests/mir-opt/inline/dont_ice_on_generic_rust_call.call.Inline.panic-abort.diff b/tests/mir-opt/inline/dont_ice_on_generic_rust_call.call.Inline.panic-abort.diff index ceacf606f3553..92060c211330e 100644 --- a/tests/mir-opt/inline/dont_ice_on_generic_rust_call.call.Inline.panic-abort.diff +++ b/tests/mir-opt/inline/dont_ice_on_generic_rust_call.call.Inline.panic-abort.diff @@ -10,7 +10,7 @@ + scope 1 (inlined > as FnMut>::call_mut) { + let mut _5: &mut dyn std::ops::FnMut; + let mut _6: *const dyn std::ops::FnMut; -+ let mut _7: std::ptr::NonNull>; ++ let mut _7: std::ptr::Unique>; + } bb0: { @@ -22,7 +22,7 @@ + StorageLive(_6); + StorageLive(_7); + StorageLive(_5); -+ _7 = no_retag copy (((*_3).0: std::ptr::Unique>).0: std::ptr::NonNull>); ++ _7 = no_retag copy ((*_3).0: std::ptr::Unique>); + _6 = copy _7 as *const dyn std::ops::FnMut (BoxDerefTransmute); + _5 = &mut (*_6); + _0 = as FnMut>::call_mut(move _5, move _4) -> [return: bb2, unwind unreachable]; diff --git a/tests/mir-opt/inline/dont_ice_on_generic_rust_call.call.Inline.panic-unwind.diff b/tests/mir-opt/inline/dont_ice_on_generic_rust_call.call.Inline.panic-unwind.diff index 862174fd94bff..085fa453ade13 100644 --- a/tests/mir-opt/inline/dont_ice_on_generic_rust_call.call.Inline.panic-unwind.diff +++ b/tests/mir-opt/inline/dont_ice_on_generic_rust_call.call.Inline.panic-unwind.diff @@ -10,7 +10,7 @@ + scope 1 (inlined > as FnMut>::call_mut) { + let mut _5: &mut dyn std::ops::FnMut; + let mut _6: *const dyn std::ops::FnMut; -+ let mut _7: std::ptr::NonNull>; ++ let mut _7: std::ptr::Unique>; + } bb0: { @@ -22,7 +22,7 @@ + StorageLive(_6); + StorageLive(_7); + StorageLive(_5); -+ _7 = no_retag copy (((*_3).0: std::ptr::Unique>).0: std::ptr::NonNull>); ++ _7 = no_retag copy ((*_3).0: std::ptr::Unique>); + _6 = copy _7 as *const dyn std::ops::FnMut (BoxDerefTransmute); + _5 = &mut (*_6); + _0 = as FnMut>::call_mut(move _5, move _4) -> [return: bb4, unwind: bb2]; diff --git a/tests/mir-opt/inline/inline_box_fn.call.Inline.panic-abort.diff b/tests/mir-opt/inline/inline_box_fn.call.Inline.panic-abort.diff index 0dc8adb257423..d04dc8f5ff5b2 100644 --- a/tests/mir-opt/inline/inline_box_fn.call.Inline.panic-abort.diff +++ b/tests/mir-opt/inline/inline_box_fn.call.Inline.panic-abort.diff @@ -10,7 +10,7 @@ + scope 1 (inlined as Fn<(i32,)>>::call) { + let mut _5: &dyn std::ops::Fn(i32); + let mut _6: *const dyn std::ops::Fn(i32); -+ let mut _7: std::ptr::NonNull; ++ let mut _7: std::ptr::Unique; + } bb0: { @@ -23,7 +23,7 @@ + StorageLive(_6); + StorageLive(_7); + StorageLive(_5); -+ _7 = no_retag copy (((*_3).0: std::ptr::Unique).0: std::ptr::NonNull); ++ _7 = no_retag copy ((*_3).0: std::ptr::Unique); + _6 = copy _7 as *const dyn std::ops::Fn(i32) (BoxDerefTransmute); + _5 = &(*_6); + _2 = >::call(move _5, move _4) -> [return: bb2, unwind unreachable]; diff --git a/tests/mir-opt/inline/inline_box_fn.call.Inline.panic-unwind.diff b/tests/mir-opt/inline/inline_box_fn.call.Inline.panic-unwind.diff index 1b320f9200405..f2fc8c7388f7d 100644 --- a/tests/mir-opt/inline/inline_box_fn.call.Inline.panic-unwind.diff +++ b/tests/mir-opt/inline/inline_box_fn.call.Inline.panic-unwind.diff @@ -10,7 +10,7 @@ + scope 1 (inlined as Fn<(i32,)>>::call) { + let mut _5: &dyn std::ops::Fn(i32); + let mut _6: *const dyn std::ops::Fn(i32); -+ let mut _7: std::ptr::NonNull; ++ let mut _7: std::ptr::Unique; + } bb0: { @@ -23,7 +23,7 @@ + StorageLive(_6); + StorageLive(_7); + StorageLive(_5); -+ _7 = no_retag copy (((*_3).0: std::ptr::Unique).0: std::ptr::NonNull); ++ _7 = no_retag copy ((*_3).0: std::ptr::Unique); + _6 = copy _7 as *const dyn std::ops::Fn(i32) (BoxDerefTransmute); + _5 = &(*_6); + _2 = >::call(move _5, move _4) -> [return: bb4, unwind: bb2]; diff --git a/tests/mir-opt/inline/issue_58867_inline_as_ref_as_mut.b.Inline.after.mir b/tests/mir-opt/inline/issue_58867_inline_as_ref_as_mut.b.Inline.after.mir index f4972c7d1437e..1d56fa0860654 100644 --- a/tests/mir-opt/inline/issue_58867_inline_as_ref_as_mut.b.Inline.after.mir +++ b/tests/mir-opt/inline/issue_58867_inline_as_ref_as_mut.b.Inline.after.mir @@ -9,7 +9,7 @@ fn b(_1: &mut Box) -> &mut T { scope 1 (inlined as AsMut>::as_mut) { debug self => _4; let mut _5: *const T; - let mut _6: std::ptr::NonNull; + let mut _6: std::ptr::Unique; } bb0: { @@ -19,7 +19,7 @@ fn b(_1: &mut Box) -> &mut T { _4 = no_retag copy _1; StorageLive(_5); StorageLive(_6); - _6 = no_retag copy (((*_4).0: std::ptr::Unique).0: std::ptr::NonNull); + _6 = no_retag copy ((*_4).0: std::ptr::Unique); _5 = copy _6 as *const T (BoxDerefTransmute); _3 = &mut (*_5); StorageDead(_6); diff --git a/tests/mir-opt/inline/issue_58867_inline_as_ref_as_mut.d.Inline.after.mir b/tests/mir-opt/inline/issue_58867_inline_as_ref_as_mut.d.Inline.after.mir index d5a0450af828e..a74065283737b 100644 --- a/tests/mir-opt/inline/issue_58867_inline_as_ref_as_mut.d.Inline.after.mir +++ b/tests/mir-opt/inline/issue_58867_inline_as_ref_as_mut.d.Inline.after.mir @@ -8,7 +8,7 @@ fn d(_1: &Box) -> &T { scope 1 (inlined as AsRef>::as_ref) { debug self => _3; let mut _4: *const T; - let mut _5: std::ptr::NonNull; + let mut _5: std::ptr::Unique; } bb0: { @@ -17,7 +17,7 @@ fn d(_1: &Box) -> &T { _3 = copy _1; StorageLive(_4); StorageLive(_5); - _5 = no_retag copy (((*_3).0: std::ptr::Unique).0: std::ptr::NonNull); + _5 = no_retag copy ((*_3).0: std::ptr::Unique); _4 = copy _5 as *const T (BoxDerefTransmute); _2 = &(*_4); StorageDead(_5); diff --git a/tests/mir-opt/inline/unsized_argument.caller.Inline.diff b/tests/mir-opt/inline/unsized_argument.caller.Inline.diff index 8ca4ca123c829..6865766499a6a 100644 --- a/tests/mir-opt/inline/unsized_argument.caller.Inline.diff +++ b/tests/mir-opt/inline/unsized_argument.caller.Inline.diff @@ -12,7 +12,7 @@ StorageLive(_2); StorageLive(_3); _3 = move _1; - _4 = copy ((_3.0: std::ptr::Unique<[i32]>).0: std::ptr::NonNull<[i32]>) as *const [i32] (BoxDerefTransmute); + _4 = copy (_3.0: std::ptr::Unique<[i32]>) as *const [i32] (BoxDerefTransmute); _2 = callee(move (*_4)) -> [return: bb1, unwind: bb3]; } diff --git a/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-abort.diff b/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-abort.diff index adf61031b3699..3a6a8e137aadc 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-abort.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-abort.diff @@ -17,7 +17,7 @@ } bb1: { - _2 = copy ((_1.0: std::ptr::Unique).0: std::ptr::NonNull) as *const Never (BoxDerefTransmute); + _2 = copy (_1.0: std::ptr::Unique) as *const Never (BoxDerefTransmute); PlaceMention((*_2)); unreachable; } diff --git a/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-unwind.diff b/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-unwind.diff index adf61031b3699..3a6a8e137aadc 100644 --- a/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-unwind.diff +++ b/tests/mir-opt/lower_intrinsics.transmute_to_box_uninhabited.LowerIntrinsics.panic-unwind.diff @@ -17,7 +17,7 @@ } bb1: { - _2 = copy ((_1.0: std::ptr::Unique).0: std::ptr::NonNull) as *const Never (BoxDerefTransmute); + _2 = copy (_1.0: std::ptr::Unique) as *const Never (BoxDerefTransmute); PlaceMention((*_2)); unreachable; } diff --git a/tests/run-make-cargo/cargo-issue-7359-load-panic/Cargo.toml b/tests/run-make-cargo/cargo-issue-7359-load-panic/Cargo.toml new file mode 100644 index 0000000000000..3ab3cf5353220 --- /dev/null +++ b/tests/run-make-cargo/cargo-issue-7359-load-panic/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "foo" +version = "0.1.0" +edition = "2024" + +[[bin]] +name = "foo" +path = "main.rs" + +[profile.release] +panic = "abort" diff --git a/tests/run-make-cargo/cargo-issue-7359-load-panic/main.rs b/tests/run-make-cargo/cargo-issue-7359-load-panic/main.rs new file mode 100644 index 0000000000000..f328e4d9d04c3 --- /dev/null +++ b/tests/run-make-cargo/cargo-issue-7359-load-panic/main.rs @@ -0,0 +1 @@ +fn main() {} diff --git a/tests/run-make-cargo/cargo-issue-7359-load-panic/rmake.rs b/tests/run-make-cargo/cargo-issue-7359-load-panic/rmake.rs new file mode 100644 index 0000000000000..670dff012331d --- /dev/null +++ b/tests/run-make-cargo/cargo-issue-7359-load-panic/rmake.rs @@ -0,0 +1,26 @@ +// This is a regression test to ensure that rustc doesn't load `panic_abort` +// from the sysroot. See rust-lang/cargo#7359 +// +//@ needs-target-std + +use run_make_support::{cargo, path, target}; + +fn main() { + let target_dir = path("target"); + + cargo() + .args(&[ + "build", + "--release", + "--manifest-path", + "Cargo.toml", + "-Zbuild-std=std", + "--target", + &target(), + ]) + .env("RUSTC_BOOTSTRAP", "1") + // Visual Studio 2022 requires that the LIB env var be set so it can + // find the Windows SDK. + .env("LIB", std::env::var("LIB").unwrap_or_default()) + .run(); +} diff --git a/tests/run-make/locate-panic-runtime/core.rs b/tests/run-make/locate-panic-runtime/core.rs new file mode 100644 index 0000000000000..ed65cbecc0560 --- /dev/null +++ b/tests/run-make/locate-panic-runtime/core.rs @@ -0,0 +1,21 @@ +// We are core. +#![feature(lang_items, no_core)] +#![allow(internal_features)] +#![no_std] +#![no_core] +#![crate_type = "rlib"] + +#[lang = "panic_info"] +pub struct PanicInfo {} + +#[lang = "copy"] +pub trait Copy: Sized {} + +#[lang = "pointee_sized"] +pub trait PointeeSized {} + +#[lang = "meta_sized"] +pub trait MetaSized: PointeeSized {} + +#[lang = "sized"] +pub trait Sized: MetaSized {} diff --git a/tests/run-make/locate-panic-runtime/lib.rs b/tests/run-make/locate-panic-runtime/lib.rs new file mode 100644 index 0000000000000..e85363beaf408 --- /dev/null +++ b/tests/run-make/locate-panic-runtime/lib.rs @@ -0,0 +1,11 @@ +#![feature(no_core)] +#![no_std] +#![no_core] +#![crate_type = "dylib"] + +extern crate std; + +#[panic_handler] +fn panic(_: &std::PanicInfo) -> ! { + loop {} +} diff --git a/tests/run-make/locate-panic-runtime/panic_abort.rs b/tests/run-make/locate-panic-runtime/panic_abort.rs new file mode 100644 index 0000000000000..f681b3386853a --- /dev/null +++ b/tests/run-make/locate-panic-runtime/panic_abort.rs @@ -0,0 +1,9 @@ +// We are panic runtime. +#![feature(panic_runtime, no_core)] +#![allow(internal_features)] +#![no_std] +#![no_core] +#![panic_runtime] +#![crate_type = "rlib"] + +extern crate core; diff --git a/tests/run-make/locate-panic-runtime/rmake.rs b/tests/run-make/locate-panic-runtime/rmake.rs new file mode 100644 index 0000000000000..3a53e4051b6cf --- /dev/null +++ b/tests/run-make/locate-panic-runtime/rmake.rs @@ -0,0 +1,66 @@ +// This test makes sure that the injected panic runtime can be loaded from +// `-L dependency=` paths as per RFC 3874 (build-std=always). +// +// Note: We have two possible panic runtime crates: the built one and the one from +// the sysroot. Sysroot lookup is disabled via the `--sysroot=` override to verify +// that we can load the correct one. +// +// `--emit=llvm-ir` is used to avoid running the linker. + +use run_make_support::{path, rfs, rust_lib_name, rustc}; + +fn main() { + rfs::create_dir("panic_abort"); + + // Compile `core`. + rustc().input("core.rs").panic("abort").sysroot("./no_exists").run(); + + // Compile `panic_abort` into a separate directory to prevent it from being + // found via `-L .` + rustc() + .input("panic_abort.rs") + .panic("abort") + .out_dir("panic_abort") + .sysroot("./no_exists") + .run(); + + // Compile `std`. + rustc() + .input("std.rs") + .extern_("panic_abort", &path("panic_abort").join(rust_lib_name("panic_abort"))) + .panic("abort") + .sysroot("./no_exists") + .run(); + + // Compile the final artifact. The panic runtime cannot be located without the + // `-Ldependency=` option. + rustc() + .input("lib.rs") + .arg("-Cpanic=abort") + .sysroot("./no_exists") + .emit("llvm-ir") + .run_fail() + .assert_stderr_contains("can't find crate for `panic_abort`"); + + // Compile the final artifact. The panic runtime cannot be located via + // `-Lcrate=` paths (This means that the panic runtime is not direct + // dependency). + rustc() + .input("lib.rs") + .arg("-Cpanic=abort") + .sysroot("./no_exists") + .library_search_path(format!("crate={}", path("panic_abort").display())) + .emit("llvm-ir") + .run_fail() + .assert_stderr_contains("can't find crate for `panic_abort`"); + + // Compile the final artifact. The panic runtime can be located via + // `-Ldependency=` paths. + rustc() + .input("lib.rs") + .arg("-Cpanic=abort") + .sysroot("./no_exists") + .library_search_path(format!("dependency={}", path("panic_abort").display())) + .emit("llvm-ir") + .run(); +} diff --git a/tests/run-make/locate-panic-runtime/std.rs b/tests/run-make/locate-panic-runtime/std.rs new file mode 100644 index 0000000000000..63eb75eca50a2 --- /dev/null +++ b/tests/run-make/locate-panic-runtime/std.rs @@ -0,0 +1,11 @@ +// We are std. +#![feature(needs_panic_runtime, no_core)] +#![allow(internal_features)] +#![no_std] +#![no_core] +// Tell rustc to inject panic runtime. +#![needs_panic_runtime] +#![crate_type = "rlib"] + +extern crate core; +pub use core::*; diff --git a/tests/run-make/rustdoc-filter-doc_cfg-doctest/foo.rs b/tests/run-make/rustdoc-filter-doc_cfg-doctest/foo.rs new file mode 100644 index 0000000000000..76f9f463f4f4d --- /dev/null +++ b/tests/run-make/rustdoc-filter-doc_cfg-doctest/foo.rs @@ -0,0 +1,15 @@ +#![feature(doc_cfg)] + +/// ``` +/// assert!(true); +/// ``` +#[doc(cfg(spec))] +fn f() {} + +#[doc(cfg(false))] +mod dummy { + /// ``` + /// assert!(true); + /// ``` + fn f2() {} +} diff --git a/tests/run-make/rustdoc-filter-doc_cfg-doctest/rmake.rs b/tests/run-make/rustdoc-filter-doc_cfg-doctest/rmake.rs new file mode 100644 index 0000000000000..942f23964f4d3 --- /dev/null +++ b/tests/run-make/rustdoc-filter-doc_cfg-doctest/rmake.rs @@ -0,0 +1,30 @@ +//! Regression test to ensure that `doc(cfg())` has no impact on the filtered-out doctests. +//! +//! Regression test for . + +//@ ignore-cross-compile + +use run_make_support::rustdoc; + +fn check_rustdoc_test_output(edition: &str) { + let out = rustdoc().input("foo.rs").edition(edition).arg("--test").run().stdout_utf8(); + + // There should be two tests run. + assert!(out.contains("running 2 test"), "Failed with edition {edition}"); + // They should be in `foo.rs`. + assert!(out.contains("test foo.rs - f (line 3) ... ok"), "Failed with edition {edition}"); + assert!( + out.contains("test foo.rs - dummy::f2 (line 11) ... ok"), + "Failed with edition {edition}" + ); + // We double-check that the test was run (successfully). + assert!( + out.contains("test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;"), + "Failed with edition {edition}", + ); +} + +fn main() { + check_rustdoc_test_output("2015"); + check_rustdoc_test_output("2024"); +} diff --git a/tests/rustdoc-ui/ice-clean-generic-args-133637.rs b/tests/rustdoc-ui/ice-clean-generic-args-133637.rs new file mode 100644 index 0000000000000..9b2b5d9dae4af --- /dev/null +++ b/tests/rustdoc-ui/ice-clean-generic-args-133637.rs @@ -0,0 +1,12 @@ +//@ check-pass +// https://github.com/rust-lang/rust/issues/133637 +#![crate_name="foo"] + +// Regression test for issue #133637. Previously we would index into the flattened generics list +// with the children generic indexes. This resulted in an ICE when debug assertions were on. + +trait Trait { + type Type<'a, 'b>; +} + +type Type = ::Type<'static, 'static>; diff --git a/tests/ui/associated-types/normalize-supertrait-projection-in-dyn-61083.rs b/tests/ui/associated-types/normalize-supertrait-projection-in-dyn-61083.rs new file mode 100644 index 0000000000000..fb93a97328bf4 --- /dev/null +++ b/tests/ui/associated-types/normalize-supertrait-projection-in-dyn-61083.rs @@ -0,0 +1,28 @@ +//! Regression test for . +//! +//! An associated type projection in a supertrait bound (`Bar: Foo`) +//! failed to normalize when the `Bar` bound was reached through a trait object, +//! so passing the object to a function expecting `Foo` was rejected. + +//@ revisions: current next +//@ ignore-compare-mode-next-solver (explicit revisions) +//@[next] compile-flags: -Znext-solver +//@ check-pass + +trait Foo {} + +trait Bar: Foo {} + +fn a(_x: &(impl Foo + ?Sized)) {} + +// The `dyn` form is the one that used to fail to normalize `T::Item` to `u32`. +fn b(y: &dyn Bar>) { + a(y) +} + +// The equivalent `impl Trait` form always compiled; keep it so both paths stay pinned. +fn c(y: &(impl Bar> + ?Sized)) { + a(y) +} + +fn main() {} diff --git a/tests/ui/attributes/rustc_confusables_std_cases.rs b/tests/ui/attributes/rustc_confusables_std_cases.rs index 4f6baea26dfd7..5e5b806d517b6 100644 --- a/tests/ui/attributes/rustc_confusables_std_cases.rs +++ b/tests/ui/attributes/rustc_confusables_std_cases.rs @@ -16,7 +16,6 @@ fn main() { //~^ HELP you might have meant to use `len` x.size(); //~ ERROR E0599 //~^ HELP you might have meant to use `len` - //~| HELP there is a method `resize` with a similar name x.append(42); //~ ERROR E0308 //~^ HELP you might have meant to use `push` String::new().push(""); //~ ERROR E0308 diff --git a/tests/ui/attributes/rustc_confusables_std_cases.stderr b/tests/ui/attributes/rustc_confusables_std_cases.stderr index f58950f3cc618..d9bf05d71f122 100644 --- a/tests/ui/attributes/rustc_confusables_std_cases.stderr +++ b/tests/ui/attributes/rustc_confusables_std_cases.stderr @@ -59,8 +59,6 @@ error[E0599]: no method named `size` found for struct `Vec<{integer}>` in the cu LL | x.size(); | ^^^^ | -help: there is a method `resize` with a similar name, but with different arguments - --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL help: you might have meant to use `len` | LL - x.size(); @@ -68,7 +66,7 @@ LL + x.len(); | error[E0308]: mismatched types - --> $DIR/rustc_confusables_std_cases.rs:20:14 + --> $DIR/rustc_confusables_std_cases.rs:19:14 | LL | x.append(42); | ------ ^^ expected `&mut Vec<{integer}>`, found integer @@ -86,7 +84,7 @@ LL + x.push(42); | error[E0308]: mismatched types - --> $DIR/rustc_confusables_std_cases.rs:22:24 + --> $DIR/rustc_confusables_std_cases.rs:21:24 | LL | String::new().push(""); | ---- ^^ expected `char`, found `&str` @@ -101,7 +99,7 @@ LL | String::new().push_str(""); | ++++ error[E0599]: no method named `append` found for struct `String` in the current scope - --> $DIR/rustc_confusables_std_cases.rs:24:19 + --> $DIR/rustc_confusables_std_cases.rs:23:19 | LL | String::new().append(""); | ^^^^^^ @@ -113,7 +111,7 @@ LL + String::new().push_str(""); | error[E0599]: no method named `get_line` found for struct `Stdin` in the current scope - --> $DIR/rustc_confusables_std_cases.rs:28:11 + --> $DIR/rustc_confusables_std_cases.rs:27:11 | LL | stdin.get_line(&mut buffer).unwrap(); | ^^^^^^^^ diff --git a/tests/ui/borrowck/const-fn-ptr-borrow-annotation.rs b/tests/ui/borrowck/const-fn-ptr-borrow-annotation.rs new file mode 100644 index 0000000000000..7d98d5a739797 --- /dev/null +++ b/tests/ui/borrowck/const-fn-ptr-borrow-annotation.rs @@ -0,0 +1,16 @@ +// Regression test for https://github.com/rust-lang/rust/issues/160255. + +use std::mem; + +const A: fn() = unsafe { + mem::transmute({ + fn fun() {} + let _ = fun as fn(); + { + let s = [0; 10]; + &s //~ ERROR: `s` does not live long enough [E0597] + } + }) +}; + +fn main() {} diff --git a/tests/ui/borrowck/const-fn-ptr-borrow-annotation.stderr b/tests/ui/borrowck/const-fn-ptr-borrow-annotation.stderr new file mode 100644 index 0000000000000..33ab95e4029b4 --- /dev/null +++ b/tests/ui/borrowck/const-fn-ptr-borrow-annotation.stderr @@ -0,0 +1,16 @@ +error[E0597]: `s` does not live long enough + --> $DIR/const-fn-ptr-borrow-annotation.rs:11:13 + | +LL | mem::transmute({ + | -------------- borrow later used by call +... +LL | let s = [0; 10]; + | - binding `s` declared here +LL | &s + | ^^ borrowed value does not live long enough +LL | } + | - `s` dropped here while still borrowed + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0597`. diff --git a/tests/ui/c-variadic/reject-varargs-without-pattern-post-expansion.rs b/tests/ui/c-variadic/reject-varargs-without-pattern-post-expansion.rs new file mode 100644 index 0000000000000..d68cf940290bf --- /dev/null +++ b/tests/ui/c-variadic/reject-varargs-without-pattern-post-expansion.rs @@ -0,0 +1,55 @@ +#![crate_type = "lib"] +#![warn(varargs_without_pattern)] + +// Test that we reject a bare `...` without a pattern post-expansion in function definitons and +// trait method declarations. On foreign function declarations it is allowed. +// +// We have the `varargs_without_pattern` FCW for this idiom, with the intent to eventually also +// reject this idiom pre-expansion. + +// Bare `...` is allowed in extern blocks. +extern "C" { + fn g(...); +} + +// When the `...` argument does not make it past expansion, that only lints. +macro_rules! discard_item { + ($item:item) => {}; +} + +discard_item! { + unsafe extern "C" fn f(...) -> i32 { + //~^ WARN missing pattern for `...` argument + //~| WARN this was previously accepted by the compiler but is being phased out + 0 + } +} + +// But when it does make it post-expansion, that is a hard error. +macro_rules! identity_item { + ($item:item) => { + $item + }; +} + +identity_item! { + unsafe extern "C" fn f(...) {} + //~^ ERROR missing pattern for `...` argument + //~| WARN missing pattern for `...` argument + //~| WARN this was previously accepted by the compiler but is being phased out + //~| WARN missing pattern for `...` argument + //~| WARN this was previously accepted by the compiler but is being phased out +} + +trait T { + identity_item! { + unsafe extern "C" fn f(...); + //~^ ERROR missing pattern for `...` argument + //~| WARN missing pattern for `...` argument + //~| WARN this was previously accepted by the compiler but is being phased out + //~| WARN missing pattern for `...` argument + //~| WARN this was previously accepted by the compiler but is being phased out + //~| WARN anonymous_parameters + //~| WARN this is accepted in the current edition (Rust 2015) + } +} diff --git a/tests/ui/c-variadic/reject-varargs-without-pattern-post-expansion.stderr b/tests/ui/c-variadic/reject-varargs-without-pattern-post-expansion.stderr new file mode 100644 index 0000000000000..f9243c97f2522 --- /dev/null +++ b/tests/ui/c-variadic/reject-varargs-without-pattern-post-expansion.stderr @@ -0,0 +1,191 @@ +error: missing pattern for `...` argument + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:36:28 + | +LL | unsafe extern "C" fn f(...) {} + | ^^^ help: add a pattern for this argument: `_: ...` + +error: missing pattern for `...` argument + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:46:32 + | +LL | unsafe extern "C" fn f(...); + | ^^^ help: add a pattern for this argument: `_: ...` + +warning: missing pattern for `...` argument + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:21:28 + | +LL | unsafe extern "C" fn f(...) -> i32 { + | ^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #145544 +note: the lint level is defined here + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:2:9 + | +LL | #![warn(varargs_without_pattern)] + | ^^^^^^^^^^^^^^^^^^^^^^^ +help: name the argument, or use `_` to continue ignoring it + | +LL | unsafe extern "C" fn f(_: ...) -> i32 { + | ++ + +warning: missing pattern for `...` argument + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:36:28 + | +LL | unsafe extern "C" fn f(...) {} + | ^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #145544 +help: name the argument, or use `_` to continue ignoring it + | +LL | unsafe extern "C" fn f(_: ...) {} + | ++ + +warning: missing pattern for `...` argument + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:36:28 + | +LL | unsafe extern "C" fn f(...) {} + | ^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #145544 + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +help: name the argument, or use `_` to continue ignoring it + | +LL | unsafe extern "C" fn f(_: ...) {} + | ++ + +warning: missing pattern for `...` argument + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:46:32 + | +LL | unsafe extern "C" fn f(...); + | ^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #145544 +help: name the argument, or use `_` to continue ignoring it + | +LL | unsafe extern "C" fn f(_: ...); + | ++ + +warning: missing pattern for `...` argument + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:46:32 + | +LL | unsafe extern "C" fn f(...); + | ^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #145544 + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +help: name the argument, or use `_` to continue ignoring it + | +LL | unsafe extern "C" fn f(_: ...); + | ++ + +warning: anonymous parameters are deprecated and will be removed in the next edition + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:46:32 + | +LL | unsafe extern "C" fn f(...); + | ^^^ help: try naming the parameter or explicitly ignoring it: `_: ...` + | + = warning: this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2018! + = note: for more information, see + = note: `#[warn(anonymous_parameters)]` (part of `#[warn(rust_2018_compatibility)]`) on by default + +error: aborting due to 2 previous errors; 6 warnings emitted + +Future incompatibility report: Future breakage diagnostic: +warning: missing pattern for `...` argument + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:21:28 + | +LL | unsafe extern "C" fn f(...) -> i32 { + | ^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #145544 +note: the lint level is defined here + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:2:9 + | +LL | #![warn(varargs_without_pattern)] + | ^^^^^^^^^^^^^^^^^^^^^^^ +help: name the argument, or use `_` to continue ignoring it + | +LL | unsafe extern "C" fn f(_: ...) -> i32 { + | ++ + +Future breakage diagnostic: +warning: missing pattern for `...` argument + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:36:28 + | +LL | unsafe extern "C" fn f(...) {} + | ^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #145544 +note: the lint level is defined here + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:2:9 + | +LL | #![warn(varargs_without_pattern)] + | ^^^^^^^^^^^^^^^^^^^^^^^ +help: name the argument, or use `_` to continue ignoring it + | +LL | unsafe extern "C" fn f(_: ...) {} + | ++ + +Future breakage diagnostic: +warning: missing pattern for `...` argument + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:36:28 + | +LL | unsafe extern "C" fn f(...) {} + | ^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #145544 +note: the lint level is defined here + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:2:9 + | +LL | #![warn(varargs_without_pattern)] + | ^^^^^^^^^^^^^^^^^^^^^^^ +help: name the argument, or use `_` to continue ignoring it + | +LL | unsafe extern "C" fn f(_: ...) {} + | ++ + +Future breakage diagnostic: +warning: missing pattern for `...` argument + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:46:32 + | +LL | unsafe extern "C" fn f(...); + | ^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #145544 +note: the lint level is defined here + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:2:9 + | +LL | #![warn(varargs_without_pattern)] + | ^^^^^^^^^^^^^^^^^^^^^^^ +help: name the argument, or use `_` to continue ignoring it + | +LL | unsafe extern "C" fn f(_: ...); + | ++ + +Future breakage diagnostic: +warning: missing pattern for `...` argument + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:46:32 + | +LL | unsafe extern "C" fn f(...); + | ^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #145544 +note: the lint level is defined here + --> $DIR/reject-varargs-without-pattern-post-expansion.rs:2:9 + | +LL | #![warn(varargs_without_pattern)] + | ^^^^^^^^^^^^^^^^^^^^^^^ +help: name the argument, or use `_` to continue ignoring it + | +LL | unsafe extern "C" fn f(_: ...); + | ++ + diff --git a/tests/ui/const-generics/generic_const_exprs/direct-inline-const-generic-default.rs b/tests/ui/const-generics/generic_const_exprs/direct-inline-const-generic-default.rs new file mode 100644 index 0000000000000..358d0d997cae8 --- /dev/null +++ b/tests/ui/const-generics/generic_const_exprs/direct-inline-const-generic-default.rs @@ -0,0 +1,10 @@ +//@ check-pass + +// Regression test for https://github.com/rust-lang/rust/issues/159063. + +#![feature(generic_const_exprs)] +#![feature(min_generic_const_args)] + +struct S; + +fn main() {} diff --git a/tests/ui/contracts/contract-clause-unused-parens-issue-143754.rs b/tests/ui/contracts/contract-clause-unused-parens-issue-143754.rs new file mode 100644 index 0000000000000..576d99665f124 --- /dev/null +++ b/tests/ui/contracts/contract-clause-unused-parens-issue-143754.rs @@ -0,0 +1,22 @@ +//@ check-pass +// Regression test for . +// The contract macros wrap the clause in braces rather than parentheses, so `unused_parens` +// must not fire on a contract attribute (and must not emit the attribute-eating suggestion). + +#![expect(incomplete_features)] +#![feature(contracts)] +#![deny(unused_parens)] + +#[core::contracts::requires(x.baz > 0)] +#[core::contracts::ensures(|ret| *ret > 100)] +fn nest(x: Baz) -> i32 { + loop { + return x.baz + 50; + } +} + +struct Baz { + baz: i32, +} + +fn main() {} diff --git a/tests/ui/eii/duplicate/both_decl_and_impl.rs b/tests/ui/eii/duplicate/both_decl_and_impl.rs new file mode 100644 index 0000000000000..a2fc571d3f497 --- /dev/null +++ b/tests/ui/eii/duplicate/both_decl_and_impl.rs @@ -0,0 +1,27 @@ +//@ ignore-backends: gcc +// FIXME(#125418): linking on Windows GNU targets is not yet supported. +//@ ignore-windows-gnu +// Tests that one item can't both define and impl an EII at the same time +#![feature(extern_item_impls)] + +#[eii] +fn a(x: u64); + +#[a] +#[eii] +//~^ ERROR a single item cannot both declare and implement EIIs +fn b(x: u64) {} + +#[eii] +fn c(x: u64); +//~^ ERROR `#[c]` function required, but not found + +#[eii] +#[c] +fn d(x: u64) {} +//~^ ERROR only a small subset of attributes are supported on externally implementable items + +fn main() { + a(42); + b(42); +} diff --git a/tests/ui/eii/duplicate/both_decl_and_impl.stderr b/tests/ui/eii/duplicate/both_decl_and_impl.stderr new file mode 100644 index 0000000000000..1cec485a90cff --- /dev/null +++ b/tests/ui/eii/duplicate/both_decl_and_impl.stderr @@ -0,0 +1,28 @@ +error: a single item cannot both declare and implement EIIs + --> $DIR/both_decl_and_impl.rs:11:1 + | +LL | #[eii] + | ^^^^^^ + +error: only a small subset of attributes are supported on externally implementable items + --> $DIR/both_decl_and_impl.rs:21:1 + | +LL | fn d(x: u64) {} + | ^^^^^^^^^^^^ + | +note: this attribute is not supported + --> $DIR/both_decl_and_impl.rs:20:1 + | +LL | #[c] + | ^^^^ + +error: `#[c]` function required, but not found + --> $DIR/both_decl_and_impl.rs:16:4 + | +LL | fn c(x: u64); + | ^ expected because `#[c]` was declared here in crate `both_decl_and_impl` + | + = help: expected at least one implementation in crate `both_decl_and_impl` or any of its dependencies + +error: aborting due to 3 previous errors + diff --git a/tests/ui/eii/duplicate/multiple_impls.rs b/tests/ui/eii/duplicate/multiple_impls.rs index 80f6147789743..3e541cb16b131 100644 --- a/tests/ui/eii/duplicate/multiple_impls.rs +++ b/tests/ui/eii/duplicate/multiple_impls.rs @@ -1,25 +1,37 @@ -//@ run-pass -//@ check-run-results //@ ignore-backends: gcc // FIXME(#125418): linking on Windows GNU targets is not yet supported. //@ ignore-windows-gnu -// Tests whether one function could implement two EIIs. +// Tests that one item can't implement two EIIs #![feature(extern_item_impls)] #[eii] fn a(x: u64); +//~^ ERROR `#[a]` function required, but not found #[eii] fn b(x: u64); #[a] #[b] +//~^ ERROR a single item cannot implement multiple EIIs fn implementation(x: u64) { println!("{x:?}") } -// what you would write: +#[eii(c)] +//~^ ERROR `#[c]` static required, but not found +static C: u64; + +#[eii(d)] +static D: u64; + +#[c] +#[d] +//~^ ERROR a single item cannot implement multiple EIIs +static IMPL: u64 = 5; + fn main() { a(42); b(42); + println!("{C} {D} {IMPL}") } diff --git a/tests/ui/eii/duplicate/multiple_impls.run.stdout b/tests/ui/eii/duplicate/multiple_impls.run.stdout deleted file mode 100644 index daaac9e303029..0000000000000 --- a/tests/ui/eii/duplicate/multiple_impls.run.stdout +++ /dev/null @@ -1,2 +0,0 @@ -42 -42 diff --git a/tests/ui/eii/duplicate/multiple_impls.stderr b/tests/ui/eii/duplicate/multiple_impls.stderr new file mode 100644 index 0000000000000..efeec635c859a --- /dev/null +++ b/tests/ui/eii/duplicate/multiple_impls.stderr @@ -0,0 +1,30 @@ +error: a single item cannot implement multiple EIIs + --> $DIR/multiple_impls.rs:15:1 + | +LL | #[b] + | ^^^^ + +error: a single item cannot implement multiple EIIs + --> $DIR/multiple_impls.rs:29:1 + | +LL | #[d] + | ^^^^ + +error: `#[a]` function required, but not found + --> $DIR/multiple_impls.rs:8:4 + | +LL | fn a(x: u64); + | ^ expected because `#[a]` was declared here in crate `multiple_impls` + | + = help: expected at least one implementation in crate `multiple_impls` or any of its dependencies + +error: `#[c]` static required, but not found + --> $DIR/multiple_impls.rs:21:7 + | +LL | #[eii(c)] + | ^ expected because `#[c]` was declared here in crate `multiple_impls` + | + = help: expected at least one implementation in crate `multiple_impls` or any of its dependencies + +error: aborting due to 4 previous errors + diff --git a/tests/ui/eii/static/multiple_impls.rs b/tests/ui/eii/static/multiple_impls.rs deleted file mode 100644 index 1129417b958ca..0000000000000 --- a/tests/ui/eii/static/multiple_impls.rs +++ /dev/null @@ -1,20 +0,0 @@ -//@ ignore-backends: gcc -// FIXME(#125418): linking on Windows GNU targets is not yet supported. -//@ ignore-windows-gnu -// Tests whether one function could implement two EIIs. -#![feature(extern_item_impls)] - -#[eii(a)] -static A: u64; - -#[eii(b)] -static B: u64; - -#[a] -#[b] -//~^ ERROR static cannot implement multiple EIIs -static IMPL: u64 = 5; - -fn main() { - println!("{A} {B} {IMPL}") -} diff --git a/tests/ui/eii/static/multiple_impls.run.stdout b/tests/ui/eii/static/multiple_impls.run.stdout deleted file mode 100644 index 58945c2b48291..0000000000000 --- a/tests/ui/eii/static/multiple_impls.run.stdout +++ /dev/null @@ -1 +0,0 @@ -5 5 5 diff --git a/tests/ui/eii/static/multiple_impls.stderr b/tests/ui/eii/static/multiple_impls.stderr deleted file mode 100644 index b31331f2483f1..0000000000000 --- a/tests/ui/eii/static/multiple_impls.stderr +++ /dev/null @@ -1,10 +0,0 @@ -error: static cannot implement multiple EIIs - --> $DIR/multiple_impls.rs:14:1 - | -LL | #[b] - | ^^^^ - | - = note: this is not allowed because multiple externally implementable statics that alias may be unintuitive - -error: aborting due to 1 previous error - diff --git a/tests/ui/macros/derive-of-trait.rs b/tests/ui/macros/derive-of-trait.rs new file mode 100644 index 0000000000000..ebabb01f3d587 --- /dev/null +++ b/tests/ui/macros/derive-of-trait.rs @@ -0,0 +1,32 @@ +//@ compile-flags: -Z deduplicate-diagnostics=yes + +// Trait used as a derive target should point at the trait definition and +// suggest a manual implementation — both when the trait is already in scope +// (via import or local definition) and when it is only importable. + +mod inner { + pub trait MyTrait {} //~ NOTE `MyTrait` is a trait, not a derive macro + pub trait OuterTrait {} //~ NOTE `OuterTrait` is a trait, not a derive macro +} + +use inner::MyTrait; + +trait LocalTrait {} +//~^ NOTE `LocalTrait` is a trait, not a derive macro + +// in-scope: locally defined +#[derive(LocalTrait)] +//~^ ERROR cannot find derive macro `LocalTrait` in this scope +struct A; + +// in-scope: imported +#[derive(MyTrait)] +//~^ ERROR cannot find derive macro `MyTrait` in this scope +struct B; + +// out-of-scope: importable but not imported +#[derive(OuterTrait)] +//~^ ERROR cannot find derive macro `OuterTrait` in this scope +struct C; + +fn main() {} diff --git a/tests/ui/macros/derive-of-trait.stderr b/tests/ui/macros/derive-of-trait.stderr new file mode 100644 index 0000000000000..6e40f13d9645f --- /dev/null +++ b/tests/ui/macros/derive-of-trait.stderr @@ -0,0 +1,41 @@ +error: cannot find derive macro `OuterTrait` in this scope + --> $DIR/derive-of-trait.rs:28:10 + | +LL | #[derive(OuterTrait)] + | ^^^^^^^^^^ + | +note: `OuterTrait` is a trait, not a derive macro + --> $DIR/derive-of-trait.rs:9:5 + | +LL | pub trait OuterTrait {} + | ^^^^^^^^^^^^^^^^^^^^^^^ + = help: consider implementing `OuterTrait` for your type manually + +error: cannot find derive macro `MyTrait` in this scope + --> $DIR/derive-of-trait.rs:23:10 + | +LL | #[derive(MyTrait)] + | ^^^^^^^ + | +note: `MyTrait` is a trait, not a derive macro + --> $DIR/derive-of-trait.rs:8:5 + | +LL | pub trait MyTrait {} + | ^^^^^^^^^^^^^^^^^^^^ + = help: consider implementing `MyTrait` for your type manually + +error: cannot find derive macro `LocalTrait` in this scope + --> $DIR/derive-of-trait.rs:18:10 + | +LL | #[derive(LocalTrait)] + | ^^^^^^^^^^ + | +note: `LocalTrait` is a trait, not a derive macro + --> $DIR/derive-of-trait.rs:14:1 + | +LL | trait LocalTrait {} + | ^^^^^^^^^^^^^^^^^^^ + = help: consider implementing `LocalTrait` for your type manually + +error: aborting due to 3 previous errors + diff --git a/tests/ui/macros/issue-88206.rs b/tests/ui/macros/issue-88206.rs index abf58fdcbc815..b78a2d48e0b62 100644 --- a/tests/ui/macros/issue-88206.rs +++ b/tests/ui/macros/issue-88206.rs @@ -8,15 +8,14 @@ use std::str::*; //~| NOTE `from_utf8_unchecked` is imported here, but it is a function mod hey { - pub trait Serialize {} + pub trait Serialize {} //~ NOTE `Serialize` is a trait, not a derive macro pub trait Deserialize {} pub struct X(i32); } use hey::{Serialize, Deserialize, X}; -//~^ NOTE `Serialize` is imported here, but it is only a trait, without a derive macro -//~| NOTE `Deserialize` is imported here, but it is a trait +//~^ NOTE `Deserialize` is imported here, but it is a trait //~| NOTE `X` is imported here, but it is a struct #[derive(Serialize)] diff --git a/tests/ui/macros/issue-88206.stderr b/tests/ui/macros/issue-88206.stderr index f7f5b56488007..93be644650f20 100644 --- a/tests/ui/macros/issue-88206.stderr +++ b/tests/ui/macros/issue-88206.stderr @@ -1,5 +1,5 @@ error: cannot find macro `X` in this scope - --> $DIR/issue-88206.rs:64:5 + --> $DIR/issue-88206.rs:63:5 | LL | X!(); | ^ @@ -11,7 +11,7 @@ LL | use hey::{Serialize, Deserialize, X}; | ^ error: cannot find macro `test` in this scope - --> $DIR/issue-88206.rs:60:5 + --> $DIR/issue-88206.rs:59:5 | LL | test!(); | ^^^^ @@ -19,7 +19,7 @@ LL | test!(); = note: `test` is in scope, but it is an attribute: `#[test]` error: cannot find macro `Copy` in this scope - --> $DIR/issue-88206.rs:56:5 + --> $DIR/issue-88206.rs:55:5 | LL | Copy!(); | ^^^^ @@ -27,7 +27,7 @@ LL | Copy!(); = note: `Copy` is in scope, but it is a derive macro: `#[derive(Copy)]` error: cannot find macro `Box` in this scope - --> $DIR/issue-88206.rs:52:5 + --> $DIR/issue-88206.rs:51:5 | LL | Box!(); | ^^^ @@ -35,7 +35,7 @@ LL | Box!(); = note: `Box` is in scope, but it is a struct, not a macro error: cannot find macro `from_utf8` in this scope - --> $DIR/issue-88206.rs:49:5 + --> $DIR/issue-88206.rs:48:5 | LL | from_utf8!(); | ^^^^^^^^^ @@ -47,7 +47,7 @@ LL | use std::str::*; | ^^^^^^^^^^^ error: cannot find attribute `println` in this scope - --> $DIR/issue-88206.rs:43:3 + --> $DIR/issue-88206.rs:42:3 | LL | #[println] | ^^^^^^^ @@ -55,7 +55,7 @@ LL | #[println] = note: `println` is in scope, but it is a function-like macro error: cannot find attribute `from_utf8_unchecked` in this scope - --> $DIR/issue-88206.rs:39:3 + --> $DIR/issue-88206.rs:38:3 | LL | #[from_utf8_unchecked] | ^^^^^^^^^^^^^^^^^^^ @@ -67,7 +67,7 @@ LL | use std::str::*; | ^^^^^^^^^^^ error: cannot find attribute `Deserialize` in this scope - --> $DIR/issue-88206.rs:35:3 + --> $DIR/issue-88206.rs:34:3 | LL | #[Deserialize] | ^^^^^^^^^^^ @@ -79,7 +79,7 @@ LL | use hey::{Serialize, Deserialize, X}; | ^^^^^^^^^^^ error: cannot find derive macro `println` in this scope - --> $DIR/issue-88206.rs:30:10 + --> $DIR/issue-88206.rs:29:10 | LL | #[derive(println)] | ^^^^^^^ @@ -87,7 +87,7 @@ LL | #[derive(println)] = note: `println` is in scope, but it is a function-like macro error: cannot find derive macro `from_utf8_mut` in this scope - --> $DIR/issue-88206.rs:26:10 + --> $DIR/issue-88206.rs:25:10 | LL | #[derive(from_utf8_mut)] | ^^^^^^^^^^^^^ @@ -99,16 +99,17 @@ LL | use std::str::*; | ^^^^^^^^^^^ error: cannot find derive macro `Serialize` in this scope - --> $DIR/issue-88206.rs:22:10 + --> $DIR/issue-88206.rs:21:10 | LL | #[derive(Serialize)] | ^^^^^^^^^ | -note: `Serialize` is imported here, but it is only a trait, without a derive macro - --> $DIR/issue-88206.rs:17:11 +note: `Serialize` is a trait, not a derive macro + --> $DIR/issue-88206.rs:11:5 | -LL | use hey::{Serialize, Deserialize, X}; - | ^^^^^^^^^ +LL | pub trait Serialize {} + | ^^^^^^^^^^^^^^^^^^^^^^ + = help: consider implementing `Serialize` for your type manually error: aborting due to 11 previous errors diff --git a/tests/ui/macros/issue-88228.rs b/tests/ui/macros/issue-88228.rs index b4195a92557ed..e58a90d08cdda 100644 --- a/tests/ui/macros/issue-88228.rs +++ b/tests/ui/macros/issue-88228.rs @@ -9,6 +9,8 @@ mod hey { //~ HELP consider importing this derive macro #[derive(Bla)] //~^ ERROR cannot find derive macro `Bla` +//~| NOTE `Bla` is a trait, not a derive macro +//~| HELP consider implementing `Bla` for your type manually struct A; #[derive(println)] diff --git a/tests/ui/macros/issue-88228.stderr b/tests/ui/macros/issue-88228.stderr index f9d0ac95da756..164af4e07bddf 100644 --- a/tests/ui/macros/issue-88228.stderr +++ b/tests/ui/macros/issue-88228.stderr @@ -1,5 +1,5 @@ error: cannot find macro `bla` in this scope - --> $DIR/issue-88228.rs:20:5 + --> $DIR/issue-88228.rs:22:5 | LL | bla!(); | ^^^ @@ -10,7 +10,7 @@ LL + use crate::hey::bla; | error: cannot find derive macro `println` in this scope - --> $DIR/issue-88228.rs:14:10 + --> $DIR/issue-88228.rs:16:10 | LL | #[derive(println)] | ^^^^^^^ @@ -23,6 +23,9 @@ error: cannot find derive macro `Bla` in this scope LL | #[derive(Bla)] | ^^^ | +note: `Bla` is a trait, not a derive macro + --> $SRC_DIR/core/src/marker.rs:LL:COL + = help: consider implementing `Bla` for your type manually help: consider importing this derive macro through its public re-export | LL + use crate::hey::Bla; diff --git a/tests/ui/suggestions/suggest-exact-alias-before-similar-name.rs b/tests/ui/suggestions/suggest-exact-alias-before-similar-name.rs new file mode 100644 index 0000000000000..6478a1c328ef4 --- /dev/null +++ b/tests/ui/suggestions/suggest-exact-alias-before-similar-name.rs @@ -0,0 +1,15 @@ +struct Reader; +//~^ NOTE method `read_exact_buf` not found for this struct + +impl Reader { + fn read_exact(&self) {} + + #[doc(alias("read_exact_buf"))] + fn read_buf_exact(&self) {} +} + +fn main() { + Reader.read_exact_buf(); + //~^ ERROR no method named `read_exact_buf` found for struct `Reader` in the current scope + //~^^ HELP there is a method `read_buf_exact` with a similar name +} diff --git a/tests/ui/suggestions/suggest-exact-alias-before-similar-name.stderr b/tests/ui/suggestions/suggest-exact-alias-before-similar-name.stderr new file mode 100644 index 0000000000000..ba18e84a78868 --- /dev/null +++ b/tests/ui/suggestions/suggest-exact-alias-before-similar-name.stderr @@ -0,0 +1,18 @@ +error[E0599]: no method named `read_exact_buf` found for struct `Reader` in the current scope + --> $DIR/suggest-exact-alias-before-similar-name.rs:12:12 + | +LL | struct Reader; + | ------------- method `read_exact_buf` not found for this struct +... +LL | Reader.read_exact_buf(); + | ^^^^^^^^^^^^^^ + | +help: there is a method `read_buf_exact` with a similar name + | +LL - Reader.read_exact_buf(); +LL + Reader.read_buf_exact(); + | + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0599`. diff --git a/tests/ui/thir-print/c-variadic.rs b/tests/ui/thir-print/c-variadic.rs index b07c422ea3cd4..2dbf2d5179190 100644 --- a/tests/ui/thir-print/c-variadic.rs +++ b/tests/ui/thir-print/c-variadic.rs @@ -1,6 +1,4 @@ //@ compile-flags: -Zunpretty=thir-tree --crate-type=lib //@ check-pass -#![expect(varargs_without_pattern)] -// The `...` argument uses `PatKind::Missing`. -unsafe extern "C" fn foo(_: i32, ...) {} +unsafe extern "C" fn foo(_: i32, _: ...) {} diff --git a/tests/ui/thir-print/c-variadic.stderr b/tests/ui/thir-print/c-variadic.stderr deleted file mode 100644 index e05e50a93f57d..0000000000000 --- a/tests/ui/thir-print/c-variadic.stderr +++ /dev/null @@ -1,12 +0,0 @@ -Future incompatibility report: Future breakage diagnostic: -warning: missing pattern for `...` argument - --> $DIR/c-variadic.rs:6:34 - | -LL | unsafe extern "C" fn foo(_: i32, ...) {} - | ^^^ - | -help: name the argument, or use `_` to continue ignoring it - | -LL | unsafe extern "C" fn foo(_: i32, _: ...) {} - | ++ - diff --git a/tests/ui/thir-print/c-variadic.stdout b/tests/ui/thir-print/c-variadic.stdout index ad6dacb4753b3..466825e4dc116 100644 --- a/tests/ui/thir-print/c-variadic.stdout +++ b/tests/ui/thir-print/c-variadic.stdout @@ -2,13 +2,13 @@ DefId(0:3 ~ c_variadic[a5de]::foo): params: [ Param { ty: i32 - ty_span: Some($DIR/c-variadic.rs:6:29: 6:32 (#0)) + ty_span: Some($DIR/c-variadic.rs:4:29: 4:32 (#0)) self_kind: None hir_id: Some(HirId(DefId(0:3 ~ c_variadic[a5de]::foo).1)) param: Some( Pat { ty: i32 - span: $DIR/c-variadic.rs:6:26: 6:27 (#0) + span: $DIR/c-variadic.rs:4:26: 4:27 (#0) kind: PatKind { Wild } @@ -23,9 +23,9 @@ params: [ param: Some( Pat { ty: std::ffi::VaList<'{erased}> - span: $DIR/c-variadic.rs:6:34: 6:37 (#0) + span: $DIR/c-variadic.rs:4:34: 4:35 (#0) kind: PatKind { - Missing + Wild } } ) @@ -35,7 +35,7 @@ body: Expr { ty: () temp_scope_id: 6 - span: $DIR/c-variadic.rs:6:39: 6:41 (#0) + span: $DIR/c-variadic.rs:4:42: 4:44 (#0) kind: Scope { region_scope: Node(6) @@ -44,11 +44,11 @@ body: Expr { ty: () temp_scope_id: 6 - span: $DIR/c-variadic.rs:6:39: 6:41 (#0) + span: $DIR/c-variadic.rs:4:42: 4:44 (#0) kind: Block { targeted_by_break: false - span: $DIR/c-variadic.rs:6:39: 6:41 (#0) + span: $DIR/c-variadic.rs:4:42: 4:44 (#0) region_scope: Node(5) safety_mode: Safe stmts: []