Skip to main content

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        DiffActivity, DiffMode, valid_input_activity, valid_ret_activity, valid_ty_for_activity,
12    };
13    use rustc_ast::token::{Lit, LitKind, Token, TokenKind};
14    use rustc_ast::tokenstream::*;
15    use rustc_ast::visit::AssocCtxt::*;
16    use rustc_ast::{
17        self as ast, AngleBracketedArg, AngleBracketedArgs, AnonConst, AssocItemKind, BindingMode,
18        FnRetTy, FnSig, GenericArg, GenericArgs, GenericParamKind, Generics, ItemKind,
19        MetaItemInner, PatKind, Path, PathSegment, TyKind, Visibility,
20    };
21    use rustc_expand::base::{Annotatable, ExtCtxt};
22    use rustc_hir::attrs::RustcAutodiff;
23    use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
24    use thin_vec::{ThinVec, thin_vec};
25    use tracing::{debug, trace};
26
27    use crate::diagnostics;
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        if !(segments.len() == 1) {
    ::core::panicking::panic("assertion failed: segments.len() == 1")
};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(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    ) -> RustcAutodiff {
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(diagnostics::AutoDiffInvalidWidth {
105                        span: meta_item[1].span(),
106                        width: x,
107                    });
108                    return RustcAutodiff::error();
109                }
110            }
111        } else {
112            1
113        };
114
115        let mut activities: Vec<DiffActivity> = ::alloc::vec::Vec::new()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(diagnostics::AutoDiffUnknownActivity {
124                        span: x.span(),
125                        act: activity_str,
126                    });
127                    errors = true;
128                }
129            };
130        }
131        if errors {
132            return RustcAutodiff::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                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("should not be reachable because we counted the number of activities previously")));
};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        RustcAutodiff {
149            mode,
150            width,
151            ret_activity: *ret_activity,
152            input_activity: input_activity.iter().cloned().collect(),
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::<> as fn(..) -> .., 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, is_impl)) = (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, _ctxt @ (Impl { of_trait: _ } | Trait)) => {
228                match &assoc_item.kind {
229                    ast::AssocItemKind::Fn(ast::Fn { sig, ident, generics, .. }) => Some((
230                        assoc_item.vis.clone(),
231                        sig.clone(),
232                        ident.clone(),
233                        generics.clone(),
234                        true,
235                    )),
236                    _ => None,
237                }
238            }
239            _ => None,
240        }) else {
241            dcx.emit_err(diagnostics::AutoDiffInvalidApplication { span: item.span() });
242            return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
243        };
244
245        let meta_item_vec: ThinVec<MetaItemInner> = match meta_item.kind {
246            ast::MetaItemKind::List(ref vec) => vec.clone(),
247            _ => {
248                dcx.emit_err(diagnostics::AutoDiffMissingConfig { span: item.span() });
249                return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
250            }
251        };
252
253        let has_ret = has_ret(&sig.decl.output);
254
255        // create TokenStream from vec elemtents:
256        // meta_item doesn't have a .tokens field
257        let mut ts: Vec<TokenTree> = ::alloc::vec::Vec::new()vec![];
258        if meta_item_vec.len() < 1 {
259            // At the bare minimum, we need a fnc name.
260            dcx.emit_err(diagnostics::AutoDiffMissingConfig { span: item.span() });
261            return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
262        }
263
264        let mode_symbol = match mode {
265            DiffMode::Forward => sym::Forward,
266            DiffMode::Reverse => sym::Reverse,
267            _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Unsupported mode: {0:?}", mode)));
}unreachable!("Unsupported mode: {:?}", mode),
268        };
269
270        // Insert mode token
271        let mode_token = Token::new(TokenKind::Ident(mode_symbol, false.into()), Span::default());
272        ts.insert(0, TokenTree::Token(mode_token, Spacing::Joint));
273        ts.insert(
274            1,
275            TokenTree::Token(Token::new(TokenKind::Comma, Span::default()), Spacing::Alone),
276        );
277
278        // Now, if the user gave a width (vector aka batch-mode ad), then we copy it.
279        // If it is not given, we default to 1 (scalar mode).
280        let start_position;
281        let kind: LitKind = LitKind::Integer;
282        let symbol;
283        if meta_item_vec.len() >= 2
284            && let Some(width) = width(&meta_item_vec[1])
285        {
286            start_position = 2;
287            symbol = Symbol::intern(&width.to_string());
288        } else {
289            start_position = 1;
290            symbol = sym::integer(1);
291        }
292
293        let l: Lit = Lit { kind, symbol, suffix: None };
294        let t = Token::new(TokenKind::Literal(l), Span::default());
295        let comma = Token::new(TokenKind::Comma, Span::default());
296        ts.push(TokenTree::Token(t, Spacing::Joint));
297        ts.push(TokenTree::Token(comma.clone(), Spacing::Alone));
298
299        for t in meta_item_vec.clone()[start_position..].iter() {
300            meta_item_inner_to_ts(t, &mut ts);
301        }
302
303        if !has_ret {
304            // We don't want users to provide a return activity if the function doesn't return anything.
305            // For simplicity, we just add a dummy token to the end of the list.
306            let t = Token::new(TokenKind::Ident(sym::None, false.into()), Span::default());
307            ts.push(TokenTree::Token(t, Spacing::Joint));
308            ts.push(TokenTree::Token(comma, Spacing::Alone));
309        }
310        // We remove the last, trailing comma.
311        ts.pop();
312        let ts: TokenStream = TokenStream::from_iter(ts);
313
314        let x: RustcAutodiff = from_ast(ecx, &meta_item_vec, has_ret, mode);
315        if !x.is_active() {
316            // We encountered an error, so we return the original item.
317            // This allows us to potentially parse other attributes.
318            return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
319        }
320        let span = ecx.with_def_site_ctxt(expand_span);
321
322        let d_sig = gen_enzyme_decl(ecx, &sig, &x, span);
323
324        let d_body = ecx.block(
325            span,
326            {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(call_autodiff(ecx, primal, first_ident(&meta_item_vec[0]), span,
            &sig, &d_sig, &generics, is_impl));
    vec
}thin_vec![call_autodiff(
327                ecx,
328                primal,
329                first_ident(&meta_item_vec[0]),
330                span,
331                &sig,
332                &d_sig,
333                &generics,
334                is_impl,
335            )],
336        );
337
338        // The first element of it is the name of the function to be generated
339        let d_fn = Box::new(ast::Fn {
340            defaultness: ast::Defaultness::Implicit,
341            sig: d_sig,
342            ident: first_ident(&meta_item_vec[0]),
343            generics,
344            contract: None,
345            body: Some(d_body),
346            define_opaque: None,
347            eii_impls: ThinVec::new(),
348        });
349        let mut rustc_ad_attr =
350            Box::new(ast::NormalAttr::from_ident(Ident::with_dummy_span(sym::rustc_autodiff)));
351
352        let ts2: Vec<TokenTree> = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [TokenTree::Token(Token::new(TokenKind::Ident(sym::never,
                            false.into()), span), Spacing::Joint)]))vec![TokenTree::Token(
353            Token::new(TokenKind::Ident(sym::never, false.into()), span),
354            Spacing::Joint,
355        )];
356        let never_arg = ast::DelimArgs {
357            dspan: DelimSpan::from_single(span),
358            delim: ast::token::Delimiter::Parenthesis,
359            tokens: TokenStream::from_iter(ts2),
360        };
361        let inline_item = ast::AttrItem {
362            unsafety: ast::Safety::Default,
363            path: ast::Path::from_ident(Ident::with_dummy_span(sym::inline)),
364            args: ast::AttrArgs::Delimited(never_arg),
365            span: DUMMY_SP,
366        };
367        let inline_never_attr = Box::new(ast::NormalAttr { item: inline_item, tokens: None });
368        let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id();
369        let attr = outer_normal_attr(&rustc_ad_attr, new_id, span);
370        let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id();
371        let inline_never = outer_normal_attr(&inline_never_attr, new_id, span);
372
373        // We're avoid duplicating the attribute `#[rustc_autodiff]`.
374        fn same_attribute(attr: &ast::AttrKind, item: &ast::AttrKind) -> bool {
375            match (attr, item) {
376                (ast::AttrKind::Normal(a), ast::AttrKind::Normal(b)) => {
377                    let a = &a.item.path;
378                    let b = &b.item.path;
379                    a.segments.iter().eq_by(&b.segments, |a, b| a.ident == b.ident)
380                }
381                _ => false,
382            }
383        }
384
385        let mut has_inline_never = false;
386
387        // Don't add it multiple times:
388        let orig_annotatable: Annotatable = match item {
389            Annotatable::Item(ref mut iitem) => {
390                if !iitem.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) {
391                    iitem.attrs.push(attr);
392                }
393                if iitem.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) {
394                    has_inline_never = true;
395                }
396                Annotatable::Item(iitem.clone())
397            }
398            Annotatable::AssocItem(ref mut assoc_item, ctxt @ (Impl { .. } | Trait)) => {
399                if !assoc_item.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) {
400                    assoc_item.attrs.push(attr);
401                }
402                if assoc_item.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) {
403                    has_inline_never = true;
404                }
405                Annotatable::AssocItem(assoc_item.clone(), ctxt)
406            }
407            Annotatable::Stmt(ref mut stmt) => {
408                match stmt.kind {
409                    ast::StmtKind::Item(ref mut iitem) => {
410                        if !iitem.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) {
411                            iitem.attrs.push(attr);
412                        }
413                        if iitem.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) {
414                            has_inline_never = true;
415                        }
416                    }
417                    _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("stmt kind checked previously")));
}unreachable!("stmt kind checked previously"),
418                };
419
420                Annotatable::Stmt(stmt.clone())
421            }
422            _ => {
423                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("annotatable kind checked previously")));
}unreachable!("annotatable kind checked previously")
424            }
425        };
426        // Now update for d_fn
427        rustc_ad_attr.item.args = rustc_ast::AttrArgs::Delimited(rustc_ast::DelimArgs {
428            dspan: DelimSpan::dummy(),
429            delim: rustc_ast::token::Delimiter::Parenthesis,
430            tokens: ts,
431        });
432
433        let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id();
434        let d_attr = outer_normal_attr(&rustc_ad_attr, new_id, span);
435
436        // If the source function has the `#[inline(never)]` attribute, we'll also add it to the diff function
437        let mut d_attrs = {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(d_attr);
    vec
}thin_vec![d_attr];
438
439        if has_inline_never {
440            d_attrs.push(inline_never);
441        }
442
443        let d_annotatable = match &item {
444            Annotatable::AssocItem(_, ctxt) => {
445                let assoc_item: AssocItemKind = ast::AssocItemKind::Fn(d_fn);
446                let d_fn = Box::new(ast::AssocItem {
447                    attrs: d_attrs,
448                    id: ast::DUMMY_NODE_ID,
449                    span,
450                    vis,
451                    kind: assoc_item,
452                    tokens: None,
453                });
454                Annotatable::AssocItem(d_fn, *ctxt)
455            }
456            Annotatable::Item(_) => {
457                let mut d_fn = ecx.item(span, d_attrs, ItemKind::Fn(d_fn));
458                d_fn.vis = vis;
459
460                Annotatable::Item(d_fn)
461            }
462            Annotatable::Stmt(_) => {
463                let mut d_fn = ecx.item(span, d_attrs, ItemKind::Fn(d_fn));
464                d_fn.vis = vis;
465
466                Annotatable::Stmt(Box::new(ast::Stmt {
467                    id: ast::DUMMY_NODE_ID,
468                    kind: ast::StmtKind::Item(d_fn),
469                    span,
470                }))
471            }
472            _ => {
473                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("item kind checked previously")));
}unreachable!("item kind checked previously")
474            }
475        };
476
477        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [orig_annotatable, d_annotatable]))vec![orig_annotatable, d_annotatable];
478    }
479
480    // shadow arguments (the extra ones which were not in the original (primal) function), in reverse mode must be
481    // mutable references or ptrs, because Enzyme will write into them.
482    fn assure_mut_ref(ty: &ast::Ty) -> ast::Ty {
483        let mut ty = ty.clone();
484        match ty.kind {
485            TyKind::Ptr(ref mut mut_ty) => {
486                mut_ty.mutbl = ast::Mutability::Mut;
487            }
488            TyKind::Ref(_, ref mut mut_ty) => {
489                mut_ty.mutbl = ast::Mutability::Mut;
490            }
491            _ => {
492                {
    ::core::panicking::panic_fmt(format_args!("unsupported type: {0:?}", ty));
};panic!("unsupported type: {:?}", ty);
493            }
494        }
495        ty
496    }
497
498    // Generate `autodiff` intrinsic call
499    // ```
500    // std::intrinsics::autodiff(source as fn(..) -> .., diff, (args))
501    // ```
502    fn call_autodiff(
503        ecx: &ExtCtxt<'_>,
504        primal: Ident,
505        diff: Ident,
506        span: Span,
507        p_sig: &FnSig,
508        d_sig: &FnSig,
509        generics: &Generics,
510        is_impl: bool,
511    ) -> rustc_ast::Stmt {
512        let primal_path_expr = gen_turbofish_expr(ecx, primal, generics, span, is_impl);
513
514        let self_ty = || ecx.ty_path(ast::Path::from_ident(Ident::with_dummy_span(kw::SelfUpper)));
515        let fn_ptr_params: ThinVec<ast::Param> = p_sig
516            .decl
517            .inputs
518            .iter()
519            .map(|param| {
520                let ty = match &param.ty.kind {
521                    TyKind::ImplicitSelf => self_ty(),
522                    TyKind::Ref(lt, mt) if #[allow(non_exhaustive_omitted_patterns)] match mt.ty.kind {
    TyKind::ImplicitSelf => true,
    _ => false,
}matches!(mt.ty.kind, TyKind::ImplicitSelf) => ecx.ty(
523                        span,
524                        TyKind::Ref(lt.clone(), ast::MutTy { ty: self_ty(), mutbl: mt.mutbl }),
525                    ),
526                    TyKind::Ptr(mt) if #[allow(non_exhaustive_omitted_patterns)] match mt.ty.kind {
    TyKind::ImplicitSelf => true,
    _ => false,
}matches!(mt.ty.kind, TyKind::ImplicitSelf) => {
527                        ecx.ty(span, TyKind::Ptr(ast::MutTy { ty: self_ty(), mutbl: mt.mutbl }))
528                    }
529                    _ => param.ty.clone(),
530                };
531                ast::Param {
532                    attrs: ast::AttrVec::new(),
533                    ty,
534                    pat: Box::new(ecx.pat_wild(span)),
535                    id: ast::DUMMY_NODE_ID,
536                    span,
537                    is_placeholder: false,
538                }
539            })
540            .collect();
541        let fn_ptr_ty = ecx.ty(
542            span,
543            TyKind::FnPtr(Box::new(ast::FnPtrTy {
544                safety: p_sig.header.safety,
545                ext: p_sig.header.ext,
546                generic_params: ThinVec::new(),
547                decl: Box::new(ast::FnDecl {
548                    inputs: fn_ptr_params,
549                    output: p_sig.decl.output.clone(),
550                }),
551                decl_span: span,
552            })),
553        );
554        let primal_fn_ptr = ecx.expr(span, ast::ExprKind::Cast(primal_path_expr, fn_ptr_ty));
555
556        let diff_path_expr = gen_turbofish_expr(ecx, diff, generics, span, is_impl);
557
558        let tuple_expr = ecx.expr_tuple(
559            span,
560            d_sig
561                .decl
562                .inputs
563                .iter()
564                .map(|arg| match arg.pat.kind {
565                    PatKind::Ident(_, ident, _) => ecx.expr_path(ecx.path_ident(span, ident)),
566                    _ => ::core::panicking::panic("not implemented")unimplemented!(),
567                })
568                .collect::<ThinVec<_>>(),
569        );
570
571        let enzyme_path_idents = ecx.std_path(&[sym::intrinsics, sym::autodiff]);
572        let enzyme_path = ecx.path(span, enzyme_path_idents);
573        let call_expr = ecx.expr_call(
574            span,
575            ecx.expr_path(enzyme_path),
576            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [primal_fn_ptr, diff_path_expr, tuple_expr]))vec![primal_fn_ptr, diff_path_expr, tuple_expr].into(),
577        );
578
579        ecx.stmt_expr(call_expr)
580    }
581
582    // Generate turbofish expression from fn name and generics
583    // Given `foo` and `<A, B, C>` params, gen `foo::<A, B, C>`
584    // We use this expression when passing primal and diff function to the autodiff intrinsic
585    fn gen_turbofish_expr(
586        ecx: &ExtCtxt<'_>,
587        ident: Ident,
588        generics: &Generics,
589        span: Span,
590        is_impl: bool,
591    ) -> Box<ast::Expr> {
592        let generic_args = generics
593            .params
594            .iter()
595            .filter_map(|p| match &p.kind {
596                GenericParamKind::Type { .. } => {
597                    let path = ast::Path::from_ident(p.ident);
598                    let ty = ecx.ty_path(path);
599                    Some(AngleBracketedArg::Arg(GenericArg::Type(ty)))
600                }
601                GenericParamKind::Const { .. } => {
602                    let expr = ecx.expr_path(ast::Path::from_ident(p.ident));
603                    let anon_const = AnonConst { id: ast::DUMMY_NODE_ID, value: expr };
604                    Some(AngleBracketedArg::Arg(GenericArg::Const(anon_const)))
605                }
606                GenericParamKind::Lifetime { .. } => None,
607            })
608            .collect::<ThinVec<_>>();
609
610        let args: AngleBracketedArgs = AngleBracketedArgs { span, args: generic_args };
611
612        let segment = PathSegment {
613            ident,
614            id: ast::DUMMY_NODE_ID,
615            args: Some(Box::new(GenericArgs::AngleBracketed(args))),
616        };
617
618        let segments = if is_impl {
619            {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(PathSegment {
            ident: Ident::from_str("Self"),
            id: ast::DUMMY_NODE_ID,
            args: None,
        });
    vec.push(segment);
    vec
}thin_vec![
620                PathSegment { ident: Ident::from_str("Self"), id: ast::DUMMY_NODE_ID, args: None },
621                segment,
622            ]
623        } else {
624            {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(segment);
    vec
}thin_vec![segment]
625        };
626
627        let path = Path { span, segments };
628
629        ecx.expr_path(path)
630    }
631
632    // Generate the new function declaration. Const arguments are kept as is. Duplicated arguments must
633    // be pointers or references. Those receive a shadow argument, which is a mutable reference/pointer.
634    // Active arguments must be scalars. Their shadow argument is added to the return type (and will be
635    // zero-initialized by Enzyme).
636    // Each argument of the primal function (and the return type if existing) must be annotated with an
637    // activity.
638    //
639    // Error handling: If the user provides an invalid configuration (incorrect numbers, types, or
640    // both), we emit an error and return the original signature. This allows us to continue parsing.
641    // FIXME(Sa4dUs): make individual activities' span available so errors
642    // can point to only the activity instead of the entire attribute
643    fn gen_enzyme_decl(
644        ecx: &ExtCtxt<'_>,
645        sig: &ast::FnSig,
646        x: &RustcAutodiff,
647        span: Span,
648    ) -> ast::FnSig {
649        let dcx = ecx.sess.dcx();
650        let has_ret = has_ret(&sig.decl.output);
651        let sig_args = sig.decl.inputs.len() + if has_ret { 1 } else { 0 };
652        let num_activities = x.input_activity.len() + if x.has_ret_activity() { 1 } else { 0 };
653        if sig_args != num_activities {
654            dcx.emit_err(diagnostics::AutoDiffInvalidNumberActivities {
655                span,
656                expected: sig_args,
657                found: num_activities,
658            });
659            // This is not the right signature, but we can continue parsing.
660            return sig.clone();
661        }
662        if !(sig.decl.inputs.len() == x.input_activity.len()) {
    ::core::panicking::panic("assertion failed: sig.decl.inputs.len() == x.input_activity.len()")
};assert!(sig.decl.inputs.len() == x.input_activity.len());
663        if !(has_ret == x.has_ret_activity()) {
    ::core::panicking::panic("assertion failed: has_ret == x.has_ret_activity()")
};assert!(has_ret == x.has_ret_activity());
664        let mut d_decl = sig.decl.clone();
665        let mut d_inputs = Vec::new();
666        let mut new_inputs = Vec::new();
667        let mut idents = Vec::new();
668        let mut act_ret = ThinVec::new();
669
670        // We have two loops, a first one just to check the activities and types and possibly report
671        // multiple errors in one compilation session.
672        let mut errors = false;
673        for (arg, activity) in sig.decl.inputs.iter().zip(x.input_activity.iter()) {
674            if !valid_input_activity(x.mode, *activity) {
675                dcx.emit_err(diagnostics::AutoDiffInvalidApplicationModeAct {
676                    span,
677                    mode: x.mode.to_string(),
678                    act: activity.to_string(),
679                });
680                errors = true;
681            }
682            if !valid_ty_for_activity(&arg.ty, *activity) {
683                dcx.emit_err(diagnostics::AutoDiffInvalidTypeForActivity {
684                    span: arg.ty.span,
685                    act: activity.to_string(),
686                });
687                errors = true;
688            }
689        }
690
691        if has_ret && !valid_ret_activity(x.mode, x.ret_activity) {
692            dcx.emit_err(diagnostics::AutoDiffInvalidRetAct {
693                span,
694                mode: x.mode.to_string(),
695                act: x.ret_activity.to_string(),
696            });
697            // We don't set `errors = true` to avoid annoying type errors relative
698            // to the expanded macro type signature
699        }
700
701        if errors {
702            // This is not the right signature, but we can continue parsing.
703            return sig.clone();
704        }
705
706        let unsafe_activities = x
707            .input_activity
708            .iter()
709            .any(|&act| #[allow(non_exhaustive_omitted_patterns)] match act {
    DiffActivity::DuplicatedOnly | DiffActivity::DualOnly => true,
    _ => false,
}matches!(act, DiffActivity::DuplicatedOnly | DiffActivity::DualOnly));
710        for (arg, activity) in sig.decl.inputs.iter().zip(x.input_activity.iter()) {
711            d_inputs.push(arg.clone());
712            match activity {
713                DiffActivity::Active => {
714                    act_ret.push(arg.ty.clone());
715                    // if width =/= 1, then push [arg.ty; width] to act_ret
716                }
717                DiffActivity::ActiveOnly => {
718                    // We will add the active scalar to the return type.
719                    // This is handled later.
720                }
721                DiffActivity::Duplicated | DiffActivity::DuplicatedOnly => {
722                    for i in 0..x.width {
723                        let mut shadow_arg = arg.clone();
724                        // We += into the shadow in reverse mode.
725                        shadow_arg.ty = Box::new(assure_mut_ref(&arg.ty));
726                        let old_name = if let PatKind::Ident(_, ident, _) = arg.pat.kind {
727                            ident.name
728                        } else {
729                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_builtin_macros/src/autodiff.rs:729",
                        "rustc_builtin_macros::autodiff::llvm_enzyme",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_builtin_macros/src/autodiff.rs"),
                        ::tracing_core::__macro_support::Option::Some(729u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_builtin_macros::autodiff::llvm_enzyme"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0:#?}",
                                                    &shadow_arg.pat) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("{:#?}", &shadow_arg.pat);
730                            { ::core::panicking::panic_fmt(format_args!("not an ident?")); };panic!("not an ident?");
731                        };
732                        let name: String = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("d{0}_{1}", old_name, i))
    })format!("d{}_{}", old_name, i);
733                        new_inputs.push(name.clone());
734                        let ident = Ident::from_str_and_span(&name, shadow_arg.pat.span);
735                        shadow_arg.pat = Box::new(ast::Pat {
736                            id: ast::DUMMY_NODE_ID,
737                            kind: PatKind::Ident(BindingMode::NONE, ident, None),
738                            span: shadow_arg.pat.span,
739                        });
740                        d_inputs.push(shadow_arg.clone());
741                    }
742                }
743                DiffActivity::Dual
744                | DiffActivity::DualOnly
745                | DiffActivity::Dualv
746                | DiffActivity::DualvOnly => {
747                    // the *v variants get lowered to enzyme_dupv and enzyme_dupnoneedv, which cause
748                    // Enzyme to not expect N arguments, but one argument (which is instead larger).
749                    let iterations =
750                        if #[allow(non_exhaustive_omitted_patterns)] match activity {
    DiffActivity::Dualv | DiffActivity::DualvOnly => true,
    _ => false,
}matches!(activity, DiffActivity::Dualv | DiffActivity::DualvOnly) {
751                            1
752                        } else {
753                            x.width
754                        };
755                    for i in 0..iterations {
756                        let mut shadow_arg = arg.clone();
757                        let old_name = if let PatKind::Ident(_, ident, _) = arg.pat.kind {
758                            ident.name
759                        } else {
760                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_builtin_macros/src/autodiff.rs:760",
                        "rustc_builtin_macros::autodiff::llvm_enzyme",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_builtin_macros/src/autodiff.rs"),
                        ::tracing_core::__macro_support::Option::Some(760u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_builtin_macros::autodiff::llvm_enzyme"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0:#?}",
                                                    &shadow_arg.pat) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("{:#?}", &shadow_arg.pat);
761                            { ::core::panicking::panic_fmt(format_args!("not an ident?")); };panic!("not an ident?");
762                        };
763                        let name: String = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("b{0}_{1}", old_name, i))
    })format!("b{}_{}", old_name, i);
