rustc_codegen_llvm/builder/
autodiff.rs

1use std::ptr;
2
3use rustc_ast::expand::autodiff_attrs::{AutoDiffAttrs, AutoDiffItem, DiffActivity, DiffMode};
4use rustc_codegen_ssa::ModuleCodegen;
5use rustc_codegen_ssa::back::write::ModuleConfig;
6use rustc_codegen_ssa::traits::BaseTypeCodegenMethods as _;
7use rustc_errors::FatalError;
8use tracing::{debug, trace};
9
10use crate::back::write::llvm_err;
11use crate::builder::SBuilder;
12use crate::context::SimpleCx;
13use crate::declare::declare_simple_fn;
14use crate::errors::{AutoDiffWithoutEnable, LlvmError};
15use crate::llvm::AttributePlace::Function;
16use crate::llvm::{Metadata, True};
17use crate::value::Value;
18use crate::{CodegenContext, LlvmCodegenBackend, ModuleLlvm, attributes, llvm};
19
20fn get_params(fnc: &Value) -> Vec<&Value> {
21    unsafe {
22        let param_num = llvm::LLVMCountParams(fnc) as usize;
23        let mut fnc_args: Vec<&Value> = vec![];
24        fnc_args.reserve(param_num);
25        llvm::LLVMGetParams(fnc, fnc_args.as_mut_ptr());
26        fnc_args.set_len(param_num);
27        fnc_args
28    }
29}
30
31/// When differentiating `fn_to_diff`, take a `outer_fn` and generate another
32/// function with expected naming and calling conventions[^1] which will be
33/// discovered by the enzyme LLVM pass and its body populated with the differentiated
34/// `fn_to_diff`. `outer_fn` is then modified to have a call to the generated
35/// function and handle the differences between the Rust calling convention and
36/// Enzyme.
37/// [^1]: <https://enzyme.mit.edu/getting_started/CallingConvention/>
38// FIXME(ZuseZ4): `outer_fn` should include upstream safety checks to
39// cover some assumptions of enzyme/autodiff, which could lead to UB otherwise.
40fn generate_enzyme_call<'ll>(
41    cx: &SimpleCx<'ll>,
42    fn_to_diff: &'ll Value,
43    outer_fn: &'ll Value,
44    attrs: AutoDiffAttrs,
45) {
46    let inputs = attrs.input_activity;
47    let output = attrs.ret_activity;
48
49    // We have to pick the name depending on whether we want forward or reverse mode autodiff.
50    let mut ad_name: String = match attrs.mode {
51        DiffMode::Forward => "__enzyme_fwddiff",
52        DiffMode::Reverse => "__enzyme_autodiff",
53        _ => panic!("logic bug in autodiff, unrecognized mode"),
54    }
55    .to_string();
56
57    // add outer_fn name to ad_name to make it unique, in case users apply autodiff to multiple
58    // functions. Unwrap will only panic, if LLVM gave us an invalid string.
59    let name = llvm::get_value_name(outer_fn);
60    let outer_fn_name = std::str::from_utf8(name).unwrap();
61    ad_name.push_str(outer_fn_name);
62
63    // Let us assume the user wrote the following function square:
64    //
65    // ```llvm
66    // define double @square(double %x) {
67    // entry:
68    //  %0 = fmul double %x, %x
69    //  ret double %0
70    // }
71    // ```
72    //
73    // The user now applies autodiff to the function square, in which case fn_to_diff will be `square`.
74    // Our macro generates the following placeholder code (slightly simplified):
75    //
76    // ```llvm
77    // define double @dsquare(double %x) {
78    //  ; placeholder code
79    //  return 0.0;
80    // }
81    // ```
82    //
83    // so our `outer_fn` will be `dsquare`. The unsafe code section below now removes the placeholder
84    // code and inserts an autodiff call. We also add a declaration for the __enzyme_autodiff call.
85    // Again, the arguments to all functions are slightly simplified.
86    // ```llvm
87    // declare double @__enzyme_autodiff_square(...)
88    //
89    // define double @dsquare(double %x) {
90    // entry:
91    //   %0 = tail call double (...) @__enzyme_autodiff_square(double (double)* nonnull @square, double %x)
92    //   ret double %0
93    // }
94    // ```
95    unsafe {
96        // On LLVM-IR, we can luckily declare __enzyme_ functions without specifying the input
97        // arguments. We do however need to declare them with their correct return type.
98        // We already figured the correct return type out in our frontend, when generating the outer_fn,
99        // so we can now just go ahead and use that. FIXME(ZuseZ4): This doesn't handle sret yet.
100        let fn_ty = llvm::LLVMGlobalGetValueType(outer_fn);
101        let ret_ty = llvm::LLVMGetReturnType(fn_ty);
102
103        // LLVM can figure out the input types on it's own, so we take a shortcut here.
104        let enzyme_ty = llvm::LLVMFunctionType(ret_ty, ptr::null(), 0, True);
105
106        //FIXME(ZuseZ4): the CC/Addr/Vis values are best effort guesses, we should look at tests and
107        // think a bit more about what should go here.
108        let cc = llvm::LLVMGetFunctionCallConv(outer_fn);
109        let ad_fn = declare_simple_fn(
110            cx,
111            &ad_name,
112            llvm::CallConv::try_from(cc).expect("invalid callconv"),
113            llvm::UnnamedAddr::No,
114            llvm::Visibility::Default,
115            enzyme_ty,
116        );
117
118        // Otherwise LLVM might inline our temporary code before the enzyme pass has a chance to
119        // do it's work.
120        let attr = llvm::AttributeKind::NoInline.create_attr(cx.llcx);
121        attributes::apply_to_llfn(ad_fn, Function, &[attr]);
122
123        // first, remove all calls from fnc
124        let entry = llvm::LLVMGetFirstBasicBlock(outer_fn);
125        let br = llvm::LLVMRustGetTerminator(entry);
126        llvm::LLVMRustEraseInstFromParent(br);
127
128        let last_inst = llvm::LLVMRustGetLastInstruction(entry).unwrap();
129        let mut builder = SBuilder::build(cx, entry);
130
131        let num_args = llvm::LLVMCountParams(&fn_to_diff);
132        let mut args = Vec::with_capacity(num_args as usize + 1);
133        args.push(fn_to_diff);
134
135        let enzyme_const = cx.create_metadata("enzyme_const".to_string()).unwrap();
136        let enzyme_out = cx.create_metadata("enzyme_out".to_string()).unwrap();
137        let enzyme_dup = cx.create_metadata("enzyme_dup".to_string()).unwrap();
138        let enzyme_dupnoneed = cx.create_metadata("enzyme_dupnoneed".to_string()).unwrap();
139        let enzyme_primal_ret = cx.create_metadata("enzyme_primal_return".to_string()).unwrap();
140
141        match output {
142            DiffActivity::Dual => {
143                args.push(cx.get_metadata_value(enzyme_primal_ret));
144            }
145            DiffActivity::Active => {
146                args.push(cx.get_metadata_value(enzyme_primal_ret));
147            }
148            _ => {}
149        }
150
151        debug!("matching autodiff arguments");
152        // We now handle the issue that Rust level arguments not always match the llvm-ir level
153        // arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
154        // llvm-ir level. The number of activities matches the number of Rust level arguments, so we
155        // need to match those.
156        // FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
157        // using iterators and peek()?
158        let mut outer_pos: usize = 0;
159        let mut activity_pos = 0;
160        let outer_args: Vec<&llvm::Value> = get_params(outer_fn);
161        while activity_pos < inputs.len() {
162            let diff_activity = inputs[activity_pos as usize];
163            // Duplicated arguments received a shadow argument, into which enzyme will write the
164            // gradient.
165            let (activity, duplicated): (&Metadata, bool) = match diff_activity {
166                DiffActivity::None => panic!("not a valid input activity"),
167                DiffActivity::Const => (enzyme_const, false),
168                DiffActivity::Active => (enzyme_out, false),
169                DiffActivity::ActiveOnly => (enzyme_out, false),
170                DiffActivity::Dual => (enzyme_dup, true),
171                DiffActivity::DualOnly => (enzyme_dupnoneed, true),
172                DiffActivity::Duplicated => (enzyme_dup, true),
173                DiffActivity::DuplicatedOnly => (enzyme_dupnoneed, true),
174                DiffActivity::FakeActivitySize => (enzyme_const, false),
175            };
176            let outer_arg = outer_args[outer_pos];
177            args.push(cx.get_metadata_value(activity));
178            args.push(outer_arg);
179            if duplicated {
180                // We know that duplicated args by construction have a following argument,
181                // so this can not be out of bounds.
182                let next_outer_arg = outer_args[outer_pos + 1];
183                let next_outer_ty = cx.val_ty(next_outer_arg);
184                // FIXME(ZuseZ4): We should add support for Vec here too, but it's less urgent since
185                // vectors behind references (&Vec<T>) are already supported. Users can not pass a
186                // Vec by value for reverse mode, so this would only help forward mode autodiff.
187                let slice = {
188                    if activity_pos + 1 >= inputs.len() {
189                        // If there is no arg following our ptr, it also can't be a slice,
190                        // since that would lead to a ptr, int pair.
191                        false
192                    } else {
193                        let next_activity = inputs[activity_pos + 1];
194                        // We analyze the MIR types and add this dummy activity if we visit a slice.
195                        next_activity == DiffActivity::FakeActivitySize
196                    }
197                };
198                if slice {
199                    // A duplicated slice will have the following two outer_fn arguments:
200                    // (..., ptr1, int1, ptr2, int2, ...). We add the following llvm-ir to our __enzyme call:
201                    // (..., metadata! enzyme_dup, ptr, ptr, int1, ...).
202                    // FIXME(ZuseZ4): We will upstream a safety check later which asserts that
203                    // int2 >= int1, which means the shadow vector is large enough to store the gradient.
204                    assert!(llvm::LLVMRustGetTypeKind(next_outer_ty) == llvm::TypeKind::Integer);
205                    let next_outer_arg2 = outer_args[outer_pos + 2];
206                    let next_outer_ty2 = cx.val_ty(next_outer_arg2);
207                    assert!(llvm::LLVMRustGetTypeKind(next_outer_ty2) == llvm::TypeKind::Pointer);
208                    let next_outer_arg3 = outer_args[outer_pos + 3];
209                    let next_outer_ty3 = cx.val_ty(next_outer_arg3);
210                    assert!(llvm::LLVMRustGetTypeKind(next_outer_ty3) == llvm::TypeKind::Integer);
211                    args.push(next_outer_arg2);
212                    args.push(cx.get_metadata_value(enzyme_const));
213                    args.push(next_outer_arg);
214                    outer_pos += 4;
215                    activity_pos += 2;
216                } else {
217                    // A duplicated pointer will have the following two outer_fn arguments:
218                    // (..., ptr, ptr, ...). We add the following llvm-ir to our __enzyme call:
219                    // (..., metadata! enzyme_dup, ptr, ptr, ...).
220                    if matches!(
221                        diff_activity,
222                        DiffActivity::Duplicated | DiffActivity::DuplicatedOnly
223                    ) {
224                        assert!(
225                            llvm::LLVMRustGetTypeKind(next_outer_ty) == llvm::TypeKind::Pointer
226                        );
227                    }
228                    // In the case of Dual we don't have assumptions, e.g. f32 would be valid.
229                    args.push(next_outer_arg);
230                    outer_pos += 2;
231                    activity_pos += 1;
232                }
233            } else {
234                // We do not differentiate with resprect to this argument.
235                // We already added the metadata and argument above, so just increase the counters.
236                outer_pos += 1;
237                activity_pos += 1;
238            }
239        }
240
241        let call = builder.call(enzyme_ty, ad_fn, &args, None);
242
243        // This part is a bit iffy. LLVM requires that a call to an inlineable function has some
244        // metadata attachted to it, but we just created this code oota. Given that the
245        // differentiated function already has partly confusing metadata, and given that this
246        // affects nothing but the auttodiff IR, we take a shortcut and just steal metadata from the
247        // dummy code which we inserted at a higher level.
248        // FIXME(ZuseZ4): Work with Enzyme core devs to clarify what debug metadata issues we have,
249        // and how to best improve it for enzyme core and rust-enzyme.
250        let md_ty = cx.get_md_kind_id("dbg");
251        if llvm::LLVMRustHasMetadata(last_inst, md_ty) {
252            let md = llvm::LLVMRustDIGetInstMetadata(last_inst)
253                .expect("failed to get instruction metadata");
254            let md_todiff = cx.get_metadata_value(md);
255            llvm::LLVMSetMetadata(call, md_ty, md_todiff);
256        } else {
257            // We don't panic, since depending on whether we are in debug or release mode, we might
258            // have no debug info to copy, which would then be ok.
259            trace!("no dbg info");
260        }
261
262        // Now that we copied the metadata, get rid of dummy code.
263        llvm::LLVMRustEraseInstUntilInclusive(entry, last_inst);
264
265        if cx.val_ty(call) == cx.type_void() {
266            builder.ret_void();
267        } else {
268            builder.ret(call);
269        }
270
271        // Let's crash in case that we messed something up above and generated invalid IR.
272        llvm::LLVMRustVerifyFunction(
273            outer_fn,
274            llvm::LLVMRustVerifierFailureAction::LLVMAbortProcessAction,
275        );
276    }
277}
278
279pub(crate) fn differentiate<'ll>(
280    module: &'ll ModuleCodegen<ModuleLlvm>,
281    cgcx: &CodegenContext<LlvmCodegenBackend>,
282    diff_items: Vec<AutoDiffItem>,
283    _config: &ModuleConfig,
284) -> Result<(), FatalError> {
285    for item in &diff_items {
286        trace!("{}", item);
287    }
288
289    let diag_handler = cgcx.create_dcx();
290
291    let cx = SimpleCx::new(module.module_llvm.llmod(), module.module_llvm.llcx, cgcx.pointer_size);
292
293    // First of all, did the user try to use autodiff without using the -Zautodiff=Enable flag?
294    if !diff_items.is_empty()
295        && !cgcx.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::Enable)
296    {
297        let dcx = cgcx.create_dcx();
298        return Err(dcx.handle().emit_almost_fatal(AutoDiffWithoutEnable));
299    }
300
301    // Before dumping the module, we want all the TypeTrees to become part of the module.
302    for item in diff_items.iter() {
303        let name = item.source.clone();
304        let fn_def: Option<&llvm::Value> = cx.get_function(&name);
305        let Some(fn_def) = fn_def else {
306            return Err(llvm_err(
307                diag_handler.handle(),
308                LlvmError::PrepareAutoDiff {
309                    src: item.source.clone(),
310                    target: item.target.clone(),
311                    error: "could not find source function".to_owned(),
312                },
313            ));
314        };
315        debug!(?item.target);
316        let fn_target: Option<&llvm::Value> = cx.get_function(&item.target);
317        let Some(fn_target) = fn_target else {
318            return Err(llvm_err(
319                diag_handler.handle(),
320                LlvmError::PrepareAutoDiff {
321                    src: item.source.clone(),
322                    target: item.target.clone(),
323                    error: "could not find target function".to_owned(),
324                },
325            ));
326        };
327
328        generate_enzyme_call(&cx, fn_def, fn_target, item.attrs.clone());
329    }
330
331    // FIXME(ZuseZ4): support SanitizeHWAddress and prevent illegal/unsupported opts
332
333    trace!("done with differentiate()");
334
335    Ok(())
336}