diff --git a/compiler/rustc_builtin_macros/src/autodiff.rs b/compiler/rustc_builtin_macros/src/autodiff.rs index da53a770cdc1a..2704496b0fbaf 100644 --- a/compiler/rustc_builtin_macros/src/autodiff.rs +++ b/compiler/rustc_builtin_macros/src/autodiff.rs @@ -1,838 +1,826 @@ //! This module contains the implementation of the `#[autodiff]` attribute. //! Currently our linter isn't smart enough to see that each import is used in one of the two //! configs (autodiff enabled or disabled), so we have to add cfg's to each import. -//! FIXME(ZuseZ4): Remove this once we have a smarter linter. -mod llvm_enzyme { - use std::str::FromStr; - use std::string::String; - - use rustc_ast::expand::autodiff_attrs::{ - DiffActivity, DiffMode, valid_input_activity, valid_ret_activity, valid_ty_for_activity, - }; - use rustc_ast::token::{IdentKind, Lit, LitKind, Token, TokenKind}; - use rustc_ast::tokenstream::*; - use rustc_ast::visit::AssocCtxt::*; - use rustc_ast::{ - self as ast, FnRetTy, FnSig, GenericParamKind, Generics, ItemKind, MetaItemInner, PatKind, - TyKind, Visibility, - }; - use rustc_attr_ir::RustcAutodiff; - use rustc_expand::base::{Annotatable, ExtCtxt}; - use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym}; - use thin_vec::{ThinVec, thin_vec}; - use tracing::{debug, trace}; - - use crate::diagnostics; - use crate::util::generic_param_to_arg; - - pub(crate) fn outer_normal_attr( - kind: &Box, - id: rustc_ast::AttrId, - span: Span, - ) -> rustc_ast::Attribute { - let style = rustc_ast::AttrStyle::Outer; - let kind = rustc_ast::AttrKind::Normal(kind.clone()); - rustc_ast::Attribute { kind, id, style, span } - } +use std::str::FromStr; +use std::string::String; + +use rustc_ast::expand::autodiff_attrs::{ + DiffActivity, DiffMode, valid_input_activity, valid_ret_activity, valid_ty_for_activity, +}; +use rustc_ast::token::{IdentKind, Lit, LitKind, Token, TokenKind}; +use rustc_ast::tokenstream::*; +use rustc_ast::visit::AssocCtxt::*; +use rustc_ast::{ + self as ast, FnRetTy, FnSig, GenericParamKind, Generics, ItemKind, MetaItemInner, PatKind, + TyKind, Visibility, +}; +use rustc_attr_ir::RustcAutodiff; +use rustc_expand::base::{Annotatable, ExtCtxt}; +use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym}; +use thin_vec::{ThinVec, thin_vec}; +use tracing::{debug, trace}; + +use crate::diagnostics; +use crate::util::generic_param_to_arg; + +fn outer_normal_attr( + kind: &Box, + id: rustc_ast::AttrId, + span: Span, +) -> rustc_ast::Attribute { + let style = rustc_ast::AttrStyle::Outer; + let kind = rustc_ast::AttrKind::Normal(kind.clone()); + rustc_ast::Attribute { kind, id, style, span } +} - // If we have a default `()` return type or explicitley `()` return type, - // then we often can skip doing some work. - fn has_ret(ty: &FnRetTy) -> bool { - match ty { - FnRetTy::Ty(ty) => !ty.kind.is_unit(), - FnRetTy::Default(_) => false, - } +// If we have a default `()` return type or explicitley `()` return type, +// then we often can skip doing some work. +fn has_ret(ty: &FnRetTy) -> bool { + match ty { + FnRetTy::Ty(ty) => !ty.kind.is_unit(), + FnRetTy::Default(_) => false, } - fn first_ident(x: &MetaItemInner) -> rustc_span::Ident { - if let Some(l) = x.lit() { - match l.kind { - ast::LitKind::Int(val, _) => { - // get an Ident from a lit - return rustc_span::Ident::from_str(val.get().to_string().as_str()); - } - _ => {} +} +fn first_ident(x: &MetaItemInner) -> rustc_span::Ident { + if let Some(l) = x.lit() { + match l.kind { + ast::LitKind::Int(val, _) => { + // get an Ident from a lit + return rustc_span::Ident::from_str(val.get().to_string().as_str()); } + _ => {} } - - let segments = &x.meta_item().unwrap().path.segments; - assert!(segments.len() == 1); - segments[0].ident } - fn name(x: &MetaItemInner) -> String { - first_ident(x).name.to_string() + let segments = &x.meta_item().unwrap().path.segments; + assert!(segments.len() == 1); + segments[0].ident +} + +fn name(x: &MetaItemInner) -> String { + first_ident(x).name.to_string() +} + +fn width(x: &MetaItemInner) -> Option { + let lit = x.lit()?; + match lit.kind { + ast::LitKind::Int(x, _) => Some(x.get()), + _ => None, } +} - fn width(x: &MetaItemInner) -> Option { - let lit = x.lit()?; - match lit.kind { - ast::LitKind::Int(x, _) => Some(x.get()), - _ => None, +// Get information about the function the macro is applied to +fn extract_item_info(iitem: &Box) -> Option<(Visibility, FnSig, Ident, Generics)> { + match &iitem.kind { + ItemKind::Fn(ast::Fn { sig, ident, generics, .. }) => { + Some((iitem.vis.clone(), sig.clone(), *ident, generics.clone())) } + _ => None, } +} - // Get information about the function the macro is applied to - fn extract_item_info(iitem: &Box) -> Option<(Visibility, FnSig, Ident, Generics)> { - match &iitem.kind { - ItemKind::Fn(ast::Fn { sig, ident, generics, .. }) => { - Some((iitem.vis.clone(), sig.clone(), *ident, generics.clone())) +fn from_ast( + ecx: &mut ExtCtxt<'_>, + meta_item: &ThinVec, + has_ret: bool, + mode: DiffMode, +) -> RustcAutodiff { + let dcx = ecx.sess.dcx(); + + // Now we check, whether the user wants autodiff in batch/vector mode, or scalar mode. + // If he doesn't specify an integer (=width), we default to scalar mode, thus width=1. + let mut first_activity = 1; + + let width = if let [_, x, ..] = &meta_item[..] + && let Some(x) = width(x) + { + first_activity = 2; + match x.try_into() { + Ok(x) => x, + Err(_) => { + dcx.emit_err(diagnostics::AutoDiffInvalidWidth { + span: meta_item[1].span(), + width: x, + }); + return RustcAutodiff::error(); } - _ => None, } - } + } else { + 1 + }; - pub(crate) fn from_ast( - ecx: &mut ExtCtxt<'_>, - meta_item: &ThinVec, - has_ret: bool, - mode: DiffMode, - ) -> RustcAutodiff { - let dcx = ecx.sess.dcx(); - - // Now we check, whether the user wants autodiff in batch/vector mode, or scalar mode. - // If he doesn't specify an integer (=width), we default to scalar mode, thus width=1. - let mut first_activity = 1; - - let width = if let [_, x, ..] = &meta_item[..] - && let Some(x) = width(x) - { - first_activity = 2; - match x.try_into() { - Ok(x) => x, - Err(_) => { - dcx.emit_err(diagnostics::AutoDiffInvalidWidth { - span: meta_item[1].span(), - width: x, - }); - return RustcAutodiff::error(); - } + let mut activities: Vec = vec![]; + let mut errors = false; + for x in &meta_item[first_activity..] { + let activity_str = name(x); + let res = DiffActivity::from_str(&activity_str); + match res { + Ok(x) => activities.push(x), + Err(_) => { + dcx.emit_err(diagnostics::AutoDiffUnknownActivity { + span: x.span(), + act: activity_str, + }); + errors = true; } - } else { - 1 }; + } + if errors { + return RustcAutodiff::error(); + } - let mut activities: Vec = vec![]; - let mut errors = false; - for x in &meta_item[first_activity..] { - let activity_str = name(x); - let res = DiffActivity::from_str(&activity_str); - match res { - Ok(x) => activities.push(x), - Err(_) => { - dcx.emit_err(diagnostics::AutoDiffUnknownActivity { - span: x.span(), - act: activity_str, - }); - errors = true; - } - }; - } - if errors { - return RustcAutodiff::error(); - } - - // If a return type exist, we need to split the last activity, - // otherwise we return None as placeholder. - let (ret_activity, input_activity) = if has_ret { - let Some((last, rest)) = activities.split_last() else { - unreachable!( - "should not be reachable because we counted the number of activities previously" - ); - }; - (last, rest) - } else { - (&DiffActivity::None, activities.as_slice()) + // If a return type exist, we need to split the last activity, + // otherwise we return None as placeholder. + let (ret_activity, input_activity) = if has_ret { + let Some((last, rest)) = activities.split_last() else { + unreachable!( + "should not be reachable because we counted the number of activities previously" + ); }; + (last, rest) + } else { + (&DiffActivity::None, activities.as_slice()) + }; - RustcAutodiff { - mode, - width, - ret_activity: *ret_activity, - input_activity: input_activity.iter().cloned().collect(), - } + RustcAutodiff { + mode, + width, + ret_activity: *ret_activity, + input_activity: input_activity.iter().cloned().collect(), } +} - fn meta_item_inner_to_ts(t: &MetaItemInner, ts: &mut Vec) { - let comma = Token::new(TokenKind::Comma, Span::default()); - let val = first_ident(t); - let t = Token::from_ast_ident(val); - ts.push(TokenTree::Token(t, Spacing::Joint)); - ts.push(TokenTree::Token(comma, Spacing::Alone)); - } +fn meta_item_inner_to_ts(t: &MetaItemInner, ts: &mut Vec) { + let comma = Token::new(TokenKind::Comma, Span::default()); + let val = first_ident(t); + let t = Token::from_ast_ident(val); + ts.push(TokenTree::Token(t, Spacing::Joint)); + ts.push(TokenTree::Token(comma, Spacing::Alone)); +} - pub(crate) fn expand_forward( - ecx: &mut ExtCtxt<'_>, - expand_span: Span, - meta_item: &ast::MetaItem, - item: Annotatable, - ) -> Vec { - expand_with_mode(ecx, expand_span, meta_item, item, DiffMode::Forward) - } +pub(crate) fn expand_forward( + ecx: &mut ExtCtxt<'_>, + expand_span: Span, + meta_item: &ast::MetaItem, + item: Annotatable, +) -> Vec { + expand_with_mode(ecx, expand_span, meta_item, item, DiffMode::Forward) +} - pub(crate) fn expand_reverse( - ecx: &mut ExtCtxt<'_>, - expand_span: Span, - meta_item: &ast::MetaItem, - item: Annotatable, - ) -> Vec { - expand_with_mode(ecx, expand_span, meta_item, item, DiffMode::Reverse) - } +pub(crate) fn expand_reverse( + ecx: &mut ExtCtxt<'_>, + expand_span: Span, + meta_item: &ast::MetaItem, + item: Annotatable, +) -> Vec { + expand_with_mode(ecx, expand_span, meta_item, item, DiffMode::Reverse) +} - /// We expand the autodiff macro to generate a new placeholder function which passes - /// type-checking and can be called by users. The exact signature of the generated function - /// depends on the configuration provided by the user, but here is an example: - /// - /// ``` - /// #[autodiff(cos_box, Reverse, Duplicated, Active)] - /// fn sin(x: &Box) -> f32 { - /// f32::sin(**x) - /// } - /// ``` - /// which becomes expanded to: - /// ``` - /// #[rustc_autodiff] - /// fn sin(x: &Box) -> f32 { - /// f32::sin(**x) - /// } - /// #[rustc_autodiff(Reverse, Duplicated, Active)] - /// fn cos_box(x: &Box, dx: &mut Box, dret: f32) -> f32 { - /// std::intrinsics::autodiff(sin::<> as fn(..) -> .., cos_box::<>, (x, dx, dret)) - /// } - /// ``` - /// FIXME(ZuseZ4): Once autodiff is enabled by default, make this a doc comment which is checked - /// in CI. - pub(crate) fn expand_with_mode( - ecx: &mut ExtCtxt<'_>, - expand_span: Span, - meta_item: &ast::MetaItem, - mut item: Annotatable, - mode: DiffMode, - ) -> Vec { - let dcx = ecx.sess.dcx(); - - // first get information about the annotable item: visibility, signature, name and generic - // parameters. - // these will be used to generate the differentiated version of the function - let Some((vis, sig, primal, generics, is_impl)) = (match &item { - Annotatable::Item(iitem) => { +/// We expand the autodiff macro to generate a new placeholder function which passes +/// type-checking and can be called by users. The exact signature of the generated function +/// depends on the configuration provided by the user, but here is an example: +/// +/// ``` +/// #[autodiff(cos_box, Reverse, Duplicated, Active)] +/// fn sin(x: &Box) -> f32 { +/// f32::sin(**x) +/// } +/// ``` +/// which becomes expanded to: +/// ``` +/// #[rustc_autodiff] +/// fn sin(x: &Box) -> f32 { +/// f32::sin(**x) +/// } +/// #[rustc_autodiff(Reverse, Duplicated, Active)] +/// fn cos_box(x: &Box, dx: &mut Box, dret: f32) -> f32 { +/// std::intrinsics::autodiff(sin::<> as fn(..) -> .., cos_box::<>, (x, dx, dret)) +/// } +/// ``` +/// FIXME(ZuseZ4): Once autodiff is enabled by default, make this a doc comment which is checked +/// in CI. +fn expand_with_mode( + ecx: &mut ExtCtxt<'_>, + expand_span: Span, + meta_item: &ast::MetaItem, + mut item: Annotatable, + mode: DiffMode, +) -> Vec { + let dcx = ecx.sess.dcx(); + + // first get information about the annotable item: visibility, signature, name and generic + // parameters. + // these will be used to generate the differentiated version of the function + let Some((vis, sig, primal, generics, is_impl)) = (match &item { + Annotatable::Item(iitem) => { + extract_item_info(iitem).map(|(v, s, p, g)| (v, s, p, g, false)) + } + Annotatable::Stmt(stmt) => match &stmt.kind { + ast::StmtKind::Item(iitem) => { extract_item_info(iitem).map(|(v, s, p, g)| (v, s, p, g, false)) } - Annotatable::Stmt(stmt) => match &stmt.kind { - ast::StmtKind::Item(iitem) => { - extract_item_info(iitem).map(|(v, s, p, g)| (v, s, p, g, false)) + _ => None, + }, + Annotatable::AssocItem(assoc_item, _ctxt @ (Impl { of_trait: _ } | Trait)) => { + match &assoc_item.kind { + ast::AssocItemKind::Fn(ast::Fn { sig, ident, generics, .. }) => { + Some((assoc_item.vis.clone(), sig.clone(), *ident, generics.clone(), true)) } _ => None, - }, - Annotatable::AssocItem(assoc_item, _ctxt @ (Impl { of_trait: _ } | Trait)) => { - match &assoc_item.kind { - ast::AssocItemKind::Fn(ast::Fn { sig, ident, generics, .. }) => { - Some((assoc_item.vis.clone(), sig.clone(), *ident, generics.clone(), true)) - } - _ => None, - } - } - _ => None, - }) else { - dcx.emit_err(diagnostics::AutoDiffInvalidApplication { span: item.span() }); - return vec![item]; - }; - - let meta_item_vec: ThinVec = match meta_item.kind { - ast::MetaItemKind::List(ref vec) => vec.clone(), - _ => { - dcx.emit_err(diagnostics::AutoDiffMissingConfig { span: item.span() }); - return vec![item]; } - }; - - let has_ret = has_ret(&sig.decl.output); + } + _ => None, + }) else { + dcx.emit_err(diagnostics::AutoDiffInvalidApplication { span: item.span() }); + return vec![item]; + }; - // create TokenStream from vec elemtents: - // meta_item doesn't have a .tokens field - let mut ts: Vec = vec![]; - if meta_item_vec.is_empty() { - // At the bare minimum, we need a fnc name. + let meta_item_vec: ThinVec = match meta_item.kind { + ast::MetaItemKind::List(ref vec) => vec.clone(), + _ => { dcx.emit_err(diagnostics::AutoDiffMissingConfig { span: item.span() }); return vec![item]; } + }; - let mode_symbol = match mode { - DiffMode::Forward => sym::Forward, - DiffMode::Reverse => sym::Reverse, - _ => unreachable!("Unsupported mode: {:?}", mode), - }; + let has_ret = has_ret(&sig.decl.output); - // Insert mode token - let mode_token = - Token::new(TokenKind::Ident(mode_symbol, IdentKind::Normal), Span::default()); - ts.insert(0, TokenTree::Token(mode_token, Spacing::Joint)); - ts.insert( - 1, - TokenTree::Token(Token::new(TokenKind::Comma, Span::default()), Spacing::Alone), - ); - - // Now, if the user gave a width (vector aka batch-mode ad), then we copy it. - // If it is not given, we default to 1 (scalar mode). - let start_position; - let kind = LitKind::Integer; - let symbol; - if meta_item_vec.len() >= 2 - && let Some(width) = width(&meta_item_vec[1]) - { - start_position = 2; - symbol = Symbol::intern(&width.to_string()); - } else { - start_position = 1; - symbol = sym::integer(1); - } + // create TokenStream from vec elemtents: + // meta_item doesn't have a .tokens field + let mut ts: Vec = vec![]; + if meta_item_vec.is_empty() { + // At the bare minimum, we need a fnc name. + dcx.emit_err(diagnostics::AutoDiffMissingConfig { span: item.span() }); + return vec![item]; + } - let l = Lit { kind, symbol, suffix: None }; - let t = Token::new(TokenKind::Literal(l), Span::default()); - let comma = Token::new(TokenKind::Comma, Span::default()); - ts.push(TokenTree::Token(t, Spacing::Joint)); - ts.push(TokenTree::Token(comma, Spacing::Alone)); + let mode_symbol = match mode { + DiffMode::Forward => sym::Forward, + DiffMode::Reverse => sym::Reverse, + _ => unreachable!("Unsupported mode: {:?}", mode), + }; - for t in meta_item_vec.clone()[start_position..].iter() { - meta_item_inner_to_ts(t, &mut ts); - } + // Insert mode token + let mode_token = Token::new(TokenKind::Ident(mode_symbol, IdentKind::Normal), Span::default()); + ts.insert(0, TokenTree::Token(mode_token, Spacing::Joint)); + ts.insert(1, TokenTree::Token(Token::new(TokenKind::Comma, Span::default()), Spacing::Alone)); + + // Now, if the user gave a width (vector aka batch-mode ad), then we copy it. + // If it is not given, we default to 1 (scalar mode). + let start_position; + let kind = LitKind::Integer; + let symbol; + if meta_item_vec.len() >= 2 + && let Some(width) = width(&meta_item_vec[1]) + { + start_position = 2; + symbol = Symbol::intern(&width.to_string()); + } else { + start_position = 1; + symbol = sym::integer(1); + } - if !has_ret { - // We don't want users to provide a return activity if the function doesn't return anything. - // For simplicity, we just add a dummy token to the end of the list. - let t = Token::new(TokenKind::Ident(sym::None, IdentKind::Normal), Span::default()); - ts.push(TokenTree::Token(t, Spacing::Joint)); - ts.push(TokenTree::Token(comma, Spacing::Alone)); - } - // We remove the last, trailing comma. - ts.pop(); - let ts = TokenStream::from_iter(ts); - - let x = from_ast(ecx, &meta_item_vec, has_ret, mode); - if !x.is_active() { - // We encountered an error, so we return the original item. - // This allows us to potentially parse other attributes. - return vec![item]; - } - let span = ecx.with_def_site_ctxt(expand_span); + let l = Lit { kind, symbol, suffix: None }; + let t = Token::new(TokenKind::Literal(l), Span::default()); + let comma = Token::new(TokenKind::Comma, Span::default()); + ts.push(TokenTree::Token(t, Spacing::Joint)); + ts.push(TokenTree::Token(comma, Spacing::Alone)); + + for t in meta_item_vec.clone()[start_position..].iter() { + meta_item_inner_to_ts(t, &mut ts); + } + + if !has_ret { + // We don't want users to provide a return activity if the function doesn't return anything. + // For simplicity, we just add a dummy token to the end of the list. + let t = Token::new(TokenKind::Ident(sym::None, IdentKind::Normal), Span::default()); + ts.push(TokenTree::Token(t, Spacing::Joint)); + ts.push(TokenTree::Token(comma, Spacing::Alone)); + } + // We remove the last, trailing comma. + ts.pop(); + let ts = TokenStream::from_iter(ts); + + let x = from_ast(ecx, &meta_item_vec, has_ret, mode); + if !x.is_active() { + // We encountered an error, so we return the original item. + // This allows us to potentially parse other attributes. + return vec![item]; + } + let span = ecx.with_def_site_ctxt(expand_span); - let d_sig = gen_enzyme_decl(ecx, &sig, &x, span); + let d_sig = gen_enzyme_decl(ecx, &sig, &x, span); - let d_body = ecx.block( + let d_body = ecx.block( + span, + thin_vec![call_autodiff( + ecx, + primal, + first_ident(&meta_item_vec[0]), span, - thin_vec![call_autodiff( - ecx, - primal, - first_ident(&meta_item_vec[0]), - span, - &sig, - &d_sig, - &generics, - is_impl, - )], - ); - - // The first element of it is the name of the function to be generated - let d_fn = ecx.item_fn(d_sig, first_ident(&meta_item_vec[0]), generics, Some(d_body)); - let mut rustc_ad_attr = - Box::new(ast::NormalAttr::from_ident(Ident::with_dummy_span(sym::rustc_autodiff))); - - let ts2 = vec![TokenTree::Token( - Token::new(TokenKind::Ident(sym::never, IdentKind::Normal), span), - Spacing::Joint, - )]; - let never_arg = ast::DelimArgs { - dspan: DelimSpan::from_single(span), - delim: ast::token::Delimiter::Parenthesis, - tokens: TokenStream::from_iter(ts2), - }; - let inline_item = ast::AttrItem { - unsafety: ast::Safety::Default, - path: ast::Path::from_ident(Ident::with_dummy_span(sym::inline)), - args: ast::AttrArgs::Delimited(never_arg), - span: DUMMY_SP, - }; - let inline_never_attr = Box::new(ast::NormalAttr { item: inline_item, tokens: None }); - let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id(); - let attr = outer_normal_attr(&rustc_ad_attr, new_id, span); - let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id(); - let inline_never = outer_normal_attr(&inline_never_attr, new_id, span); - - // We're avoid duplicating the attribute `#[rustc_autodiff]`. - fn same_attribute(attr: &ast::AttrKind, item: &ast::AttrKind) -> bool { - match (attr, item) { - (ast::AttrKind::Normal(a), ast::AttrKind::Normal(b)) => { - let a = &a.item.path; - let b = &b.item.path; - a.segments.iter().eq_by(&b.segments, |a, b| a.ident == b.ident) - } - _ => false, + &sig, + &d_sig, + &generics, + is_impl, + )], + ); + + // The first element of it is the name of the function to be generated + let d_fn = ecx.item_fn(d_sig, first_ident(&meta_item_vec[0]), generics, Some(d_body)); + let mut rustc_ad_attr = + Box::new(ast::NormalAttr::from_ident(Ident::with_dummy_span(sym::rustc_autodiff))); + + let ts2 = vec![TokenTree::Token( + Token::new(TokenKind::Ident(sym::never, IdentKind::Normal), span), + Spacing::Joint, + )]; + let never_arg = ast::DelimArgs { + dspan: DelimSpan::from_single(span), + delim: ast::token::Delimiter::Parenthesis, + tokens: TokenStream::from_iter(ts2), + }; + let inline_item = ast::AttrItem { + unsafety: ast::Safety::Default, + path: ast::Path::from_ident(Ident::with_dummy_span(sym::inline)), + args: ast::AttrArgs::Delimited(never_arg), + span: DUMMY_SP, + }; + let inline_never_attr = Box::new(ast::NormalAttr { item: inline_item, tokens: None }); + let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id(); + let attr = outer_normal_attr(&rustc_ad_attr, new_id, span); + let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id(); + let inline_never = outer_normal_attr(&inline_never_attr, new_id, span); + + // We're avoid duplicating the attribute `#[rustc_autodiff]`. + fn same_attribute(attr: &ast::AttrKind, item: &ast::AttrKind) -> bool { + match (attr, item) { + (ast::AttrKind::Normal(a), ast::AttrKind::Normal(b)) => { + let a = &a.item.path; + let b = &b.item.path; + a.segments.iter().eq_by(&b.segments, |a, b| a.ident == b.ident) } + _ => false, } + } - let mut has_inline_never = false; + let mut has_inline_never = false; - // Don't add it multiple times: - let orig_annotatable = match item { - Annotatable::Item(ref mut iitem) => { - if !iitem.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) { - iitem.attrs.push(attr); - } - if iitem.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) { - has_inline_never = true; - } - Annotatable::Item(iitem.clone()) + // Don't add it multiple times: + let orig_annotatable = match item { + Annotatable::Item(ref mut iitem) => { + if !iitem.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) { + iitem.attrs.push(attr); } - Annotatable::AssocItem(ref mut assoc_item, ctxt @ (Impl { .. } | Trait)) => { - if !assoc_item.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) { - assoc_item.attrs.push(attr); - } - if assoc_item.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) { - has_inline_never = true; - } - Annotatable::AssocItem(assoc_item.clone(), ctxt) + if iitem.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) { + has_inline_never = true; } - Annotatable::Stmt(ref mut stmt) => { - match stmt.kind { - ast::StmtKind::Item(ref mut iitem) => { - if !iitem.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) { - iitem.attrs.push(attr); - } - if iitem.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) { - has_inline_never = true; - } - } - _ => unreachable!("stmt kind checked previously"), - }; - - Annotatable::Stmt(stmt.clone()) + Annotatable::Item(iitem.clone()) + } + Annotatable::AssocItem(ref mut assoc_item, ctxt @ (Impl { .. } | Trait)) => { + if !assoc_item.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) { + assoc_item.attrs.push(attr); } - _ => { - unreachable!("annotatable kind checked previously") + if assoc_item.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) { + has_inline_never = true; } - }; - // Now update for d_fn - rustc_ad_attr.item.args = rustc_ast::AttrArgs::Delimited(rustc_ast::DelimArgs { - dspan: DelimSpan::dummy(), - delim: rustc_ast::token::Delimiter::Parenthesis, - tokens: ts, - }); - - let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id(); - let d_attr = outer_normal_attr(&rustc_ad_attr, new_id, span); - - // If the source function has the `#[inline(never)]` attribute, we'll also add it to the diff function - let mut d_attrs = thin_vec![d_attr]; + Annotatable::AssocItem(assoc_item.clone(), ctxt) + } + Annotatable::Stmt(ref mut stmt) => { + match stmt.kind { + ast::StmtKind::Item(ref mut iitem) => { + if !iitem.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) { + iitem.attrs.push(attr); + } + if iitem.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) { + has_inline_never = true; + } + } + _ => unreachable!("stmt kind checked previously"), + }; - if has_inline_never { - d_attrs.push(inline_never); + Annotatable::Stmt(stmt.clone()) } + _ => { + unreachable!("annotatable kind checked previously") + } + }; + // Now update for d_fn + rustc_ad_attr.item.args = rustc_ast::AttrArgs::Delimited(rustc_ast::DelimArgs { + dspan: DelimSpan::dummy(), + delim: rustc_ast::token::Delimiter::Parenthesis, + tokens: ts, + }); - let d_annotatable = match &item { - Annotatable::AssocItem(_, ctxt) => { - let assoc_item = ast::AssocItemKind::Fn(d_fn); - let d_fn = Box::new(ast::AssocItem { - attrs: d_attrs, - id: ast::DUMMY_NODE_ID, - span, - vis, - kind: assoc_item, - tokens: None, - }); - Annotatable::AssocItem(d_fn, *ctxt) - } - Annotatable::Item(_) => { - let mut d_fn = ecx.item(span, d_attrs, ItemKind::Fn(d_fn)); - d_fn.vis = vis; + let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id(); + let d_attr = outer_normal_attr(&rustc_ad_attr, new_id, span); - Annotatable::Item(d_fn) - } - Annotatable::Stmt(_) => { - let mut d_fn = ecx.item(span, d_attrs, ItemKind::Fn(d_fn)); - d_fn.vis = vis; - Annotatable::Stmt(ecx.stmt_item(span, d_fn)) - } - _ => { - unreachable!("item kind checked previously") - } - }; + // If the source function has the `#[inline(never)]` attribute, we'll also add it to the diff function + let mut d_attrs = thin_vec![d_attr]; - vec![orig_annotatable, d_annotatable] + if has_inline_never { + d_attrs.push(inline_never); } - // shadow arguments (the extra ones which were not in the original (primal) function), in reverse mode must be - // mutable references or ptrs, because Enzyme will write into them. - fn assure_mut_ref(ty: &ast::Ty) -> ast::Ty { - let mut ty = ty.clone(); - match ty.kind { - TyKind::Ptr(_, ref mut mutbl) => { - *mutbl = ast::Mutability::Mut; - } - TyKind::Ref(_, _, ref mut mutbl) => { - *mutbl = ast::Mutability::Mut; - } - _ => { - panic!("unsupported type: {:?}", ty); - } + let d_annotatable = match &item { + Annotatable::AssocItem(_, ctxt) => { + let assoc_item = ast::AssocItemKind::Fn(d_fn); + let d_fn = Box::new(ast::AssocItem { + attrs: d_attrs, + id: ast::DUMMY_NODE_ID, + span, + vis, + kind: assoc_item, + tokens: None, + }); + Annotatable::AssocItem(d_fn, *ctxt) + } + Annotatable::Item(_) => { + let mut d_fn = ecx.item(span, d_attrs, ItemKind::Fn(d_fn)); + d_fn.vis = vis; + + Annotatable::Item(d_fn) + } + Annotatable::Stmt(_) => { + let mut d_fn = ecx.item(span, d_attrs, ItemKind::Fn(d_fn)); + d_fn.vis = vis; + Annotatable::Stmt(ecx.stmt_item(span, d_fn)) + } + _ => { + unreachable!("item kind checked previously") + } + }; + + vec![orig_annotatable, d_annotatable] +} + +// shadow arguments (the extra ones which were not in the original (primal) function), in reverse mode must be +// mutable references or ptrs, because Enzyme will write into them. +fn assure_mut_ref(ty: &ast::Ty) -> ast::Ty { + let mut ty = ty.clone(); + match ty.kind { + TyKind::Ptr(_, ref mut mutbl) => { + *mutbl = ast::Mutability::Mut; + } + TyKind::Ref(_, _, ref mut mutbl) => { + *mutbl = ast::Mutability::Mut; + } + _ => { + panic!("unsupported type: {:?}", ty); } - ty } + ty +} - // Generate `autodiff` intrinsic call - // ``` - // std::intrinsics::autodiff(source as fn(..) -> .., diff, (args)) - // ``` - fn call_autodiff( - ecx: &ExtCtxt<'_>, - primal: Ident, - diff: Ident, - span: Span, - p_sig: &FnSig, - d_sig: &FnSig, - generics: &Generics, - is_impl: bool, - ) -> rustc_ast::Stmt { - let primal_path_expr = gen_turbofish_expr(ecx, primal, generics, span, is_impl); - - let self_ty = || ecx.ty_self(DUMMY_SP); - let fn_ptr_params: ThinVec = p_sig +// Generate `autodiff` intrinsic call +// ``` +// std::intrinsics::autodiff(source as fn(..) -> .., diff, (args)) +// ``` +fn call_autodiff( + ecx: &ExtCtxt<'_>, + primal: Ident, + diff: Ident, + span: Span, + p_sig: &FnSig, + d_sig: &FnSig, + generics: &Generics, + is_impl: bool, +) -> rustc_ast::Stmt { + let primal_path_expr = gen_turbofish_expr(ecx, primal, generics, span, is_impl); + + let self_ty = || ecx.ty_self(DUMMY_SP); + let fn_ptr_params: ThinVec = p_sig + .decl + .inputs + .iter() + .map(|param| { + let ty = match ¶m.ty.kind { + TyKind::ImplicitSelf => self_ty(), + TyKind::Ref(lt, inner_ty, mutbl) + if matches!(inner_ty.kind, TyKind::ImplicitSelf) => + { + ecx.ty(span, TyKind::Ref(*lt, self_ty(), *mutbl)) + } + TyKind::Ptr(inner_ty, mutbl) if matches!(inner_ty.kind, TyKind::ImplicitSelf) => { + ecx.ty(span, TyKind::Ptr(self_ty(), *mutbl)) + } + _ => param.ty.clone(), + }; + ast::Param { + attrs: ast::AttrVec::new(), + ty, + pat: Box::new(ecx.pat_wild(span)), + id: ast::DUMMY_NODE_ID, + span, + is_placeholder: false, + has_const_keyword: false, + } + }) + .collect(); + let fn_ptr_ty = ecx.ty( + span, + TyKind::FnPtr(Box::new(ast::FnPtrTy { + safety: p_sig.header.safety, + ext: p_sig.header.ext, + generic_params: ThinVec::new(), + decl: Box::new(ast::FnDecl { + inputs: fn_ptr_params, + output: p_sig.decl.output.clone(), + }), + decl_span: span, + })), + ); + let primal_fn_ptr = ecx.expr(span, ast::ExprKind::Cast(primal_path_expr, fn_ptr_ty)); + + let diff_path_expr = gen_turbofish_expr(ecx, diff, generics, span, is_impl); + + let tuple_expr = ecx.expr_tuple( + span, + d_sig .decl .inputs .iter() - .map(|param| { - let ty = match ¶m.ty.kind { - TyKind::ImplicitSelf => self_ty(), - TyKind::Ref(lt, inner_ty, mutbl) - if matches!(inner_ty.kind, TyKind::ImplicitSelf) => - { - ecx.ty(span, TyKind::Ref(*lt, self_ty(), *mutbl)) - } - TyKind::Ptr(inner_ty, mutbl) - if matches!(inner_ty.kind, TyKind::ImplicitSelf) => - { - ecx.ty(span, TyKind::Ptr(self_ty(), *mutbl)) - } - _ => param.ty.clone(), - }; - ast::Param { - attrs: ast::AttrVec::new(), - ty, - pat: Box::new(ecx.pat_wild(span)), - id: ast::DUMMY_NODE_ID, - span, - is_placeholder: false, - has_const_keyword: false, - } + .map(|arg| match arg.pat.kind { + PatKind::Ident(_, ident, _) => ecx.expr_path(ecx.path_ident(span, ident)), + _ => unimplemented!(), }) - .collect(); - let fn_ptr_ty = ecx.ty( - span, - TyKind::FnPtr(Box::new(ast::FnPtrTy { - safety: p_sig.header.safety, - ext: p_sig.header.ext, - generic_params: ThinVec::new(), - decl: Box::new(ast::FnDecl { - inputs: fn_ptr_params, - output: p_sig.decl.output.clone(), - }), - decl_span: span, - })), - ); - let primal_fn_ptr = ecx.expr(span, ast::ExprKind::Cast(primal_path_expr, fn_ptr_ty)); - - let diff_path_expr = gen_turbofish_expr(ecx, diff, generics, span, is_impl); - - let tuple_expr = ecx.expr_tuple( - span, - d_sig - .decl - .inputs - .iter() - .map(|arg| match arg.pat.kind { - PatKind::Ident(_, ident, _) => ecx.expr_path(ecx.path_ident(span, ident)), - _ => unimplemented!(), - }) - .collect::>(), - ); - - let call_expr = ecx.expr_call_intrinsic( - span, - sym::autodiff, - thin_vec![primal_fn_ptr, diff_path_expr, tuple_expr], - ); + .collect::>(), + ); - ecx.stmt_expr(call_expr) - } + let call_expr = ecx.expr_call_intrinsic( + span, + sym::autodiff, + thin_vec![primal_fn_ptr, diff_path_expr, tuple_expr], + ); - // Generate turbofish expression from fn name and generics - // Given `foo` and `` params, gen `foo::` - // We use this expression when passing primal and diff function to the autodiff intrinsic - fn gen_turbofish_expr( - ecx: &ExtCtxt<'_>, - ident: Ident, - generics: &Generics, - span: Span, - is_impl: bool, - ) -> Box { - let generic_args = generics - .params - .iter() - .filter_map(|p| match &p.kind { - GenericParamKind::Lifetime => None, - _ => Some(generic_param_to_arg(ecx, p, span)), - }) - .collect::>(); + ecx.stmt_expr(call_expr) +} - let idents = if is_impl { &[Ident::new(kw::SelfUpper, span), ident][..] } else { &[ident] }; - let path = ecx.path_all(span, idents, generic_args); +// Generate turbofish expression from fn name and generics +// Given `foo` and `` params, gen `foo::` +// We use this expression when passing primal and diff function to the autodiff intrinsic +fn gen_turbofish_expr( + ecx: &ExtCtxt<'_>, + ident: Ident, + generics: &Generics, + span: Span, + is_impl: bool, +) -> Box { + let generic_args = generics + .params + .iter() + .filter_map(|p| match &p.kind { + GenericParamKind::Lifetime => None, + _ => Some(generic_param_to_arg(ecx, p, span)), + }) + .collect::>(); + + let idents = if is_impl { &[Ident::new(kw::SelfUpper, span), ident][..] } else { &[ident] }; + let path = ecx.path_all(span, idents, generic_args); + + ecx.expr_path(path) +} - ecx.expr_path(path) +// Generate the new function declaration. Const arguments are kept as is. Duplicated arguments must +// be pointers or references. Those receive a shadow argument, which is a mutable reference/pointer. +// Active arguments must be scalars. Their shadow argument is added to the return type (and will be +// zero-initialized by Enzyme). +// Each argument of the primal function (and the return type if existing) must be annotated with an +// activity. +// +// Error handling: If the user provides an invalid configuration (incorrect numbers, types, or +// both), we emit an error and return the original signature. This allows us to continue parsing. +// FIXME(Sa4dUs): make individual activities' span available so errors +// can point to only the activity instead of the entire attribute +fn gen_enzyme_decl( + ecx: &ExtCtxt<'_>, + sig: &ast::FnSig, + x: &RustcAutodiff, + span: Span, +) -> ast::FnSig { + let dcx = ecx.sess.dcx(); + let has_ret = has_ret(&sig.decl.output); + let sig_args = sig.decl.inputs.len() + if has_ret { 1 } else { 0 }; + let num_activities = x.input_activity.len() + if x.has_ret_activity() { 1 } else { 0 }; + if sig_args != num_activities { + dcx.emit_err(diagnostics::AutoDiffInvalidNumberActivities { + span, + expected: sig_args, + found: num_activities, + }); + // This is not the right signature, but we can continue parsing. + return sig.clone(); } - - // Generate the new function declaration. Const arguments are kept as is. Duplicated arguments must - // be pointers or references. Those receive a shadow argument, which is a mutable reference/pointer. - // Active arguments must be scalars. Their shadow argument is added to the return type (and will be - // zero-initialized by Enzyme). - // Each argument of the primal function (and the return type if existing) must be annotated with an - // activity. - // - // Error handling: If the user provides an invalid configuration (incorrect numbers, types, or - // both), we emit an error and return the original signature. This allows us to continue parsing. - // FIXME(Sa4dUs): make individual activities' span available so errors - // can point to only the activity instead of the entire attribute - fn gen_enzyme_decl( - ecx: &ExtCtxt<'_>, - sig: &ast::FnSig, - x: &RustcAutodiff, - span: Span, - ) -> ast::FnSig { - let dcx = ecx.sess.dcx(); - let has_ret = has_ret(&sig.decl.output); - let sig_args = sig.decl.inputs.len() + if has_ret { 1 } else { 0 }; - let num_activities = x.input_activity.len() + if x.has_ret_activity() { 1 } else { 0 }; - if sig_args != num_activities { - dcx.emit_err(diagnostics::AutoDiffInvalidNumberActivities { + assert!(sig.decl.inputs.len() == x.input_activity.len()); + assert!(has_ret == x.has_ret_activity()); + let mut d_decl = sig.decl.clone(); + let mut d_inputs = ThinVec::new(); + let mut act_ret = ThinVec::new(); + + // We have two loops, a first one just to check the activities and types and possibly report + // multiple errors in one compilation session. + let mut errors = false; + for (arg, activity) in sig.decl.inputs.iter().zip(x.input_activity.iter()) { + if !valid_input_activity(x.mode, *activity) { + dcx.emit_err(diagnostics::AutoDiffInvalidApplicationModeAct { span, - expected: sig_args, - found: num_activities, + mode: x.mode.to_string(), + act: activity.to_string(), }); - // This is not the right signature, but we can continue parsing. - return sig.clone(); - } - assert!(sig.decl.inputs.len() == x.input_activity.len()); - assert!(has_ret == x.has_ret_activity()); - let mut d_decl = sig.decl.clone(); - let mut d_inputs = ThinVec::new(); - let mut act_ret = ThinVec::new(); - - // We have two loops, a first one just to check the activities and types and possibly report - // multiple errors in one compilation session. - let mut errors = false; - for (arg, activity) in sig.decl.inputs.iter().zip(x.input_activity.iter()) { - if !valid_input_activity(x.mode, *activity) { - dcx.emit_err(diagnostics::AutoDiffInvalidApplicationModeAct { - span, - mode: x.mode.to_string(), - act: activity.to_string(), - }); - errors = true; - } - if !valid_ty_for_activity(&arg.ty, *activity) { - dcx.emit_err(diagnostics::AutoDiffInvalidTypeForActivity { - span: arg.ty.span, - act: activity.to_string(), - }); - errors = true; - } + errors = true; } - - if has_ret && !valid_ret_activity(x.mode, x.ret_activity) { - dcx.emit_err(diagnostics::AutoDiffInvalidRetAct { - span, - mode: x.mode.to_string(), - act: x.ret_activity.to_string(), + if !valid_ty_for_activity(&arg.ty, *activity) { + dcx.emit_err(diagnostics::AutoDiffInvalidTypeForActivity { + span: arg.ty.span, + act: activity.to_string(), }); - // We don't set `errors = true` to avoid annoying type errors relative - // to the expanded macro type signature + errors = true; } + } - if errors { - // This is not the right signature, but we can continue parsing. - return sig.clone(); - } + if has_ret && !valid_ret_activity(x.mode, x.ret_activity) { + dcx.emit_err(diagnostics::AutoDiffInvalidRetAct { + span, + mode: x.mode.to_string(), + act: x.ret_activity.to_string(), + }); + // We don't set `errors = true` to avoid annoying type errors relative + // to the expanded macro type signature + } - let unsafe_activities = x - .input_activity - .iter() - .any(|&act| matches!(act, DiffActivity::DuplicatedOnly | DiffActivity::DualOnly)); - for (arg, activity) in sig.decl.inputs.iter().zip(x.input_activity.iter()) { - d_inputs.push(arg.clone()); - match activity { - DiffActivity::Active => { - act_ret.push(arg.ty.clone()); - // if width =/= 1, then push [arg.ty; width] to act_ret - } - DiffActivity::ActiveOnly => { - // We will add the active scalar to the return type. - // This is handled later. - } - DiffActivity::Duplicated | DiffActivity::DuplicatedOnly => { - for i in 0..x.width { - let mut shadow_arg = arg.clone(); - // We += into the shadow in reverse mode. - *shadow_arg.ty = assure_mut_ref(&arg.ty); - let old_name = if let PatKind::Ident(_, ident, _) = arg.pat.kind { - ident.name - } else { - debug!("{:#?}", &shadow_arg.pat); - panic!("not an ident?"); - }; - let name = format!("d{}_{}", old_name, i); - *shadow_arg.pat = ecx.pat_name(shadow_arg.pat.span, Symbol::intern(&name)); - d_inputs.push(shadow_arg); - } - } - DiffActivity::Dual - | DiffActivity::DualOnly - | DiffActivity::Dualv - | DiffActivity::DualvOnly => { - // the *v variants get lowered to enzyme_dupv and enzyme_dupnoneedv, which cause - // Enzyme to not expect N arguments, but one argument (which is instead larger). - let iterations = - if matches!(activity, DiffActivity::Dualv | DiffActivity::DualvOnly) { - 1 - } else { - x.width - }; - for i in 0..iterations { - let mut shadow_arg = arg.clone(); - let old_name = if let PatKind::Ident(_, ident, _) = arg.pat.kind { - ident.name - } else { - debug!("{:#?}", &shadow_arg.pat); - panic!("not an ident?"); - }; - let name = format!("b{}_{}", old_name, i); - - *shadow_arg.pat = ecx.pat_name(shadow_arg.pat.span, Symbol::intern(&name)); - d_inputs.push(shadow_arg); - } - } - DiffActivity::Const => { - // Nothing to do here. + if errors { + // This is not the right signature, but we can continue parsing. + return sig.clone(); + } + + let unsafe_activities = x + .input_activity + .iter() + .any(|&act| matches!(act, DiffActivity::DuplicatedOnly | DiffActivity::DualOnly)); + for (arg, activity) in sig.decl.inputs.iter().zip(x.input_activity.iter()) { + d_inputs.push(arg.clone()); + match activity { + DiffActivity::Active => { + act_ret.push(arg.ty.clone()); + // if width =/= 1, then push [arg.ty; width] to act_ret + } + DiffActivity::ActiveOnly => { + // We will add the active scalar to the return type. + // This is handled later. + } + DiffActivity::Duplicated | DiffActivity::DuplicatedOnly => { + for i in 0..x.width { + let mut shadow_arg = arg.clone(); + // We += into the shadow in reverse mode. + *shadow_arg.ty = assure_mut_ref(&arg.ty); + let old_name = if let PatKind::Ident(_, ident, _) = arg.pat.kind { + ident.name + } else { + debug!("{:#?}", &shadow_arg.pat); + panic!("not an ident?"); + }; + let name = format!("d{}_{}", old_name, i); + *shadow_arg.pat = ecx.pat_name(shadow_arg.pat.span, Symbol::intern(&name)); + d_inputs.push(shadow_arg); } - DiffActivity::None | DiffActivity::FakeActivitySize(_) => { - panic!("Should not happen"); + } + DiffActivity::Dual + | DiffActivity::DualOnly + | DiffActivity::Dualv + | DiffActivity::DualvOnly => { + // the *v variants get lowered to enzyme_dupv and enzyme_dupnoneedv, which cause + // Enzyme to not expect N arguments, but one argument (which is instead larger). + let iterations = + if matches!(activity, DiffActivity::Dualv | DiffActivity::DualvOnly) { + 1 + } else { + x.width + }; + for i in 0..iterations { + let mut shadow_arg = arg.clone(); + let old_name = if let PatKind::Ident(_, ident, _) = arg.pat.kind { + ident.name + } else { + debug!("{:#?}", &shadow_arg.pat); + panic!("not an ident?"); + }; + let name = format!("b{}_{}", old_name, i); + + *shadow_arg.pat = ecx.pat_name(shadow_arg.pat.span, Symbol::intern(&name)); + d_inputs.push(shadow_arg); } } + DiffActivity::Const => { + // Nothing to do here. + } + DiffActivity::None | DiffActivity::FakeActivitySize(_) => { + panic!("Should not happen"); + } } + } - let active_only_ret = x.ret_activity == DiffActivity::ActiveOnly; - if active_only_ret { - assert!(x.mode.is_rev()); - } + let active_only_ret = x.ret_activity == DiffActivity::ActiveOnly; + if active_only_ret { + assert!(x.mode.is_rev()); + } - // If we return a scalar in the primal and the scalar is active, - // then add it as last arg to the inputs. - if x.mode.is_rev() { - match x.ret_activity { - DiffActivity::Active | DiffActivity::ActiveOnly => { - let ty = match d_decl.output { - FnRetTy::Ty(ref ty) => ty.clone(), - FnRetTy::Default(span) => { - panic!("Did not expect Default ret ty: {:?}", span); - } - }; - let shadow_arg = ecx.param(ty.span, sym::dret, ty); - d_inputs.push(shadow_arg); - } - _ => {} + // If we return a scalar in the primal and the scalar is active, + // then add it as last arg to the inputs. + if x.mode.is_rev() { + match x.ret_activity { + DiffActivity::Active | DiffActivity::ActiveOnly => { + let ty = match d_decl.output { + FnRetTy::Ty(ref ty) => ty.clone(), + FnRetTy::Default(span) => { + panic!("Did not expect Default ret ty: {:?}", span); + } + }; + let shadow_arg = ecx.param(ty.span, sym::dret, ty); + d_inputs.push(shadow_arg); } + _ => {} } - d_decl.inputs = d_inputs; - - if x.mode.is_fwd() { - let ty = match d_decl.output { - FnRetTy::Ty(ref ty) => ty.clone(), - FnRetTy::Default(span) => { - // We want to return std::hint::black_box(()). - let ty = ecx.ty_unit(span); - d_decl.output = FnRetTy::Ty(ty.clone()); - assert!(matches!(x.ret_activity, DiffActivity::None)); - // this won't be used below, so any type would be fine. - ty - } - }; + } + d_decl.inputs = d_inputs; + + if x.mode.is_fwd() { + let ty = match d_decl.output { + FnRetTy::Ty(ref ty) => ty.clone(), + FnRetTy::Default(span) => { + // We want to return std::hint::black_box(()). + let ty = ecx.ty_unit(span); + d_decl.output = FnRetTy::Ty(ty.clone()); + assert!(matches!(x.ret_activity, DiffActivity::None)); + // this won't be used below, so any type would be fine. + ty + } + }; - if matches!(x.ret_activity, DiffActivity::Dual | DiffActivity::Dualv) { - let kind = if x.width == 1 || matches!(x.ret_activity, DiffActivity::Dualv) { - // Dual can only be used for f32/f64 ret. - // In that case we return now a tuple with two floats. - TyKind::Tup(thin_vec![ty.clone(), ty.clone()]) - } else { - // We have to return [T; width+1], +1 for the primal return. - let anon_const = rustc_ast::AnonConst { - id: ast::DUMMY_NODE_ID, - value: ecx.expr_usize(span, 1 + x.width as usize), - }; - TyKind::Array(ty.clone(), anon_const) + if matches!(x.ret_activity, DiffActivity::Dual | DiffActivity::Dualv) { + let kind = if x.width == 1 || matches!(x.ret_activity, DiffActivity::Dualv) { + // Dual can only be used for f32/f64 ret. + // In that case we return now a tuple with two floats. + TyKind::Tup(thin_vec![ty.clone(), ty.clone()]) + } else { + // We have to return [T; width+1], +1 for the primal return. + let anon_const = rustc_ast::AnonConst { + id: ast::DUMMY_NODE_ID, + value: ecx.expr_usize(span, 1 + x.width as usize), + }; + TyKind::Array(ty.clone(), anon_const) + }; + let ty = Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span }); + d_decl.output = FnRetTy::Ty(ty); + } + if matches!(x.ret_activity, DiffActivity::DualOnly | DiffActivity::DualvOnly) { + // No need to change the return type, + // we will just return the shadow in place of the primal return. + // However, if we have a width > 1, then we don't return -> T, but -> [T; width] + if x.width > 1 { + let anon_const = rustc_ast::AnonConst { + id: ast::DUMMY_NODE_ID, + value: ecx.expr_usize(span, x.width as usize), }; + let kind = TyKind::Array(ty.clone(), anon_const); let ty = Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span }); d_decl.output = FnRetTy::Ty(ty); } - if matches!(x.ret_activity, DiffActivity::DualOnly | DiffActivity::DualvOnly) { - // No need to change the return type, - // we will just return the shadow in place of the primal return. - // However, if we have a width > 1, then we don't return -> T, but -> [T; width] - if x.width > 1 { - let anon_const = rustc_ast::AnonConst { - id: ast::DUMMY_NODE_ID, - value: ecx.expr_usize(span, x.width as usize), - }; - let kind = TyKind::Array(ty.clone(), anon_const); - let ty = Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span }); - d_decl.output = FnRetTy::Ty(ty); - } - } } + } - // If we use ActiveOnly, drop the original return value. - d_decl.output = - if active_only_ret { FnRetTy::Default(span) } else { d_decl.output.clone() }; + // If we use ActiveOnly, drop the original return value. + d_decl.output = if active_only_ret { FnRetTy::Default(span) } else { d_decl.output.clone() }; - trace!("act_ret: {:?}", act_ret); + trace!("act_ret: {:?}", act_ret); - // If we have an active input scalar, add it's gradient to the - // return type. This might require changing the return type to a - // tuple. - if act_ret.len() > 0 { - let ret_ty = match d_decl.output { - FnRetTy::Ty(ref ty) => { - if !active_only_ret { - act_ret.insert(0, ty.clone()); - } - let kind = TyKind::Tup(act_ret); - Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span }) + // If we have an active input scalar, add it's gradient to the + // return type. This might require changing the return type to a + // tuple. + if act_ret.len() > 0 { + let ret_ty = match d_decl.output { + FnRetTy::Ty(ref ty) => { + if !active_only_ret { + act_ret.insert(0, ty.clone()); } - FnRetTy::Default(span) => { - if act_ret.len() == 1 { - act_ret[0].clone() - } else { - ecx.ty(span, TyKind::Tup(act_ret)) - } + let kind = TyKind::Tup(act_ret); + Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span }) + } + FnRetTy::Default(span) => { + if act_ret.len() == 1 { + act_ret[0].clone() + } else { + ecx.ty(span, TyKind::Tup(act_ret)) } - }; - d_decl.output = FnRetTy::Ty(ret_ty); - } + } + }; + d_decl.output = FnRetTy::Ty(ret_ty); + } - let mut d_header = sig.header; - if unsafe_activities { - d_header.safety = rustc_ast::Safety::Unsafe(span); - } - let d_sig = FnSig { header: d_header, decl: d_decl, span }; - trace!("Generated signature: {:?}", d_sig); - d_sig + let mut d_header = sig.header; + if unsafe_activities { + d_header.safety = rustc_ast::Safety::Unsafe(span); } + let d_sig = FnSig { header: d_header, decl: d_decl, span }; + trace!("Generated signature: {:?}", d_sig); + d_sig } - -pub(crate) use llvm_enzyme::{expand_forward, expand_reverse}; diff --git a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs index 4622870fee4d5..650e03072e60a 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs @@ -150,7 +150,13 @@ fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx> (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => { ConstValue::Scalar(Scalar::from_uint(n, Size::from_bytes(1))) } - (ast::LitKind::Int(n, _), ty::Uint(_)) if !neg => trunc(n.get()), + // Only reachable through a user `impl Neg` for an unsigned type, which violates the + // orphan rules and has already been reported. + (ast::LitKind::Int(..), ty::Uint(_)) if neg => { + let guar = tcx.dcx().delayed_bug("negated unsigned literal without a prior error"); + return Const::Ty(Ty::new_error(tcx, guar), ty::Const::new_error(tcx, guar)); + } + (ast::LitKind::Int(n, _), ty::Uint(_)) => trunc(n.get()), (ast::LitKind::Int(n, _), ty::Int(_)) => { // Unsigned "negation" has the same bitwise effect as signed negation, // which gets the result we want without additional casts. diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index d14308bb6545b..5da6461ca9a04 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -1,5 +1,4 @@ use std::fmt::Write; -use std::hash::Hasher; use std::iter; use std::ops::Range; @@ -8,7 +7,6 @@ use rustc_data_structures::base_n::ToBaseN; use rustc_data_structures::either::Either; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::intern::Interned; -use rustc_data_structures::stable_hash::StableHasher; use rustc_hashes::Hash64; use rustc_hir as hir; use rustc_hir::def::CtorKind; @@ -172,15 +170,19 @@ pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> Strin |p| { p.push("C"); p.push_disambiguator_fixed_len({ - let mut hasher = StableHasher::new(); - // Incorporate the rustc version to ensure #[rustc_std_internal_symbol] functions - // get a different symbol name depending on the rustc version. - // - // RUSTC_FORCE_RUSTC_VERSION is ignored here as otherwise different we would get an - // abi incompatibility with the standard library. - hasher.write(tcx.sess.cfg_version.as_bytes()); - - hasher.finish() + let core = tcx + .lang_items() + .sized_trait() + // The Sized trait is guaranteed to exist at this point. If you try to define + // any function or static without defining the Sized trait you will get an error + // during type checking. + .expect("#[rustc_std_internal_symbol] requires the Sized trait to be defined") + .krate; + + // Use the same disambiguator as 'core' to ensure #[rustc_std_internal_symbol] + // functions get a different symbol name depending on the rustc version and + // -Cmetadata flags. + tcx.stable_crate_id(core).as_hash() }); p.push_ident("__rustc"); Ok(()) diff --git a/src/bootstrap/Cargo.lock b/src/bootstrap/Cargo.lock index b31d58887ebd3..5ddffe393fb6f 100644 --- a/src/bootstrap/Cargo.lock +++ b/src/bootstrap/Cargo.lock @@ -48,7 +48,6 @@ dependencies = [ "clap", "clap_complete", "cmake", - "errno", "expect-test", "home", "ignore", @@ -56,6 +55,7 @@ dependencies = [ "libc", "object", "opener", + "rustix", "semver", "serde", "serde_derive", diff --git a/src/bootstrap/Cargo.toml b/src/bootstrap/Cargo.toml index 7d055bddf77c7..5a470051fd84f 100644 --- a/src/bootstrap/Cargo.toml +++ b/src/bootstrap/Cargo.toml @@ -90,7 +90,7 @@ features = [ # src/utils/job.rs [target.'cfg(all(unix, not(any(target_os = "haiku", target_os = "hermit"))))'.dependencies] -errno = "0.3.14" +rustix = { version = "1.1.4", default-features = false, features = ["std", "process"] } [dev-dependencies] expect-test = "1" diff --git a/src/bootstrap/src/utils/job.rs b/src/bootstrap/src/utils/job.rs index b370bed36006b..df4d7cb9f5b43 100644 --- a/src/bootstrap/src/utils/job.rs +++ b/src/bootstrap/src/utils/job.rs @@ -9,39 +9,14 @@ pub(crate) fn setup(_sess: &Session) {} #[cfg(all(unix, not(any(target_os = "haiku", target_os = "hermit"))))] mod for_unix { - use std::ffi::c_int; - use std::io; - - use libc::id_t; - - fn get_priority(which: c_int, who: id_t) -> io::Result { - // Genius design: `getpriority` can return -1 on success if the nice value is literally -1. - // Per `getpriority`'s docs, clear `errno` beforehand and check it afterward regardless of - // return value. - errno::set_errno(errno::Errno(0)); - // SAFETY: empty safety contract - let nice = unsafe { libc::getpriority(which as _, who) }; - let new_errno = errno::errno().0; - if new_errno == 0 { Ok(nice) } else { Err(io::Error::from_raw_os_error(new_errno)) } - } - fn set_priority(which: c_int, who: id_t, prio: c_int) -> io::Result<()> { - // SAFETY: empty safety contract - if unsafe { libc::setpriority(which as _, who, prio) != -1 } { - Ok(()) - } else { - Err(io::Error::last_os_error()) - } - } + use rustix::process::{getpriority_process, setpriority_process}; pub(crate) fn setup(sess: &super::Session) { - const TARGET_NICE: c_int = 10; - // The processes that spawn the build are all descendants of the - // current thread. - let (which, who) = (libc::PRIO_PROCESS as _, 0); - // Unwrap both of those to alert users to ridiculous Seccomp-BPF setups messing up their - // performance. - if sess.config.low_priority && get_priority(which, who).unwrap() < TARGET_NICE { - set_priority(which, who, TARGET_NICE).unwrap(); + const TARGET_NICE: libc::c_int = 10; + // The processes that spawn the build are all descendants of the current thread. Unwrap both + // of those to alert users to ridiculous Seccomp-BPF setups messing up their performance. + if sess.config.low_priority && getpriority_process(None).unwrap() < TARGET_NICE { + setpriority_process(None, TARGET_NICE).unwrap(); } } } diff --git a/tests/ui/coherence/orphan-neg-impl-negated-unsigned-literal.rs b/tests/ui/coherence/orphan-neg-impl-negated-unsigned-literal.rs new file mode 100644 index 0000000000000..f412d1a966149 --- /dev/null +++ b/tests/ui/coherence/orphan-neg-impl-negated-unsigned-literal.rs @@ -0,0 +1,12 @@ +// Regression test for . +// An orphan `impl Neg for u8` let `-1: u8` reach MIR building, which ICEd on the negated literal. + +impl std::ops::Neg for u8 { + //~^ ERROR only traits defined in the current crate can be implemented for primitive types + type Output = u8; + fn neg(self) -> Self::Output { + -1 + } +} + +fn main() {} diff --git a/tests/ui/coherence/orphan-neg-impl-negated-unsigned-literal.stderr b/tests/ui/coherence/orphan-neg-impl-negated-unsigned-literal.stderr new file mode 100644 index 0000000000000..d421380438b36 --- /dev/null +++ b/tests/ui/coherence/orphan-neg-impl-negated-unsigned-literal.stderr @@ -0,0 +1,15 @@ +error[E0117]: only traits defined in the current crate can be implemented for primitive types + --> $DIR/orphan-neg-impl-negated-unsigned-literal.rs:4:1 + | +LL | impl std::ops::Neg for u8 { + | ^^^^^^^^^^^^^^^^^^^^^^^-- + | | + | `u8` is not defined in the current crate + | + = note: impl doesn't have any local type before any uncovered type parameters + = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules + = note: define and implement a trait or new type instead + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0117`. diff --git a/tests/ui/type-alias-impl-trait/next-solver-non-defining-use-ice-152446.rs b/tests/ui/type-alias-impl-trait/next-solver-non-defining-use-ice-152446.rs new file mode 100644 index 0000000000000..e29d124a6c26d --- /dev/null +++ b/tests/ui/type-alias-impl-trait/next-solver-non-defining-use-ice-152446.rs @@ -0,0 +1,16 @@ +//@ compile-flags: -Znext-solver=globally + +#![feature(type_alias_impl_trait)] +type Tait = impl Iterator; + +#[define_opaque(Tait)] +fn a() { + let _: Tait = IntoIterator::into_iter([0i32; 0i32]); //~ ERROR mismatched types +} + +#[define_opaque(Tait)] +fn b() { + let _: Tait = IntoIterator::into_iter([0i32; 42 /* <- */]); +} + +fn main() {} diff --git a/tests/ui/type-alias-impl-trait/next-solver-non-defining-use-ice-152446.stderr b/tests/ui/type-alias-impl-trait/next-solver-non-defining-use-ice-152446.stderr new file mode 100644 index 0000000000000..3533410370d24 --- /dev/null +++ b/tests/ui/type-alias-impl-trait/next-solver-non-defining-use-ice-152446.stderr @@ -0,0 +1,16 @@ +error[E0308]: mismatched types + --> $DIR/next-solver-non-defining-use-ice-152446.rs:8:50 + | +LL | let _: Tait = IntoIterator::into_iter([0i32; 0i32]); + | ^^^^ expected `usize`, found `i32` + | + = note: array length can only be `usize` +help: change the type of the numeric literal from `i32` to `usize` + | +LL - let _: Tait = IntoIterator::into_iter([0i32; 0i32]); +LL + let _: Tait = IntoIterator::into_iter([0i32; 0usize]); + | + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0308`.