764                        new_inputs.push(name.clone());
765                        let ident = Ident::from_str_and_span(&name, shadow_arg.pat.span);
766                        shadow_arg.pat = Box::new(ast::Pat {
767                            id: ast::DUMMY_NODE_ID,
768                            kind: PatKind::Ident(BindingMode::NONE, ident, None),
769                            span: shadow_arg.pat.span,
770                        });
771                        d_inputs.push(shadow_arg.clone());
772                    }
773                }
774                DiffActivity::Const => {
775                    // Nothing to do here.
776                }
777                DiffActivity::None | DiffActivity::FakeActivitySize(_) => {
778                    { ::core::panicking::panic_fmt(format_args!("Should not happen")); };panic!("Should not happen");
779                }
780            }
781            if let PatKind::Ident(_, ident, _) = arg.pat.kind {
782                idents.push(ident.clone());
783            } else {
784                { ::core::panicking::panic_fmt(format_args!("not an ident?")); };panic!("not an ident?");
785            }
786        }
787
788        let active_only_ret = x.ret_activity == DiffActivity::ActiveOnly;
789        if active_only_ret {
790            if !x.mode.is_rev() {
    ::core::panicking::panic("assertion failed: x.mode.is_rev()")
};assert!(x.mode.is_rev());
791        }
792
793        // If we return a scalar in the primal and the scalar is active,
794        // then add it as last arg to the inputs.
795        if x.mode.is_rev() {
796            match x.ret_activity {
797                DiffActivity::Active | DiffActivity::ActiveOnly => {
798                    let ty = match d_decl.output {
799                        FnRetTy::Ty(ref ty) => ty.clone(),
800                        FnRetTy::Default(span) => {
801                            {
    ::core::panicking::panic_fmt(format_args!("Did not expect Default ret ty: {0:?}",
            span));
};panic!("Did not expect Default ret ty: {:?}", span);
802                        }
803                    };
804                    let name = "dret".to_string();
805                    let ident = Ident::from_str_and_span(&name, ty.span);
806                    let shadow_arg = ast::Param {
807                        attrs: ThinVec::new(),
808                        ty: ty.clone(),
809                        pat: Box::new(ast::Pat {
810                            id: ast::DUMMY_NODE_ID,
811                            kind: PatKind::Ident(BindingMode::NONE, ident, None),
812                            span: ty.span,
813                        }),
814                        id: ast::DUMMY_NODE_ID,
815                        span: ty.span,
816                        is_placeholder: false,
817                    };
818                    d_inputs.push(shadow_arg);
819                    new_inputs.push(name);
820                }
821                _ => {}
822            }
823        }
824        d_decl.inputs = d_inputs.into();
825
826        if x.mode.is_fwd() {
827            let ty = match d_decl.output {
828                FnRetTy::Ty(ref ty) => ty.clone(),
829                FnRetTy::Default(span) => {
830                    // We want to return std::hint::black_box(()).
831                    let kind = TyKind::Tup(ThinVec::new());
832                    let ty = Box::new(rustc_ast::Ty { kind, id: ast::DUMMY_NODE_ID, span });
833                    d_decl.output = FnRetTy::Ty(ty.clone());
834                    if !#[allow(non_exhaustive_omitted_patterns)] match x.ret_activity {
            DiffActivity::None => true,
            _ => false,
        } {
    ::core::panicking::panic("assertion failed: matches!(x.ret_activity, DiffActivity::None)")
};assert!(matches!(x.ret_activity, DiffActivity::None));
835                    // this won't be used below, so any type would be fine.
836                    ty
837                }
838            };
839
840            if #[allow(non_exhaustive_omitted_patterns)] match x.ret_activity {
    DiffActivity::Dual | DiffActivity::Dualv => true,
    _ => false,
}matches!(x.ret_activity, DiffActivity::Dual | DiffActivity::Dualv) {
841                let kind = if x.width == 1 || #[allow(non_exhaustive_omitted_patterns)] match x.ret_activity {
    DiffActivity::Dualv => true,
    _ => false,
}matches!(x.ret_activity, DiffActivity::Dualv) {
842                    // Dual can only be used for f32/f64 ret.
843                    // In that case we return now a tuple with two floats.
844                    TyKind::Tup({
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(ty.clone());
    vec.push(ty.clone());
    vec
}thin_vec![ty.clone(), ty.clone()])
845                } else {
846                    // We have to return [T; width+1], +1 for the primal return.
847                    let anon_const = rustc_ast::AnonConst {
848                        id: ast::DUMMY_NODE_ID,
849                        value: ecx.expr_usize(span, 1 + x.width as usize),
850                    };
851                    TyKind::Array(ty.clone(), anon_const)
852                };
853                let ty = Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span });
854                d_decl.output = FnRetTy::Ty(ty);
855            }
856            if #[allow(non_exhaustive_omitted_patterns)] match x.ret_activity {
    DiffActivity::DualOnly | DiffActivity::DualvOnly => true,
    _ => false,
}matches!(x.ret_activity, DiffActivity::DualOnly | DiffActivity::DualvOnly) {
857                // No need to change the return type,
858                // we will just return the shadow in place of the primal return.
859                // However, if we have a width > 1, then we don't return -> T, but -> [T; width]
860                if x.width > 1 {
861                    let anon_const = rustc_ast::AnonConst {
862                        id: ast::DUMMY_NODE_ID,
863                        value: ecx.expr_usize(span, x.width as usize),
864                    };
865                    let kind = TyKind::Array(ty.clone(), anon_const);
866                    let ty = Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span });
867                    d_decl.output = FnRetTy::Ty(ty);
868                }
869            }
870        }
871
872        // If we use ActiveOnly, drop the original return value.
873        d_decl.output =
874            if active_only_ret { FnRetTy::Default(span) } else { d_decl.output.clone() };
875
876        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_builtin_macros/src/autodiff.rs:876",
                        "rustc_builtin_macros::autodiff::llvm_enzyme",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_builtin_macros/src/autodiff.rs"),
                        ::tracing_core::__macro_support::Option::Some(876u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_builtin_macros::autodiff::llvm_enzyme"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("act_ret: {0:?}",
                                                    act_ret) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("act_ret: {:?}", act_ret);
