rustc_codegen_llvm/builder/
autodiff.rs

1use std::ptr;
2
3use rustc_ast::expand::autodiff_attrs::{AutoDiffAttrs, DiffActivity, DiffMode};
4use rustc_ast::expand::typetree::FncTree;
5use rustc_codegen_ssa::common::TypeKind;
6use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, BuilderMethods};
7use rustc_middle::ty::{Instance, PseudoCanonicalInput, TyCtxt, TypingEnv};
8use rustc_middle::{bug, ty};
9use rustc_target::callconv::PassMode;
10use tracing::debug;
11
12use crate::builder::{Builder, PlaceRef, UNNAMED};
13use crate::context::SimpleCx;
14use crate::declare::declare_simple_fn;
15use crate::llvm;
16use crate::llvm::{Metadata, TRUE, Type};
17use crate::value::Value;
18
19pub(crate) fn adjust_activity_to_abi<'tcx>(
20    tcx: TyCtxt<'tcx>,
21    instance: Instance<'tcx>,
22    typing_env: TypingEnv<'tcx>,
23    da: &mut Vec<DiffActivity>,
24) {
25    let fn_ty = instance.ty(tcx, typing_env);
26
27    if !matches!(fn_ty.kind(), ty::FnDef(..)) {
28        bug!("expected fn def for autodiff, got {:?}", fn_ty);
29    }
30
31    // We don't actually pass the types back into the type system.
32    // All we do is decide how to handle the arguments.
33    let sig = fn_ty.fn_sig(tcx).skip_binder();
34
35    // FIXME(Sa4dUs): pass proper varargs once we have support for differentiating variadic functions
36    let Ok(fn_abi) =
37        tcx.fn_abi_of_instance(typing_env.as_query_input((instance, ty::List::empty())))
38    else {
39        bug!("failed to get fn_abi of instance with empty varargs");
40    };
41
42    let mut new_activities = vec![];
43    let mut new_positions = vec![];
44    let mut del_activities = 0;
45    for (i, ty) in sig.inputs().iter().enumerate() {
46        if let Some(inner_ty) = ty.builtin_deref(true) {
47            if inner_ty.is_slice() {
48                // Now we need to figure out the size of each slice element in memory to allow
49                // safety checks and usability improvements in the backend.
50                let sty = match inner_ty.builtin_index() {
51                    Some(sty) => sty,
52                    None => {
53                        panic!("slice element type unknown");
54                    }
55                };
56                let pci = PseudoCanonicalInput {
57                    typing_env: TypingEnv::fully_monomorphized(),
58                    value: sty,
59                };
60
61                let layout = tcx.layout_of(pci);
62                let elem_size = match layout {
63                    Ok(layout) => layout.size,
64                    Err(_) => {
65                        bug!("autodiff failed to compute slice element size");
66                    }
67                };
68                let elem_size: u32 = elem_size.bytes() as u32;
69
70                // We know that the length will be passed as extra arg.
71                if !da.is_empty() {
72                    // We are looking at a slice. The length of that slice will become an
73                    // extra integer on llvm level. Integers are always const.
74                    // However, if the slice get's duplicated, we want to know to later check the
75                    // size. So we mark the new size argument as FakeActivitySize.
76                    // There is one FakeActivitySize per slice, so for convenience we store the
77                    // slice element size in bytes in it. We will use the size in the backend.
78                    let activity = match da[i] {
79                        DiffActivity::DualOnly
80                        | DiffActivity::Dual
81                        | DiffActivity::Dualv
82                        | DiffActivity::DuplicatedOnly
83                        | DiffActivity::Duplicated => {
84                            DiffActivity::FakeActivitySize(Some(elem_size))
85                        }
86                        DiffActivity::Const => DiffActivity::Const,
87                        _ => bug!("unexpected activity for ptr/ref"),
88                    };
89                    new_activities.push(activity);
90                    new_positions.push(i + 1);
91                }
92
93                continue;
94            }
95        }
96
97        let pci = PseudoCanonicalInput { typing_env: TypingEnv::fully_monomorphized(), value: *ty };
98
99        let layout = match tcx.layout_of(pci) {
100            Ok(layout) => layout.layout,
101            Err(_) => {
102                bug!("failed to compute layout for type {:?}", ty);
103            }
104        };
105
106        let pass_mode = &fn_abi.args[i].mode;
107
108        // For ZST, just ignore and don't add its activity, as this arg won't be present
109        // in the LLVM passed to Enzyme.
110        // Some targets pass ZST indirectly in the C ABI, in that case, handle it as a normal arg
111        // FIXME(Sa4dUs): Enforce ZST corresponding diff activity be `Const`
112        if *pass_mode == PassMode::Ignore {
113            del_activities += 1;
114            da.remove(i);
115        }
116
117        // If the argument is lowered as a `ScalarPair`, we need to duplicate its activity.
118        // Otherwise, the number of activities won't match the number of LLVM arguments and
119        // this will lead to errors when verifying the Enzyme call.
120        if let rustc_abi::BackendRepr::ScalarPair(_, _) = layout.backend_repr() {
121            new_activities.push(da[i].clone());
122            new_positions.push(i + 1 - del_activities);
123        }
124    }
125    // now add the extra activities coming from slices
126    // Reverse order to not invalidate the indices
127    for _ in 0..new_activities.len() {
128        let pos = new_positions.pop().unwrap();
129        let activity = new_activities.pop().unwrap();
130        da.insert(pos, activity);
131    }
132}
133
134// When we call the `__enzyme_autodiff` or `__enzyme_fwddiff` function, we need to pass all the
135// original inputs, as well as metadata and the additional shadow arguments.
136// This function matches the arguments from the outer function to the inner enzyme call.
137//
138// This function also considers that Rust level arguments not always match the llvm-ir level
139// arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
140// llvm-ir level. The number of activities matches the number of Rust level arguments, so we
141// need to match those.
142// FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
143// using iterators and peek()?
144fn match_args_from_caller_to_enzyme<'ll, 'tcx>(
145    cx: &SimpleCx<'ll>,
146    builder: &mut Builder<'_, 'll, 'tcx>,
147    width: u32,
148    args: &mut Vec<&'ll llvm::Value>,
149    inputs: &[DiffActivity],
150    outer_args: &[&'ll llvm::Value],
151) {
152    debug!("matching autodiff arguments");
153    // We now handle the issue that Rust level arguments not always match the llvm-ir level
154    // arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
155    // llvm-ir level. The number of activities matches the number of Rust level arguments, so we
156    // need to match those.
157    // FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
158    // using iterators and peek()?
159    let mut outer_pos: usize = 0;
160    let mut activity_pos = 0;
161
162    let enzyme_const = cx.create_metadata(b"enzyme_const");
163    let enzyme_out = cx.create_metadata(b"enzyme_out");
164    let enzyme_dup = cx.create_metadata(b"enzyme_dup");
165    let enzyme_dupv = cx.create_metadata(b"enzyme_dupv");
166    let enzyme_dupnoneed = cx.create_metadata(b"enzyme_dupnoneed");
167    let enzyme_dupnoneedv = cx.create_metadata(b"enzyme_dupnoneedv");
168
169    while activity_pos < inputs.len() {
170        let diff_activity = inputs[activity_pos as usize];
171        // Duplicated arguments received a shadow argument, into which enzyme will write the
172        // gradient.
173        let (activity, duplicated): (&Metadata, bool) = match diff_activity {
174            DiffActivity::None => panic!("not a valid input activity"),
175            DiffActivity::Const => (enzyme_const, false),
176            DiffActivity::Active => (enzyme_out, false),
177            DiffActivity::ActiveOnly => (enzyme_out, false),
178            DiffActivity::Dual => (enzyme_dup, true),
179            DiffActivity::Dualv => (enzyme_dupv, true),
180            DiffActivity::DualOnly => (enzyme_dupnoneed, true),
181            DiffActivity::DualvOnly => (enzyme_dupnoneedv, true),
182            DiffActivity::Duplicated => (enzyme_dup, true),
183            DiffActivity::DuplicatedOnly => (enzyme_dupnoneed, true),
184            DiffActivity::FakeActivitySize(_) => (enzyme_const, false),
185        };
186        let outer_arg = outer_args[outer_pos];
187        args.push(cx.get_metadata_value(activity));
188        if matches!(diff_activity, DiffActivity::Dualv) {
189            let next_outer_arg = outer_args[outer_pos + 1];
190            let elem_bytes_size: u64 = match inputs[activity_pos + 1] {
191                DiffActivity::FakeActivitySize(Some(s)) => s.into(),
192                _ => bug!("incorrect Dualv handling recognized."),
193            };
194            // stride: sizeof(T) * n_elems.
195            // n_elems is the next integer.
196            // Now we multiply `4 * next_outer_arg` to get the stride.
197            let mul = unsafe {
198                llvm::LLVMBuildMul(
199                    builder.llbuilder,
200                    cx.get_const_int(cx.type_i64(), elem_bytes_size),
201                    next_outer_arg,
202                    UNNAMED,
203                )
204            };
205            args.push(mul);
206        }
207        args.push(outer_arg);
208        if duplicated {
209            // We know that duplicated args by construction have a following argument,
210            // so this can not be out of bounds.
211            let next_outer_arg = outer_args[outer_pos + 1];
212            let next_outer_ty = cx.val_ty(next_outer_arg);
213            // FIXME(ZuseZ4): We should add support for Vec here too, but it's less urgent since
214            // vectors behind references (&Vec<T>) are already supported. Users can not pass a
215            // Vec by value for reverse mode, so this would only help forward mode autodiff.
216            let slice = {
217                if activity_pos + 1 >= inputs.len() {
218                    // If there is no arg following our ptr, it also can't be a slice,
219                    // since that would lead to a ptr, int pair.
220                    false
221                } else {
222                    let next_activity = inputs[activity_pos + 1];
223                    // We analyze the MIR types and add this dummy activity if we visit a slice.
224                    matches!(next_activity, DiffActivity::FakeActivitySize(_))
225                }
226            };
227            if slice {
228                // A duplicated slice will have the following two outer_fn arguments:
229                // (..., ptr1, int1, ptr2, int2, ...). We add the following llvm-ir to our __enzyme call:
230                // (..., metadata! enzyme_dup, ptr, ptr, int1, ...).
231                // FIXME(ZuseZ4): We will upstream a safety check later which asserts that
232                // int2 >= int1, which means the shadow vector is large enough to store the gradient.
233                assert_eq!(cx.type_kind(next_outer_ty), TypeKind::Integer);
234
235                let iterations =
236                    if matches!(diff_activity, DiffActivity::Dualv) { 1 } else { width as usize };
237
238                for i in 0..iterations {
239                    let next_outer_arg2 = outer_args[outer_pos + 2 * (i + 1)];
240                    let next_outer_ty2 = cx.val_ty(next_outer_arg2);
241                    assert_eq!(cx.type_kind(next_outer_ty2), TypeKind::Pointer);
242                    let next_outer_arg3 = outer_args[outer_pos + 2 * (i + 1) + 1];
243                    let next_outer_ty3 = cx.val_ty(next_outer_arg3);
244                    assert_eq!(cx.type_kind(next_outer_ty3), TypeKind::Integer);
245                    args.push(next_outer_arg2);
246                }
247                args.push(cx.get_metadata_value(enzyme_const));
248                args.push(next_outer_arg);
249                outer_pos += 2 + 2 * iterations;
250                activity_pos += 2;
251            } else {
252                // A duplicated pointer will have the following two outer_fn arguments:
253                // (..., ptr, ptr, ...). We add the following llvm-ir to our __enzyme call:
254                // (..., metadata! enzyme_dup, ptr, ptr, ...).
255                if matches!(diff_activity, DiffActivity::Duplicated | DiffActivity::DuplicatedOnly)
256                {
257                    assert_eq!(cx.type_kind(next_outer_ty), TypeKind::Pointer);
258                }
259                // In the case of Dual we don't have assumptions, e.g. f32 would be valid.
260                args.push(next_outer_arg);
261                outer_pos += 2;
262                activity_pos += 1;
263
264                // Now, if width > 1, we need to account for that
265                for _ in 1..width {
266                    let next_outer_arg = outer_args[outer_pos];
267                    args.push(next_outer_arg);
268                    outer_pos += 1;
269                }
270            }
271        } else {
272            // We do not differentiate with resprect to this argument.
273            // We already added the metadata and argument above, so just increase the counters.
274            outer_pos += 1;
275            activity_pos += 1;
276        }
277    }
278}
279
280/// When differentiating `fn_to_diff`, take a `outer_fn` and generate another
281/// function with expected naming and calling conventions[^1] which will be
282/// discovered by the enzyme LLVM pass and its body populated with the differentiated
283/// `fn_to_diff`. `outer_fn` is then modified to have a call to the generated
284/// function and handle the differences between the Rust calling convention and
285/// Enzyme.
286/// [^1]: <https://enzyme.mit.edu/getting_started/CallingConvention/>
287// FIXME(ZuseZ4): `outer_fn` should include upstream safety checks to
288// cover some assumptions of enzyme/autodiff, which could lead to UB otherwise.
289pub(crate) fn generate_enzyme_call<'ll, 'tcx>(
290    builder: &mut Builder<'_, 'll, 'tcx>,
291    cx: &SimpleCx<'ll>,
292    fn_to_diff: &'ll Value,
293    outer_name: &str,
294    ret_ty: &'ll Type,
295    fn_args: &[&'ll Value],
296    attrs: AutoDiffAttrs,
297    dest: PlaceRef<'tcx, &'ll Value>,
298    fnc_tree: FncTree,
299) {
300    // We have to pick the name depending on whether we want forward or reverse mode autodiff.
301    let mut ad_name: String = match attrs.mode {
302        DiffMode::Forward => "__enzyme_fwddiff",
303        DiffMode::Reverse => "__enzyme_autodiff",
304        _ => panic!("logic bug in autodiff, unrecognized mode"),
305    }
306    .to_string();
307
308    // add outer_name to ad_name to make it unique, in case users apply autodiff to multiple
309    // functions. Unwrap will only panic, if LLVM gave us an invalid string.
310    ad_name.push_str(outer_name);
311
312    // Let us assume the user wrote the following function square:
313    //
314    // ```llvm
315    // define double @square(double %x) {
316    // entry:
317    //  %0 = fmul double %x, %x
318    //  ret double %0
319    // }
320    //
321    // define double @dsquare(double %x) {
322    //  return 0.0;
323    // }
324    // ```
325    //
326    // so our `outer_fn` will be `dsquare`. The unsafe code section below now removes the placeholder
327    // code and inserts an autodiff call. We also add a declaration for the __enzyme_autodiff call.
328    // Again, the arguments to all functions are slightly simplified.
329    // ```llvm
330    // declare double @__enzyme_autodiff_square(...)
331    //
332    // define double @dsquare(double %x) {
333    // entry:
334    //   %0 = tail call double (...) @__enzyme_autodiff_square(double (double)* nonnull @square, double %x)
335    //   ret double %0
336    // }
337    // ```
338    let enzyme_ty = unsafe { llvm::LLVMFunctionType(ret_ty, ptr::null(), 0, TRUE) };
339
340    // FIXME(ZuseZ4): the CC/Addr/Vis values are best effort guesses, we should look at tests and
341    // think a bit more about what should go here.
342    let cc = unsafe { llvm::LLVMGetFunctionCallConv(fn_to_diff) };
343    let ad_fn = declare_simple_fn(
344        cx,
345        &ad_name,
346        llvm::CallConv::try_from(cc).expect("invalid callconv"),
347        llvm::UnnamedAddr::No,
348        llvm::Visibility::Default,
349        enzyme_ty,
350    );
351
352    let num_args = llvm::LLVMCountParams(&fn_to_diff);
353    let mut args = Vec::with_capacity(num_args as usize + 1);
354    args.push(fn_to_diff);
355
356    let enzyme_primal_ret = cx.create_metadata(b"enzyme_primal_return");
357    if matches!(attrs.ret_activity, DiffActivity::Dual | DiffActivity::Active) {
358        args.push(cx.get_metadata_value(enzyme_primal_ret));
359    }
360    if attrs.width > 1 {
361        let enzyme_width = cx.create_metadata(b"enzyme_width");
362        args.push(cx.get_metadata_value(enzyme_width));
363        args.push(cx.get_const_int(cx.type_i64(), attrs.width as u64));
364    }
365
366    match_args_from_caller_to_enzyme(
367        &cx,
368        builder,
369        attrs.width,
370        &mut args,
371        &attrs.input_activity,
372        fn_args,
373    );
374
375    if !fnc_tree.args.is_empty() || !fnc_tree.ret.0.is_empty() {
376        crate::typetree::add_tt(cx.llmod, cx.llcx, fn_to_diff, fnc_tree);
377    }
378
379    let call = builder.call(enzyme_ty, None, None, ad_fn, &args, None, None);
380
381    builder.store_to_place(call, dest.val);
382}