rustc_builtin_macros/
autodiff.rs

1//! This module contains the implementation of the `#[autodiff]` attribute.
2//! Currently our linter isn't smart enough to see that each import is used in one of the two
3//! configs (autodiff enabled or disabled), so we have to add cfg's to each import.
4//! FIXME(ZuseZ4): Remove this once we have a smarter linter.
5
6mod llvm_enzyme {
7    use std::str::FromStr;
8    use std::string::String;
9
10    use rustc_ast::expand::autodiff_attrs::{
11        AutoDiffAttrs, DiffActivity, DiffMode, valid_input_activity, valid_ret_activity,
12        valid_ty_for_activity,
13    };
14    use rustc_ast::token::{Lit, LitKind, Token, TokenKind};
15    use rustc_ast::tokenstream::*;
16    use rustc_ast::visit::AssocCtxt::*;
17    use rustc_ast::{
18        self as ast, AngleBracketedArg, AngleBracketedArgs, AnonConst, AssocItemKind, BindingMode,
19        FnRetTy, FnSig, GenericArg, GenericArgs, GenericParamKind, Generics, ItemKind,
20        MetaItemInner, MgcaDisambiguation, PatKind, Path, PathSegment, TyKind, Visibility,
21    };
22    use rustc_expand::base::{Annotatable, ExtCtxt};
23    use rustc_span::{Ident, Span, Symbol, sym};
24    use thin_vec::{ThinVec, thin_vec};
25    use tracing::{debug, trace};
26
27    use crate::errors;
28
29    pub(crate) fn outer_normal_attr(
30        kind: &Box<rustc_ast::NormalAttr>,
31        id: rustc_ast::AttrId,
32        span: Span,
33    ) -> rustc_ast::Attribute {
34        let style = rustc_ast::AttrStyle::Outer;
35        let kind = rustc_ast::AttrKind::Normal(kind.clone());
36        rustc_ast::Attribute { kind, id, style, span }
37    }
38
39    // If we have a default `()` return type or explicitley `()` return type,
40    // then we often can skip doing some work.
41    fn has_ret(ty: &FnRetTy) -> bool {
42        match ty {
43            FnRetTy::Ty(ty) => !ty.kind.is_unit(),
44            FnRetTy::Default(_) => false,
45        }
46    }
47    fn first_ident(x: &MetaItemInner) -> rustc_span::Ident {
48        if let Some(l) = x.lit() {
49            match l.kind {
50                ast::LitKind::Int(val, _) => {
51                    // get an Ident from a lit
52                    return rustc_span::Ident::from_str(val.get().to_string().as_str());
53                }
54                _ => {}
55            }
56        }
57
58        let segments = &x.meta_item().unwrap().path.segments;
59        assert!(segments.len() == 1);
60        segments[0].ident
61    }
62
63    fn name(x: &MetaItemInner) -> String {
64        first_ident(x).name.to_string()
65    }
66
67    fn width(x: &MetaItemInner) -> Option<u128> {
68        let lit = x.lit()?;
69        match lit.kind {
70            ast::LitKind::Int(x, _) => Some(x.get()),
71            _ => return None,
72        }
73    }
74
75    // Get information about the function the macro is applied to
76    fn extract_item_info(iitem: &Box<ast::Item>) -> Option<(Visibility, FnSig, Ident, Generics)> {
77        match &iitem.kind {
78            ItemKind::Fn(box ast::Fn { sig, ident, generics, .. }) => {
79                Some((iitem.vis.clone(), sig.clone(), ident.clone(), generics.clone()))
80            }
81            _ => None,
82        }
83    }
84
85    pub(crate) fn from_ast(
86        ecx: &mut ExtCtxt<'_>,
87        meta_item: &ThinVec<MetaItemInner>,
88        has_ret: bool,
89        mode: DiffMode,
90    ) -> AutoDiffAttrs {
91        let dcx = ecx.sess.dcx();
92
93        // Now we check, whether the user wants autodiff in batch/vector mode, or scalar mode.
94        // If he doesn't specify an integer (=width), we default to scalar mode, thus width=1.
95        let mut first_activity = 1;
96
97        let width = if let [_, x, ..] = &meta_item[..]
98            && let Some(x) = width(x)
99        {
100            first_activity = 2;
101            match x.try_into() {
102                Ok(x) => x,
103                Err(_) => {
104                    dcx.emit_err(errors::AutoDiffInvalidWidth {
105                        span: meta_item[1].span(),
106                        width: x,
107                    });
108                    return AutoDiffAttrs::error();
109                }
110            }
111        } else {
112            1
113        };
114
115        let mut activities: Vec<DiffActivity> = vec![];
116        let mut errors = false;
117        for x in &meta_item[first_activity..] {
118            let activity_str = name(&x);
119            let res = DiffActivity::from_str(&activity_str);
120            match res {
121                Ok(x) => activities.push(x),
122                Err(_) => {
123                    dcx.emit_err(errors::AutoDiffUnknownActivity {
124                        span: x.span(),
125                        act: activity_str,
126                    });
127                    errors = true;
128                }
129            };
130        }
131        if errors {
132            return AutoDiffAttrs::error();
133        }
134
135        // If a return type exist, we need to split the last activity,
136        // otherwise we return None as placeholder.
137        let (ret_activity, input_activity) = if has_ret {
138            let Some((last, rest)) = activities.split_last() else {
139                unreachable!(
140                    "should not be reachable because we counted the number of activities previously"
141                );
142            };
143            (last, rest)
144        } else {
145            (&DiffActivity::None, activities.as_slice())
146        };
147
148        AutoDiffAttrs {
149            mode,
150            width,
151            ret_activity: *ret_activity,
152            input_activity: input_activity.to_vec(),
153        }
154    }
155
156    fn meta_item_inner_to_ts(t: &MetaItemInner, ts: &mut Vec<TokenTree>) {
157        let comma: Token = Token::new(TokenKind::Comma, Span::default());
158        let val = first_ident(t);
159        let t = Token::from_ast_ident(val);
160        ts.push(TokenTree::Token(t, Spacing::Joint));
161        ts.push(TokenTree::Token(comma.clone(), Spacing::Alone));
162    }
163
164    pub(crate) fn expand_forward(
165        ecx: &mut ExtCtxt<'_>,
166        expand_span: Span,
167        meta_item: &ast::MetaItem,
168        item: Annotatable,
169    ) -> Vec<Annotatable> {
170        expand_with_mode(ecx, expand_span, meta_item, item, DiffMode::Forward)
171    }
172
173    pub(crate) fn expand_reverse(
174        ecx: &mut ExtCtxt<'_>,
175        expand_span: Span,
176        meta_item: &ast::MetaItem,
177        item: Annotatable,
178    ) -> Vec<Annotatable> {
179        expand_with_mode(ecx, expand_span, meta_item, item, DiffMode::Reverse)
180    }
181
182    /// We expand the autodiff macro to generate a new placeholder function which passes
183    /// type-checking and can be called by users. The exact signature of the generated function
184    /// depends on the configuration provided by the user, but here is an example:
185    ///
186    /// ```
187    /// #[autodiff(cos_box, Reverse, Duplicated, Active)]
188    /// fn sin(x: &Box<f32>) -> f32 {
189    ///     f32::sin(**x)
190    /// }
191    /// ```
192    /// which becomes expanded to:
193    /// ```
194    /// #[rustc_autodiff]
195    /// fn sin(x: &Box<f32>) -> f32 {
196    ///     f32::sin(**x)
197    /// }
198    /// #[rustc_autodiff(Reverse, Duplicated, Active)]
199    /// fn cos_box(x: &Box<f32>, dx: &mut Box<f32>, dret: f32) -> f32 {
200    ///     std::intrinsics::autodiff(sin::<>, cos_box::<>, (x, dx, dret))
201    /// }
202    /// ```
203    /// FIXME(ZuseZ4): Once autodiff is enabled by default, make this a doc comment which is checked
204    /// in CI.
205    pub(crate) fn expand_with_mode(
206        ecx: &mut ExtCtxt<'_>,
207        expand_span: Span,
208        meta_item: &ast::MetaItem,
209        mut item: Annotatable,
210        mode: DiffMode,
211    ) -> Vec<Annotatable> {
212        let dcx = ecx.sess.dcx();
213
214        // first get information about the annotable item: visibility, signature, name and generic
215        // parameters.
216        // these will be used to generate the differentiated version of the function
217        let Some((vis, sig, primal, generics, impl_of_trait)) = (match &item {
218            Annotatable::Item(iitem) => {
219                extract_item_info(iitem).map(|(v, s, p, g)| (v, s, p, g, false))
220            }
221            Annotatable::Stmt(stmt) => match &stmt.kind {
222                ast::StmtKind::Item(iitem) => {
223                    extract_item_info(iitem).map(|(v, s, p, g)| (v, s, p, g, false))
224                }
225                _ => None,
226            },
227            Annotatable::AssocItem(assoc_item, Impl { of_trait }) => match &assoc_item.kind {
228                ast::AssocItemKind::Fn(box ast::Fn { sig, ident, generics, .. }) => Some((
229                    assoc_item.vis.clone(),
230                    sig.clone(),
231                    ident.clone(),
232                    generics.clone(),
233                    *of_trait,
234                )),
235                _ => None,
236            },
237            _ => None,
238        }) else {
239            dcx.emit_err(errors::AutoDiffInvalidApplication { span: item.span() });
240            return vec![item];
241        };
242
243        let meta_item_vec: ThinVec<MetaItemInner> = match meta_item.kind {
244            ast::MetaItemKind::List(ref vec) => vec.clone(),
245            _ => {
246                dcx.emit_err(errors::AutoDiffMissingConfig { span: item.span() });
247                return vec![item];
248            }
249        };
250
251        let has_ret = has_ret(&sig.decl.output);
252
253        // create TokenStream from vec elemtents:
254        // meta_item doesn't have a .tokens field
255        let mut ts: Vec<TokenTree> = vec![];
256        if meta_item_vec.len() < 1 {
257            // At the bare minimum, we need a fnc name.
258            dcx.emit_err(errors::AutoDiffMissingConfig { span: item.span() });
259            return vec![item];
260        }
261
262        let mode_symbol = match mode {
263            DiffMode::Forward => sym::Forward,
264            DiffMode::Reverse => sym::Reverse,
265            _ => unreachable!("Unsupported mode: {:?}", mode),
266        };
267
268        // Insert mode token
269        let mode_token = Token::new(TokenKind::Ident(mode_symbol, false.into()), Span::default());
270        ts.insert(0, TokenTree::Token(mode_token, Spacing::Joint));
271        ts.insert(
272            1,
273            TokenTree::Token(Token::new(TokenKind::Comma, Span::default()), Spacing::Alone),
274        );
275
276        // Now, if the user gave a width (vector aka batch-mode ad), then we copy it.
277        // If it is not given, we default to 1 (scalar mode).
278        let start_position;
279        let kind: LitKind = LitKind::Integer;
280        let symbol;
281        if meta_item_vec.len() >= 2
282            && let Some(width) = width(&meta_item_vec[1])
283        {
284            start_position = 2;
285            symbol = Symbol::intern(&width.to_string());
286        } else {
287            start_position = 1;
288            symbol = sym::integer(1);
289        }
290
291        let l: Lit = Lit { kind, symbol, suffix: None };
292        let t = Token::new(TokenKind::Literal(l), Span::default());
293        let comma = Token::new(TokenKind::Comma, Span::default());
294        ts.push(TokenTree::Token(t, Spacing::Joint));
295        ts.push(TokenTree::Token(comma.clone(), Spacing::Alone));
296
297        for t in meta_item_vec.clone()[start_position..].iter() {
298            meta_item_inner_to_ts(t, &mut ts);
299        }
300
301        if !has_ret {
302            // We don't want users to provide a return activity if the function doesn't return anything.
303            // For simplicity, we just add a dummy token to the end of the list.
304            let t = Token::new(TokenKind::Ident(sym::None, false.into()), Span::default());
305            ts.push(TokenTree::Token(t, Spacing::Joint));
306            ts.push(TokenTree::Token(comma, Spacing::Alone));
307        }
308        // We remove the last, trailing comma.
309        ts.pop();
310        let ts: TokenStream = TokenStream::from_iter(ts);
311
312        let x: AutoDiffAttrs = from_ast(ecx, &meta_item_vec, has_ret, mode);
313        if !x.is_active() {
314            // We encountered an error, so we return the original item.
315            // This allows us to potentially parse other attributes.
316            return vec![item];
317        }
318        let span = ecx.with_def_site_ctxt(expand_span);
319
320        let d_sig = gen_enzyme_decl(ecx, &sig, &x, span);
321
322        let d_body = ecx.block(
323            span,
324            thin_vec![call_autodiff(
325                ecx,
326                primal,
327                first_ident(&meta_item_vec[0]),
328                span,
329                &d_sig,
330                &generics,
331                impl_of_trait,
332            )],
333        );
334
335        // The first element of it is the name of the function to be generated
336        let d_fn = Box::new(ast::Fn {
337            defaultness: ast::Defaultness::Final,
338            sig: d_sig,
339            ident: first_ident(&meta_item_vec[0]),
340            generics,
341            contract: None,
342            body: Some(d_body),
343            define_opaque: None,
344            eii_impls: ThinVec::new(),
345        });
346        let mut rustc_ad_attr =
347            Box::new(ast::NormalAttr::from_ident(Ident::with_dummy_span(sym::rustc_autodiff)));
348
349        let ts2: Vec<TokenTree> = vec![TokenTree::Token(
350            Token::new(TokenKind::Ident(sym::never, false.into()), span),
351            Spacing::Joint,
352        )];
353        let never_arg = ast::DelimArgs {
354            dspan: DelimSpan::from_single(span),
355            delim: ast::token::Delimiter::Parenthesis,
356            tokens: TokenStream::from_iter(ts2),
357        };
358        let inline_item = ast::AttrItem {
359            unsafety: ast::Safety::Default,
360            path: ast::Path::from_ident(Ident::with_dummy_span(sym::inline)),
361            args: ast::AttrArgs::Delimited(never_arg),
362            tokens: None,
363        };
364        let inline_never_attr = Box::new(ast::NormalAttr { item: inline_item, tokens: None });
365        let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id();
366        let attr = outer_normal_attr(&rustc_ad_attr, new_id, span);
367        let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id();
368        let inline_never = outer_normal_attr(&inline_never_attr, new_id, span);
369
370        // We're avoid duplicating the attribute `#[rustc_autodiff]`.
371        fn same_attribute(attr: &ast::AttrKind, item: &ast::AttrKind) -> bool {
372            match (attr, item) {
373                (ast::AttrKind::Normal(a), ast::AttrKind::Normal(b)) => {
374                    let a = &a.item.path;
375                    let b = &b.item.path;
376                    a.segments.iter().eq_by(&b.segments, |a, b| a.ident == b.ident)
377                }
378                _ => false,
379            }
380        }
381
382        let mut has_inline_never = false;
383
384        // Don't add it multiple times:
385        let orig_annotatable: Annotatable = match item {
386            Annotatable::Item(ref mut iitem) => {
387                if !iitem.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) {
388                    iitem.attrs.push(attr);
389                }
390                if iitem.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) {
391                    has_inline_never = true;
392                }
393                Annotatable::Item(iitem.clone())
394            }
395            Annotatable::AssocItem(ref mut assoc_item, i @ Impl { .. }) => {
396                if !assoc_item.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) {
397                    assoc_item.attrs.push(attr);
398                }
399                if assoc_item.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) {
400                    has_inline_never = true;
401                }
402                Annotatable::AssocItem(assoc_item.clone(), i)
403            }
404            Annotatable::Stmt(ref mut stmt) => {
405                match stmt.kind {
406                    ast::StmtKind::Item(ref mut iitem) => {
407                        if !iitem.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) {
408                            iitem.attrs.push(attr);
409                        }
410                        if iitem.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) {
411                            has_inline_never = true;
412                        }
413                    }
414                    _ => unreachable!("stmt kind checked previously"),
415                };
416
417                Annotatable::Stmt(stmt.clone())
418            }
419            _ => {
420                unreachable!("annotatable kind checked previously")
421            }
422        };
423        // Now update for d_fn
424        rustc_ad_attr.item.args = rustc_ast::AttrArgs::Delimited(rustc_ast::DelimArgs {
425            dspan: DelimSpan::dummy(),
426            delim: rustc_ast::token::Delimiter::Parenthesis,
427            tokens: ts,
428        });
429
430        let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id();
431        let d_attr = outer_normal_attr(&rustc_ad_attr, new_id, span);
432
433        // If the source function has the `#[inline(never)]` attribute, we'll also add it to the diff function
434        let mut d_attrs = thin_vec![d_attr];
435
436        if has_inline_never {
437            d_attrs.push(inline_never);
438        }
439
440        let d_annotatable = match &item {
441            Annotatable::AssocItem(_, _) => {
442                let assoc_item: AssocItemKind = ast::AssocItemKind::Fn(d_fn);
443                let d_fn = Box::new(ast::AssocItem {
444                    attrs: d_attrs,
445                    id: ast::DUMMY_NODE_ID,
446                    span,
447                    vis,
448                    kind: assoc_item,
449                    tokens: None,
450                });
451                Annotatable::AssocItem(d_fn, Impl { of_trait: false })
452            }
453            Annotatable::Item(_) => {
454                let mut d_fn = ecx.item(span, d_attrs, ItemKind::Fn(d_fn));
455                d_fn.vis = vis;
456
457                Annotatable::Item(d_fn)
458            }
459            Annotatable::Stmt(_) => {
460                let mut d_fn = ecx.item(span, d_attrs, ItemKind::Fn(d_fn));
461                d_fn.vis = vis;
462
463                Annotatable::Stmt(Box::new(ast::Stmt {
464                    id: ast::DUMMY_NODE_ID,
465                    kind: ast::StmtKind::Item(d_fn),
466                    span,
467                }))
468            }
469            _ => {
470                unreachable!("item kind checked previously")
471            }
472        };
473
474        return vec![orig_annotatable, d_annotatable];
475    }
476
477    // shadow arguments (the extra ones which were not in the original (primal) function), in reverse mode must be
478    // mutable references or ptrs, because Enzyme will write into them.
479    fn assure_mut_ref(ty: &ast::Ty) -> ast::Ty {
480        let mut ty = ty.clone();
481        match ty.kind {
482            TyKind::Ptr(ref mut mut_ty) => {
483                mut_ty.mutbl = ast::Mutability::Mut;
484            }
485            TyKind::Ref(_, ref mut mut_ty) => {
486                mut_ty.mutbl = ast::Mutability::Mut;
487            }
488            _ => {
489                panic!("unsupported type: {:?}", ty);
490            }
491        }
492        ty
493    }
494
495    // Generate `autodiff` intrinsic call
496    // ```
497    // std::intrinsics::autodiff(source, diff, (args))
498    // ```
499    fn call_autodiff(
500        ecx: &ExtCtxt<'_>,
501        primal: Ident,
502        diff: Ident,
503        span: Span,
504        d_sig: &FnSig,
505        generics: &Generics,
506        is_impl: bool,
507    ) -> rustc_ast::Stmt {
508        let primal_path_expr = gen_turbofish_expr(ecx, primal, generics, span, is_impl);
509        let diff_path_expr = gen_turbofish_expr(ecx, diff, generics, span, is_impl);
510
511        let tuple_expr = ecx.expr_tuple(
512            span,
513            d_sig
514                .decl
515                .inputs
516                .iter()
517                .map(|arg| match arg.pat.kind {
518                    PatKind::Ident(_, ident, _) => ecx.expr_path(ecx.path_ident(span, ident)),
519                    _ => todo!(),
520                })
521                .collect::<ThinVec<_>>()
522                .into(),
523        );
524
525        let enzyme_path_idents = ecx.std_path(&[sym::intrinsics, sym::autodiff]);
526        let enzyme_path = ecx.path(span, enzyme_path_idents);
527        let call_expr = ecx.expr_call(
528            span,
529            ecx.expr_path(enzyme_path),
530            vec![primal_path_expr, diff_path_expr, tuple_expr].into(),
531        );
532
533        ecx.stmt_expr(call_expr)
534    }
535
536    // Generate turbofish expression from fn name and generics
537    // Given `foo` and `<A, B, C>` params, gen `foo::<A, B, C>`
538    // We use this expression when passing primal and diff function to the autodiff intrinsic
539    fn gen_turbofish_expr(
540        ecx: &ExtCtxt<'_>,
541        ident: Ident,
542        generics: &Generics,
543        span: Span,
544        is_impl: bool,
545    ) -> Box<ast::Expr> {
546        let generic_args = generics
547            .params
548            .iter()
549            .filter_map(|p| match &p.kind {
550                GenericParamKind::Type { .. } => {
551                    let path = ast::Path::from_ident(p.ident);
552                    let ty = ecx.ty_path(path);
553                    Some(AngleBracketedArg::Arg(GenericArg::Type(ty)))
554                }
555                GenericParamKind::Const { .. } => {
556                    let expr = ecx.expr_path(ast::Path::from_ident(p.ident));
557                    let anon_const = AnonConst {
558                        id: ast::DUMMY_NODE_ID,
559                        value: expr,
560                        mgca_disambiguation: MgcaDisambiguation::Direct,
561                    };
562                    Some(AngleBracketedArg::Arg(GenericArg::Const(anon_const)))
563                }
564                GenericParamKind::Lifetime { .. } => None,
565            })
566            .collect::<ThinVec<_>>();
567
568        let args: AngleBracketedArgs = AngleBracketedArgs { span, args: generic_args };
569
570        let segment = PathSegment {
571            ident,
572            id: ast::DUMMY_NODE_ID,
573            args: Some(Box::new(GenericArgs::AngleBracketed(args))),
574        };
575
576        let segments = if is_impl {
577            thin_vec![
578                PathSegment { ident: Ident::from_str("Self"), id: ast::DUMMY_NODE_ID, args: None },
579                segment,
580            ]
581        } else {
582            thin_vec![segment]
583        };
584
585        let path = Path { span, segments, tokens: None };
586
587        ecx.expr_path(path)
588    }
589
590    // Generate the new function declaration. Const arguments are kept as is. Duplicated arguments must
591    // be pointers or references. Those receive a shadow argument, which is a mutable reference/pointer.
592    // Active arguments must be scalars. Their shadow argument is added to the return type (and will be
593    // zero-initialized by Enzyme).
594    // Each argument of the primal function (and the return type if existing) must be annotated with an
595    // activity.
596    //
597    // Error handling: If the user provides an invalid configuration (incorrect numbers, types, or
598    // both), we emit an error and return the original signature. This allows us to continue parsing.
599    // FIXME(Sa4dUs): make individual activities' span available so errors
600    // can point to only the activity instead of the entire attribute
601    fn gen_enzyme_decl(
602        ecx: &ExtCtxt<'_>,
603        sig: &ast::FnSig,
604        x: &AutoDiffAttrs,
605        span: Span,
606    ) -> ast::FnSig {
607        let dcx = ecx.sess.dcx();
608        let has_ret = has_ret(&sig.decl.output);
609        let sig_args = sig.decl.inputs.len() + if has_ret { 1 } else { 0 };
610        let num_activities = x.input_activity.len() + if x.has_ret_activity() { 1 } else { 0 };
611        if sig_args != num_activities {
612            dcx.emit_err(errors::AutoDiffInvalidNumberActivities {
613                span,
614                expected: sig_args,
615                found: num_activities,
616            });
617            // This is not the right signature, but we can continue parsing.
618            return sig.clone();
619        }
620        assert!(sig.decl.inputs.len() == x.input_activity.len());
621        assert!(has_ret == x.has_ret_activity());
622        let mut d_decl = sig.decl.clone();
623        let mut d_inputs = Vec::new();
624        let mut new_inputs = Vec::new();
625        let mut idents = Vec::new();
626        let mut act_ret = ThinVec::new();
627
628        // We have two loops, a first one just to check the activities and types and possibly report
629        // multiple errors in one compilation session.
630        let mut errors = false;
631        for (arg, activity) in sig.decl.inputs.iter().zip(x.input_activity.iter()) {
632            if !valid_input_activity(x.mode, *activity) {
633                dcx.emit_err(errors::AutoDiffInvalidApplicationModeAct {
634                    span,
635                    mode: x.mode.to_string(),
636                    act: activity.to_string(),
637                });
638                errors = true;
639            }
640            if !valid_ty_for_activity(&arg.ty, *activity) {
641                dcx.emit_err(errors::AutoDiffInvalidTypeForActivity {
642                    span: arg.ty.span,
643                    act: activity.to_string(),
644                });
645                errors = true;
646            }
647        }
648
649        if has_ret && !valid_ret_activity(x.mode, x.ret_activity) {
650            dcx.emit_err(errors::AutoDiffInvalidRetAct {
651                span,
652                mode: x.mode.to_string(),
653                act: x.ret_activity.to_string(),
654            });
655            // We don't set `errors = true` to avoid annoying type errors relative
656            // to the expanded macro type signature
657        }
658
659        if errors {
660            // This is not the right signature, but we can continue parsing.
661            return sig.clone();
662        }
663
664        let unsafe_activities = x
665            .input_activity
666            .iter()
667            .any(|&act| matches!(act, DiffActivity::DuplicatedOnly | DiffActivity::DualOnly));
668        for (arg, activity) in sig.decl.inputs.iter().zip(x.input_activity.iter()) {
669            d_inputs.push(arg.clone());
670            match activity {
671                DiffActivity::Active => {
672                    act_ret.push(arg.ty.clone());
673                    // if width =/= 1, then push [arg.ty; width] to act_ret
674                }
675                DiffActivity::ActiveOnly => {
676                    // We will add the active scalar to the return type.
677                    // This is handled later.
678                }
679                DiffActivity::Duplicated | DiffActivity::DuplicatedOnly => {
680                    for i in 0..x.width {
681                        let mut shadow_arg = arg.clone();
682                        // We += into the shadow in reverse mode.
683                        shadow_arg.ty = Box::new(assure_mut_ref(&arg.ty));
684                        let old_name = if let PatKind::Ident(_, ident, _) = arg.pat.kind {
685                            ident.name
686                        } else {
687                            debug!("{:#?}", &shadow_arg.pat);
688                            panic!("not an ident?");
689                        };
690                        let name: String = format!("d{}_{}", old_name, i);
691                        new_inputs.push(name.clone());
692                        let ident = Ident::from_str_and_span(&name, shadow_arg.pat.span);
693                        shadow_arg.pat = Box::new(ast::Pat {
694                            id: ast::DUMMY_NODE_ID,
695                            kind: PatKind::Ident(BindingMode::NONE, ident, None),
696                            span: shadow_arg.pat.span,
697                            tokens: shadow_arg.pat.tokens.clone(),
698                        });
699                        d_inputs.push(shadow_arg.clone());
700                    }
701                }
702                DiffActivity::Dual
703                | DiffActivity::DualOnly
704                | DiffActivity::Dualv
705                | DiffActivity::DualvOnly => {
706                    // the *v variants get lowered to enzyme_dupv and enzyme_dupnoneedv, which cause
707                    // Enzyme to not expect N arguments, but one argument (which is instead larger).
708                    let iterations =
709                        if matches!(activity, DiffActivity::Dualv | DiffActivity::DualvOnly) {
710                            1
711                        } else {
712                            x.width
713                        };
714                    for i in 0..iterations {
715                        let mut shadow_arg = arg.clone();
716                        let old_name = if let PatKind::Ident(_, ident, _) = arg.pat.kind {
717                            ident.name
718                        } else {
719                            debug!("{:#?}", &shadow_arg.pat);
720                            panic!("not an ident?");
721                        };
722                        let name: String = format!("b{}_{}", old_name, i);
723                        new_inputs.push(name.clone());
724                        let ident = Ident::from_str_and_span(&name, shadow_arg.pat.span);
725                        shadow_arg.pat = Box::new(ast::Pat {
726                            id: ast::DUMMY_NODE_ID,
727                            kind: PatKind::Ident(BindingMode::NONE, ident, None),
728                            span: shadow_arg.pat.span,
729                            tokens: shadow_arg.pat.tokens.clone(),
730                        });
731                        d_inputs.push(shadow_arg.clone());
732                    }
733                }
734                DiffActivity::Const => {
735                    // Nothing to do here.
736                }
737                DiffActivity::None | DiffActivity::FakeActivitySize(_) => {
738                    panic!("Should not happen");
739                }
740            }
741            if let PatKind::Ident(_, ident, _) = arg.pat.kind {
742                idents.push(ident.clone());
743            } else {
744                panic!("not an ident?");
745            }
746        }
747
748        let active_only_ret = x.ret_activity == DiffActivity::ActiveOnly;
749        if active_only_ret {
750            assert!(x.mode.is_rev());
751        }
752
753        // If we return a scalar in the primal and the scalar is active,
754        // then add it as last arg to the inputs.
755        if x.mode.is_rev() {
756            match x.ret_activity {
757                DiffActivity::Active | DiffActivity::ActiveOnly => {
758                    let ty = match d_decl.output {
759                        FnRetTy::Ty(ref ty) => ty.clone(),
760                        FnRetTy::Default(span) => {
761                            panic!("Did not expect Default ret ty: {:?}", span);
762                        }
763                    };
764                    let name = "dret".to_string();
765                    let ident = Ident::from_str_and_span(&name, ty.span);
766                    let shadow_arg = ast::Param {
767                        attrs: ThinVec::new(),
768                        ty: ty.clone(),
769                        pat: Box::new(ast::Pat {
770                            id: ast::DUMMY_NODE_ID,
771                            kind: PatKind::Ident(BindingMode::NONE, ident, None),
772                            span: ty.span,
773                            tokens: None,
774                        }),
775                        id: ast::DUMMY_NODE_ID,
776                        span: ty.span,
777                        is_placeholder: false,
778                    };
779                    d_inputs.push(shadow_arg);
780                    new_inputs.push(name);
781                }
782                _ => {}
783            }
784        }
785        d_decl.inputs = d_inputs.into();
786
787        if x.mode.is_fwd() {
788            let ty = match d_decl.output {
789                FnRetTy::Ty(ref ty) => ty.clone(),
790                FnRetTy::Default(span) => {
791                    // We want to return std::hint::black_box(()).
792                    let kind = TyKind::Tup(ThinVec::new());
793                    let ty = Box::new(rustc_ast::Ty {
794                        kind,
795                        id: ast::DUMMY_NODE_ID,
796                        span,
797                        tokens: None,
798                    });
799                    d_decl.output = FnRetTy::Ty(ty.clone());
800                    assert!(matches!(x.ret_activity, DiffActivity::None));
801                    // this won't be used below, so any type would be fine.
802                    ty
803                }
804            };
805
806            if matches!(x.ret_activity, DiffActivity::Dual | DiffActivity::Dualv) {
807                let kind = if x.width == 1 || matches!(x.ret_activity, DiffActivity::Dualv) {
808                    // Dual can only be used for f32/f64 ret.
809                    // In that case we return now a tuple with two floats.
810                    TyKind::Tup(thin_vec![ty.clone(), ty.clone()])
811                } else {
812                    // We have to return [T; width+1], +1 for the primal return.
813                    let anon_const = rustc_ast::AnonConst {
814                        id: ast::DUMMY_NODE_ID,
815                        value: ecx.expr_usize(span, 1 + x.width as usize),
816                        mgca_disambiguation: MgcaDisambiguation::Direct,
817                    };
818                    TyKind::Array(ty.clone(), anon_const)
819                };
820                let ty = Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span, tokens: None });
821                d_decl.output = FnRetTy::Ty(ty);
822            }
823            if matches!(x.ret_activity, DiffActivity::DualOnly | DiffActivity::DualvOnly) {
824                // No need to change the return type,
825                // we will just return the shadow in place of the primal return.
826                // However, if we have a width > 1, then we don't return -> T, but -> [T; width]
827                if x.width > 1 {
828                    let anon_const = rustc_ast::AnonConst {
829                        id: ast::DUMMY_NODE_ID,
830                        value: ecx.expr_usize(span, x.width as usize),
831                        mgca_disambiguation: MgcaDisambiguation::Direct,
832                    };
833                    let kind = TyKind::Array(ty.clone(), anon_const);
834                    let ty =
835                        Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span, tokens: None });
836                    d_decl.output = FnRetTy::Ty(ty);
837                }
838            }
839        }
840
841        // If we use ActiveOnly, drop the original return value.
842        d_decl.output =
843            if active_only_ret { FnRetTy::Default(span) } else { d_decl.output.clone() };
844
845        trace!("act_ret: {:?}", act_ret);
846
847        // If we have an active input scalar, add it's gradient to the
848        // return type. This might require changing the return type to a
849        // tuple.
850        if act_ret.len() > 0 {
851            let ret_ty = match d_decl.output {
852                FnRetTy::Ty(ref ty) => {
853                    if !active_only_ret {
854                        act_ret.insert(0, ty.clone());
855                    }
856                    let kind = TyKind::Tup(act_ret);
857                    Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span, tokens: None })
858                }
859                FnRetTy::Default(span) => {
860                    if act_ret.len() == 1 {
861                        act_ret[0].clone()
862                    } else {
863                        let kind = TyKind::Tup(act_ret.iter().map(|arg| arg.clone()).collect());
864                        Box::new(rustc_ast::Ty { kind, id: ast::DUMMY_NODE_ID, span, tokens: None })
865                    }
866                }
867            };
868            d_decl.output = FnRetTy::Ty(ret_ty);
869        }
870
871        let mut d_header = sig.header.clone();
872        if unsafe_activities {
873            d_header.safety = rustc_ast::Safety::Unsafe(span);
874        }
875        let d_sig = FnSig { header: d_header, decl: d_decl, span };
876        trace!("Generated signature: {:?}", d_sig);
877        d_sig
878    }
879}
880
881pub(crate) use llvm_enzyme::{expand_forward, expand_reverse};