877
878        // If we have an active input scalar, add it's gradient to the
879        // return type. This might require changing the return type to a
880        // tuple.
881        if act_ret.len() > 0 {
882            let ret_ty = match d_decl.output {
883                FnRetTy::Ty(ref ty) => {
884                    if !active_only_ret {
885                        act_ret.insert(0, ty.clone());
886                    }
887                    let kind = TyKind::Tup(act_ret);
888                    Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span })
889                }
890                FnRetTy::Default(span) => {
891                    if act_ret.len() == 1 {
892                        act_ret[0].clone()
893                    } else {
894                        let kind = TyKind::Tup(act_ret.iter().map(|arg| arg.clone()).collect());
895                        Box::new(rustc_ast::Ty { kind, id: ast::DUMMY_NODE_ID, span })
896                    }
897                }
898            };
899            d_decl.output = FnRetTy::Ty(ret_ty);
900        }
901
902        let mut d_header = sig.header.clone();
903        if unsafe_activities {
904            d_header.safety = rustc_ast::Safety::Unsafe(span);
905        }
906        let d_sig = FnSig { header: d_header, decl: d_decl, span };
907        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_builtin_macros/src/autodiff.rs:907",
                        "rustc_builtin_macros::autodiff::llvm_enzyme",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_builtin_macros/src/autodiff.rs"),
                        ::tracing_core::__macro_support::Option::Some(907u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_builtin_macros::autodiff::llvm_enzyme"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Generated signature: {0:?}",
                                                    d_sig) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("Generated signature: {:?}", d_sig);
908        d_sig
909    }
910}
911
912pub(crate) use llvm_enzyme::{expand_forward, expand_reverse};