Skip to main content

rustc_builtin_macros/
offload.rs

1use rustc_ast::ast;
2use rustc_ast::token::{Delimiter, IdentKind, Token, TokenKind};
3use rustc_ast::tokenstream::{DelimSpan, Spacing, TokenStream, TokenTree};
4use rustc_expand::base::{Annotatable, ExtCtxt};
5use rustc_session::config::Offload;
6use rustc_span::{DUMMY_SP, Ident, Span, sym};
7use thin_vec::thin_vec;
8
9use crate::diagnostics;
10
11fn compile_for_device(ecx: &mut ExtCtxt<'_>) -> bool {
12    ecx.sess.opts.unstable_opts.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    Offload::Device(_) => true,
    _ => false,
}matches!(o, Offload::Device(_)))
13}
14
15fn outer_normal_attr(normal: &Box<ast::NormalAttr>, id: ast::AttrId, span: Span) -> ast::Attribute {
16    let style = ast::AttrStyle::Outer;
17    let kind = ast::AttrKind::Normal(normal.clone());
18    ast::Attribute { kind, id, style, span }
19}
20
21fn extract_fn(
22    item: &Annotatable,
23) -> Option<(ast::Visibility, ast::FnSig, Ident, ast::Generics, Option<Box<ast::Block>>)> {
24    match item {
25        Annotatable::Item(iitem) => match &iitem.kind {
26            ast::ItemKind::Fn(ast::Fn { sig, ident, generics, body, .. }) => {
27                Some((iitem.vis.clone(), sig.clone(), *ident, generics.clone(), body.clone()))
28            }
29            _ => None,
30        },
31        _ => None,
32    }
33}
34
35/// The `offload_kernel` macro expands the function into two separate definitions:
36/// one on the host to handle the call, and one on the device for executing the kernel.
37///
38/// ```
39/// #[offload_kernel]
40/// fn foo(a: &[f32], b: &[f32], c: *mut f32) {
41///     *c = a[0] + b[0];
42/// }
43/// ```
44///
45/// This expands to the host-side function:
46///
47/// ```
48/// #[inline(never)]
49/// fn foo(_: &[f32], _: &[f32], _: *mut f32) {
50///     ::core::panicking::panic("not implemented")
51/// }
52/// ```
53///
54/// And the device-side kernel:
55///
56/// ```
57/// #[rustc_offload_kernel]
58/// unsafe extern "gpu-kernel" fn foo(a: &[f32], b: &[f32], c: *mut f32) {
59///     *c = a[0] + b[0];
60/// }
61/// ```
62pub(crate) fn expand_kernel(
63    ecx: &mut ExtCtxt<'_>,
64    expand_span: Span,
65    _meta_item: &ast::MetaItem,
66    item: Annotatable,
67) -> Vec<Annotatable> {
68    let dcx = ecx.sess.dcx();
69
70    let Some((vis, sig, ident, generics, body)) = extract_fn(&item) else {
71        dcx.emit_err(diagnostics::AutoDiffInvalidApplication { span: item.span() });
72        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
73    };
74
75    let span = ecx.with_def_site_ctxt(expand_span);
76
77    // device function
78    let mut device_fn = ecx.item_fn(sig.clone(), ident, generics.clone(), body);
79
80    let extern_gpu_kernel = ast::Extern::from_abi(
81        Some(ast::StrLit {
82            symbol: sym::gpu_kernel,
83            suffix: None,
84            symbol_unescaped: sym::gpu_kernel,
85            style: ast::StrStyle::Cooked,
86            span,
87        }),
88        span,
89    );
90    device_fn.sig.header.ext = extern_gpu_kernel;
91    device_fn.sig.header.safety = ast::Safety::Unsafe(span);
92
93    // rustc_offload_kernel attr
94    let rustc_offload_kernel_attr =
95        Box::new(ast::NormalAttr::from_ident(Ident::with_dummy_span(sym::rustc_offload_kernel)));
96    let rustc_offload_kernel = outer_normal_attr(
97        &rustc_offload_kernel_attr,
98        ecx.sess.psess.attr_id_generator.mk_attr_id(),
99        span,
100    );
101
102    let device_item = {
103        let mut item =
104            ecx.item(span, {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(rustc_offload_kernel.clone());
    vec
}thin_vec![rustc_offload_kernel.clone()], ast::ItemKind::Fn(device_fn));
105        item.vis = vis.clone();
106        Annotatable::Item(item)
107    };
108
109    // unimplemented! body
110    let macro_expr = ecx.expr_macro_call(
111        span,
112        ecx.macro_call(
113            span,
114            ecx.std_path(span, &[sym::unimplemented]),
115            Delimiter::Parenthesis,
116            TokenStream::default(),
117        ),
118    );
119    let stmt = ecx.stmt_expr(macro_expr);
120    let body = ecx.block(span, {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(stmt);
    vec
}thin_vec![stmt]);
121
122    // host function
123    let mut host_fn = ecx.item_fn(sig, ident, generics, Some(body));
124
125    for param in host_fn.sig.decl.inputs.iter_mut() {
126        *param.pat = ecx.pat_wild(param.pat.span);
127    }
128
129    // inline(never) attr
130    let ts = ::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,
                            IdentKind::Normal), span), Spacing::Joint)]))vec![TokenTree::Token(
131        Token::new(TokenKind::Ident(sym::never, IdentKind::Normal), span),
132        Spacing::Joint,
133    )];
134
135    let never_arg = ast::DelimArgs {
136        dspan: DelimSpan::from_single(span),
137        delim: Delimiter::Parenthesis,
138        tokens: TokenStream::from_iter(ts),
139    };
140
141    let inline_item = ast::AttrItem {
142        unsafety: ast::Safety::Default,
143        path: ast::Path::from_ident(Ident::with_dummy_span(sym::inline)),
144        args: ast::AttrArgs::Delimited(never_arg),
145        span: DUMMY_SP,
146    };
147    let inline_never_attr = Box::new(ast::NormalAttr { item: inline_item, tokens: None });
148
149    let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id();
150    let inline_never = outer_normal_attr(&inline_never_attr, new_id, span);
151
152    let host_item = {
153        let mut item = ecx.item(
154            span,
155            {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(rustc_offload_kernel);
    vec.push(inline_never);
    vec
}thin_vec![rustc_offload_kernel, inline_never],
156            ast::ItemKind::Fn(host_fn),
157        );
158        item.vis = vis;
159        Annotatable::Item(item)
160    };
161
162    if compile_for_device(ecx) { ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [device_item]))vec![device_item] } else { ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [host_item]))vec![host_item] }
163}