1use std::ptr;
23use rustc_ast::expand::autodiff_attrs::{DiffActivity, DiffMode};
4use rustc_ast::expand::typetree::FncTree;
5use rustc_attr_ir::RustcAutodiff;
6use rustc_codegen_ssa::common::TypeKind;
7use rustc_codegen_ssa::mir::IntrinsicResult;
8use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
9use rustc_codegen_ssa::mir::place::PlaceValue;
10use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, BuilderMethods, ReturnSlot};
11use rustc_data_structures::thin_vec::ThinVec;
12use rustc_middle::ty;
13use rustc_middle::ty::{Ty, TyCtxt, TypingEnv};
14use rustc_span::bug;
15use rustc_target::callconv::PassMode;
16use tracing::debug;
1718use crate::builder::{Builder, UNNAMED};
19use crate::context::SimpleCx;
20use crate::declare::declare_simple_fn;
21use crate::llvm::{self, TRUE, Type, Value};
2223pub(crate) fn adjust_activity_to_abi<'tcx>(
24 tcx: TyCtxt<'tcx>,
25 fn_ptr_ty: Ty<'tcx>,
26 typing_env: TypingEnv<'tcx>,
27 da: &mut ThinVec<DiffActivity>,
28) {
29if !#[allow(non_exhaustive_omitted_patterns)] match fn_ptr_ty.kind() {
ty::FnPtr(..) => true,
_ => false,
}matches!(fn_ptr_ty.kind(), ty::FnPtr(..)) {
30::rustc_span::macros::bug_impl(None,
format_args!("expected fn ptr for autodiff, got {0:?}", fn_ptr_ty),
Location::caller());bug!("expected fn ptr for autodiff, got {:?}", fn_ptr_ty);
31 }
3233// We don't actually pass the types back into the type system.
34 // All we do is decide how to handle the arguments.
35let fn_sig = fn_ptr_ty.fn_sig(tcx);
36let sig = fn_sig.skip_binder();
3738// FIXME(Sa4dUs): pass proper varargs once we have support for differentiating variadic functions
39let Ok(fn_abi) = tcx.fn_abi_of_fn_ptr(typing_env.as_query_input((fn_sig, ty::List::empty())))
40else {
41::rustc_span::macros::bug_impl(None,
format_args!("failed to get fn_abi of fn_ptr with empty varargs"),
Location::caller());bug!("failed to get fn_abi of fn_ptr with empty varargs");
42 };
4344let mut new_activities = ::alloc::vec::Vec::new()vec![];
45let mut new_positions = ::alloc::vec::Vec::new()vec![];
46let mut del_activities = 0;
47for (i, ty) in sig.inputs().iter().enumerate() {
48if let Some(inner_ty) = ty.builtin_deref(true) {
49let tail_ty = tcx.struct_tail_for_codegen(inner_ty, typing_env);
50if let ty::Slice(element_ty) = tail_ty.kind() {
51// Now we need to figure out the size of each slice element in memory to allow
52 // safety checks and usability improvements in the backend.
5354let layout = tcx.layout_of(typing_env.as_query_input(*element_ty));
55let elem_size = match layout {
56Ok(layout) => layout.size,
57Err(_) => {
58::rustc_span::macros::bug_impl(None,
format_args!("autodiff failed to compute slice element size"),
Location::caller());bug!("autodiff failed to compute slice element size");
59 }
60 };
61let elem_size: u32 = elem_size.bytes() as u32;
6263// We know that the length will be passed as extra arg.
64if !da.is_empty() {
65// We are looking at a slice. The length of that slice will become an
66 // extra integer on llvm level. Integers are always const.
67 // However, if the slice get's duplicated, we want to know to later check the
68 // size. So we mark the new size argument as FakeActivitySize.
69 // There is one FakeActivitySize per slice, so for convenience we store the
70 // slice element size in bytes in it. We will use the size in the backend.
71let activity = match da[i] {
72 DiffActivity::DualOnly
73 | DiffActivity::Dual
74 | DiffActivity::Dualv
75 | DiffActivity::DuplicatedOnly
76 | DiffActivity::Duplicated => {
77 DiffActivity::FakeActivitySize(Some(elem_size))
78 }
79 DiffActivity::Const => DiffActivity::Const,
80_ => ::rustc_span::macros::bug_impl(None,
format_args!("unexpected activity for ptr/ref"), Location::caller())bug!("unexpected activity for ptr/ref"),
81 };
82 new_activities.push(activity);
83 new_positions.push(i + 1);
84 }
8586continue;
87 }
88 }
8990let layout = match tcx.layout_of(typing_env.as_query_input(*ty)) {
91Ok(layout) => layout.layout,
92Err(_) => {
93::rustc_span::macros::bug_impl(None,
format_args!("failed to compute layout for type {0:?}", ty),
Location::caller());bug!("failed to compute layout for type {:?}", ty);
94 }
95 };
9697let pass_mode = &fn_abi.args[i].mode;
9899// For ZST, just ignore and don't add its activity, as this arg won't be present
100 // in the LLVM passed to Enzyme.
101 // Some targets pass ZST indirectly in the C ABI, in that case, handle it as a normal arg
102 // FIXME(Sa4dUs): Enforce ZST corresponding diff activity be `Const`
103if *pass_mode == PassMode::Ignore {
104 del_activities += 1;
105 da.remove(i);
106 }
107108// If the argument is lowered as a `ScalarPair`, we need to duplicate its activity.
109 // Otherwise, the number of activities won't match the number of LLVM arguments and
110 // this will lead to errors when verifying the Enzyme call.
111if let rustc_abi::BackendRepr::ScalarPair { a: _, b: _, b_offset: _ } =
112 layout.backend_repr()
113 {
114 new_activities.push(da[i].clone());
115 new_positions.push(i + 1 - del_activities);
116 }
117 }
118// now add the extra activities coming from slices
119 // Reverse order to not invalidate the indices
120for _ in 0..new_activities.len() {
121let pos = new_positions.pop().unwrap();
122let activity = new_activities.pop().unwrap();
123 da.insert(pos, activity);
124 }
125}
126127// When we call the `__enzyme_autodiff` or `__enzyme_fwddiff` function, we need to pass all the
128// original inputs, as well as metadata and the additional shadow arguments.
129// This function matches the arguments from the outer function to the inner enzyme call.
130//
131// This function also considers that Rust level arguments not always match the llvm-ir level
132// arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
133// llvm-ir level. The number of activities matches the number of Rust level arguments, so we
134// need to match those.
135// FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
136// using iterators and peek()?
137fn match_args_from_caller_to_enzyme<'ll, 'tcx>(
138 builder: &mut Builder<'_, 'll, 'tcx>,
139 width: u32,
140 args: &mut Vec<&'ll Value>,
141 inputs: &[DiffActivity],
142 outer_args: &[&'ll Value],
143) {
144{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/builder/autodiff.rs:144",
"rustc_codegen_llvm::builder::autodiff",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/builder/autodiff.rs"),
::tracing_core::__macro_support::Option::Some(144u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder::autodiff"),
::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!("matching autodiff arguments")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("matching autodiff arguments");
145// We now handle the issue that Rust level arguments not always match the llvm-ir level
146 // arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
147 // llvm-ir level. The number of activities matches the number of Rust level arguments, so we
148 // need to match those.
149 // FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
150 // using iterators and peek()?
151let cx = &builder.scx;
152let mut outer_pos: usize = 0;
153let mut activity_pos = 0;
154155// We used to use llvm's metadata to instruct enzyme how to differentiate a function.
156 // In debug mode we would use incremental compilation which caused the metadata to be
157 // dropped. This is prevented by now using named globals, which are also understood
158 // by Enzyme.
159let global_const = cx.declare_global("enzyme_const", cx.type_ptr());
160let global_out = cx.declare_global("enzyme_out", cx.type_ptr());
161let global_dup = cx.declare_global("enzyme_dup", cx.type_ptr());
162let global_dupv = cx.declare_global("enzyme_dupv", cx.type_ptr());
163let global_dupnoneed = cx.declare_global("enzyme_dupnoneed", cx.type_ptr());
164let global_dupnoneedv = cx.declare_global("enzyme_dupnoneedv", cx.type_ptr());
165166while activity_pos < inputs.len() {
167let diff_activity = inputs[activity_pos as usize];
168// Duplicated arguments received a shadow argument, into which enzyme will write the
169 // gradient.
170let (activity, duplicated): (&Value, bool) = match diff_activity {
171 DiffActivity::None => { ::core::panicking::panic_fmt(format_args!("not a valid input activity")); }panic!("not a valid input activity"),
172 DiffActivity::Const => (global_const, false),
173 DiffActivity::Active => (global_out, false),
174 DiffActivity::ActiveOnly => (global_out, false),
175 DiffActivity::Dual => (global_dup, true),
176 DiffActivity::Dualv => (global_dupv, true),
177 DiffActivity::DualOnly => (global_dupnoneed, true),
178 DiffActivity::DualvOnly => (global_dupnoneedv, true),
179 DiffActivity::Duplicated => (global_dup, true),
180 DiffActivity::DuplicatedOnly => (global_dupnoneed, true),
181 DiffActivity::FakeActivitySize(_) => (global_const, false),
182 };
183let outer_arg = outer_args[outer_pos];
184 args.push(activity);
185if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
DiffActivity::Dualv => true,
_ => false,
}matches!(diff_activity, DiffActivity::Dualv) {
186let next_outer_arg = outer_args[outer_pos + 1];
187let elem_bytes_size: u64 = match inputs[activity_pos + 1] {
188 DiffActivity::FakeActivitySize(Some(s)) => s.into(),
189_ => ::rustc_span::macros::bug_impl(None,
format_args!("incorrect Dualv handling recognized."), Location::caller())bug!("incorrect Dualv handling recognized."),
190 };
191// stride: sizeof(T) * n_elems.
192 // n_elems is the next integer.
193 // Now we multiply `4 * next_outer_arg` to get the stride.
194let mul = unsafe {
195 llvm::LLVMBuildMul(
196 builder.llbuilder,
197 cx.get_const_int(cx.type_i64(), elem_bytes_size),
198 next_outer_arg,
199 UNNAMED,
200 )
201 };
202 args.push(mul);
203 }
204 args.push(outer_arg);
205if duplicated {
206// We know that duplicated args by construction have a following argument,
207 // so this can not be out of bounds.
208let next_outer_arg = outer_args[outer_pos + 1];
209let next_outer_ty = cx.val_ty(next_outer_arg);
210// FIXME(ZuseZ4): We should add support for Vec here too, but it's less urgent since
211 // vectors behind references (&Vec<T>) are already supported. Users can not pass a
212 // Vec by value for reverse mode, so this would only help forward mode autodiff.
213let slice = {
214if activity_pos + 1 >= inputs.len() {
215// If there is no arg following our ptr, it also can't be a slice,
216 // since that would lead to a ptr, int pair.
217false
218} else {
219let next_activity = inputs[activity_pos + 1];
220// We analyze the MIR types and add this dummy activity if we visit a slice.
221#[allow(non_exhaustive_omitted_patterns)] match next_activity {
DiffActivity::FakeActivitySize(_) => true,
_ => false,
}matches!(next_activity, DiffActivity::FakeActivitySize(_))222 }
223 };
224if slice {
225// A duplicated slice will have the following two outer_fn arguments:
226 // (..., ptr1, int1, ptr2, int2, ...). We add the following llvm-ir to our __enzyme call:
227 // (..., metadata! enzyme_dup, ptr, ptr, int1, ...).
228 // FIXME(ZuseZ4): We will upstream a safety check later which asserts that
229 // int2 >= int1, which means the shadow vector is large enough to store the gradient.
230{
match (&cx.type_kind(next_outer_ty), &TypeKind::Integer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(cx.type_kind(next_outer_ty), TypeKind::Integer);
231232let iterations =
233if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
DiffActivity::Dualv => true,
_ => false,
}matches!(diff_activity, DiffActivity::Dualv) { 1 } else { width as usize };
234235for i in 0..iterations {
236let next_outer_arg2 = outer_args[outer_pos + 2 * (i + 1)];
237let next_outer_ty2 = cx.val_ty(next_outer_arg2);
238{
match (&cx.type_kind(next_outer_ty2), &TypeKind::Pointer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(cx.type_kind(next_outer_ty2), TypeKind::Pointer);
239let next_outer_arg3 = outer_args[outer_pos + 2 * (i + 1) + 1];
240let next_outer_ty3 = cx.val_ty(next_outer_arg3);
241{
match (&cx.type_kind(next_outer_ty3), &TypeKind::Integer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(cx.type_kind(next_outer_ty3), TypeKind::Integer);
242 args.push(next_outer_arg2);
243 }
244 args.push(global_const);
245 args.push(next_outer_arg);
246 outer_pos += 2 + 2 * iterations;
247 activity_pos += 2;
248 } else {
249// A duplicated pointer will have the following two outer_fn arguments:
250 // (..., ptr, ptr, ...). We add the following llvm-ir to our __enzyme call:
251 // (..., metadata! enzyme_dup, ptr, ptr, ...).
252if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
DiffActivity::Duplicated | DiffActivity::DuplicatedOnly => true,
_ => false,
}matches!(diff_activity, DiffActivity::Duplicated | DiffActivity::DuplicatedOnly)253 {
254{
match (&cx.type_kind(next_outer_ty), &TypeKind::Pointer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(cx.type_kind(next_outer_ty), TypeKind::Pointer);
255 }
256// In the case of Dual we don't have assumptions, e.g. f32 would be valid.
257args.push(next_outer_arg);
258 outer_pos += 2;
259 activity_pos += 1;
260261// Now, if width > 1, we need to account for that
262for _ in 1..width {
263let next_outer_arg = outer_args[outer_pos];
264 args.push(next_outer_arg);
265 outer_pos += 1;
266 }
267 }
268 } else {
269// We do not differentiate with resprect to this argument.
270 // We already added the metadata and argument above, so just increase the counters.
271outer_pos += 1;
272 activity_pos += 1;
273 }
274 }
275}
276277/// When differentiating `fn_to_diff`, take a `outer_fn` and generate another
278/// function with expected naming and calling conventions[^1] which will be
279/// discovered by the enzyme LLVM pass and its body populated with the differentiated
280/// `fn_to_diff`. `outer_fn` is then modified to have a call to the generated
281/// function and handle the differences between the Rust calling convention and
282/// Enzyme.
283/// [^1]: <https://enzyme.mit.edu/getting_started/CallingConvention/>
284// FIXME(ZuseZ4): `outer_fn` should include upstream safety checks to
285// cover some assumptions of enzyme/autodiff, which could lead to UB otherwise.
286pub(crate) fn generate_enzyme_call<'ll, 'tcx>(
287 bx: &mut Builder<'_, 'll, 'tcx>,
288 fn_to_diff: &'ll Value,
289 outer_name: &str,
290 ret_ty: &'ll Type,
291 fn_args: &[&'ll Value],
292 attrs: &RustcAutodiff,
293 dest_layout: ty::layout::TyAndLayout<'tcx>,
294 dest_place: Option<PlaceValue<&'ll Value>>,
295 fnc_tree: FncTree,
296) -> IntrinsicResult<'tcx, &'ll Value> {
297let cx: &SimpleCx<'ll> = &bx.scx;
298// We have to pick the name depending on whether we want forward or reverse mode autodiff.
299let mut ad_name: String = match attrs.mode {
300 DiffMode::Forward => "__enzyme_fwddiff",
301 DiffMode::Reverse => "__enzyme_autodiff",
302_ => {
::core::panicking::panic_fmt(format_args!("logic bug in autodiff, unrecognized mode"));
}panic!("logic bug in autodiff, unrecognized mode"),
303 }
304 .to_string();
305306// add outer_name to ad_name to make it unique, in case users apply autodiff to multiple
307 // functions. Unwrap will only panic, if LLVM gave us an invalid string.
308ad_name.push_str(outer_name);
309310// Let us assume the user wrote the following function square:
311 //
312 // ```llvm
313 // define double @square(double %x) {
314 // entry:
315 // %0 = fmul double %x, %x
316 // ret double %0
317 // }
318 //
319 // define double @dsquare(double %x) {
320 // return 0.0;
321 // }
322 // ```
323 //
324 // so our `outer_fn` will be `dsquare`. The unsafe code section below now removes the placeholder
325 // code and inserts an autodiff call. We also add a declaration for the __enzyme_autodiff call.
326 // Again, the arguments to all functions are slightly simplified.
327 // ```llvm
328 // declare double @__enzyme_autodiff_square(...)
329 //
330 // define double @dsquare(double %x) {
331 // entry:
332 // %0 = tail call double (...) @__enzyme_autodiff_square(double (double)* nonnull @square, double %x)
333 // ret double %0
334 // }
335 // ```
336let enzyme_ty = unsafe { llvm::LLVMFunctionType(ret_ty, ptr::null(), 0, TRUE) };
337338// FIXME(ZuseZ4): the CC/Addr/Vis values are best effort guesses, we should look at tests and
339 // think a bit more about what should go here.
340let cc = unsafe { llvm::LLVMGetFunctionCallConv(fn_to_diff) };
341let ad_fn = declare_simple_fn(
342cx,
343&ad_name,
344 llvm::CallConv::try_from(cc).expect("invalid callconv"),
345 llvm::UnnamedAddr::No,
346 llvm::Visibility::Default,
347enzyme_ty,
348 );
349350let num_args = llvm::LLVMCountParams(&fn_to_diff);
351let mut args = Vec::with_capacity(num_argsas usize + 1);
352args.push(fn_to_diff);
353354let global_primal_ret = cx.declare_global("enzyme_primal_return", cx.type_ptr());
355if #[allow(non_exhaustive_omitted_patterns)] match attrs.ret_activity {
DiffActivity::Dual | DiffActivity::Active => true,
_ => false,
}matches!(attrs.ret_activity, DiffActivity::Dual | DiffActivity::Active) {
356args.push(global_primal_ret);
357 }
358if attrs.width > 1 {
359let global_width = cx.declare_global("enzyme_width", cx.type_ptr());
360args.push(global_width);
361args.push(cx.get_const_int(cx.type_i64(), attrs.width as u64));
362 }
363364match_args_from_caller_to_enzyme(bx, attrs.width, &mut args, &attrs.input_activity, fn_args);
365366if !fnc_tree.args.is_empty() || !fnc_tree.ret.0.is_empty() {
367crate::typetree::add_tt(&bx, fn_to_diff, fnc_tree);
368 }
369370let call = bx.call(enzyme_ty, None, None, ad_fn, ReturnSlot::Direct, &args, None, None);
371372let fn_ret_ty = bx.cx.val_ty(call);
373if fn_ret_ty == bx.cx.type_void() || fn_ret_ty == bx.cx.type_struct(&[], false) {
374// If we return void or an empty struct, then our caller (due to how we generated it)
375 // does not expect a return value. As such, we have no pointer (or place) into which
376 // we could store our value, and would store into an undef, which would cause UB.
377 // As such, we just ignore the return value in those cases.
378IntrinsicResult::Operand(OperandValue::ZeroSized)
379 } else if let Some(dest_place) = dest_place {
380bx.store_to_place(call, dest_place);
381 IntrinsicResult::WroteIntoPlace382 } else {
383 IntrinsicResult::Operand(
384OperandRef::from_immediate_or_packed_pair(bx, call, dest_layout).val,
385 )
386 }
387}