Skip to content

Commit 75c0091

Browse files
committed
Fix typetree generation for arguments, like slices and re-enable their generation for memcpy.
This moves a TA failure in the testcase from memcpy to a later location.
1 parent b4486ca commit 75c0091

12 files changed

Lines changed: 287 additions & 78 deletions

File tree

‎compiler/rustc_ast/src/expand/typetree.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ pub enum Kind {
2828
Anything,
2929
Integer,
3030
Pointer,
31+
// We prefer to directly lower to things that our Enzyme backend supports.
32+
// However, it's sometimes convenient to pass ptr+int as one type.
33+
RustSlice,
3134
Half,
3235
Float,
3336
Double,
@@ -57,6 +60,9 @@ impl TypeTree {
5760
}
5861
Self(ints)
5962
}
63+
pub fn add_indirection(self) -> Self {
64+
Self(vec![Type { offset: 0, size: 1, kind: Kind::Pointer, child: self }])
65+
}
6066
}
6167

6268
#[derive(Clone, Eq, PartialEq, Encodable, Decodable, Debug, StableHash)]

‎compiler/rustc_codegen_llvm/src/builder.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1175,7 +1175,7 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
11751175
// vs. copying a struct with mixed types requires different derivative handling.
11761176
// The TypeTree tells Enzyme exactly what memory layout to expect.
11771177
if let Some(tt) = tt {
1178-
crate::typetree::add_tt(self.cx().llmod, self.cx().llcx, memcpy, tt);
1178+
crate::typetree::add_tt(self.cx().llmod, self.cx().llcx, self.cx().tcx, memcpy, tt);
11791179
}
11801180
}
11811181

‎compiler/rustc_codegen_llvm/src/builder/autodiff.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,7 @@ fn match_args_from_caller_to_enzyme<'ll, 'tcx>(
293293
// cover some assumptions of enzyme/autodiff, which could lead to UB otherwise.
294294
pub(crate) fn generate_enzyme_call<'ll, 'tcx>(
295295
builder: &mut Builder<'_, 'll, 'tcx>,
296+
tcx: TyCtxt<'tcx>,
296297
cx: &SimpleCx<'ll>,
297298
fn_to_diff: &'ll Value,
298299
outer_name: &str,
@@ -379,7 +380,7 @@ pub(crate) fn generate_enzyme_call<'ll, 'tcx>(
379380
);
380381

381382
if !fnc_tree.args.is_empty() || !fnc_tree.ret.0.is_empty() {
382-
crate::typetree::add_tt(cx.llmod, cx.llcx, fn_to_diff, fnc_tree);
383+
crate::typetree::add_tt(cx.llmod, cx.llcx, tcx, fn_to_diff, fnc_tree);
383384
}
384385

385386
let call = builder.call(enzyme_ty, None, None, ad_fn, &args, None, None);

‎compiler/rustc_codegen_llvm/src/intrinsic.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1807,6 +1807,7 @@ fn codegen_autodiff<'ll, 'tcx>(
18071807
// Build body
18081808
generate_enzyme_call(
18091809
bx,
1810+
tcx,
18101811
bx.cx,
18111812
fn_to_diff,
18121813
&diff_symbol,

‎compiler/rustc_codegen_llvm/src/llvm/enzyme_ffi.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ unsafe extern "C" {
6666
NameLen: libc::size_t,
6767
) -> Option<&Value>;
6868

69+
pub(crate) safe fn LLVMRustIsCall(V: &Value) -> bool;
6970
}
7071

7172
unsafe extern "C" {
@@ -292,6 +293,11 @@ pub(crate) mod Enzyme_AD {
292293
unsafe { (self.EnzymeTypeTreeToString)(tree) }
293294
}
294295

296+
pub(crate) fn tree_to_cstr(&self, tree: *mut EnzymeTypeTree) -> &std::ffi::CStr {
297+
let c_str = self.tree_to_string(tree);
298+
unsafe { std::ffi::CStr::from_ptr(c_str) }
299+
}
300+
295301
pub(crate) fn tree_to_string_free(&self, ch: *const c_char) {
296302
unsafe { (self.EnzymeTypeTreeToStringFree)(ch) }
297303
}

‎compiler/rustc_codegen_llvm/src/llvm/mod.rs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,21 @@ pub(crate) fn CreateAttrStringValue<'ll>(
7676
)
7777
}
7878
}
79+
pub(crate) fn CreateAttrStringValueFromCStr<'ll>(
80+
llcx: &'ll Context,
81+
attr: &std::ffi::CStr,
82+
value: &std::ffi::CStr,
83+
) -> &'ll Attribute {
84+
unsafe {
85+
LLVMCreateStringAttribute(
86+
llcx,
87+
(*attr).as_ptr(),
88+
(*attr).to_bytes().len() as c_uint,
89+
(*value).as_ptr(),
90+
(*value).to_bytes().len() as c_uint,
91+
)
92+
}
93+
}
7994

8095
pub(crate) fn CreateAttrString<'ll>(llcx: &'ll Context, attr: &str) -> &'ll Attribute {
8196
unsafe {
Lines changed: 117 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,47 @@
1-
use std::ffi::{CString, c_char, c_uint};
1+
use std::ffi::{CString, c_char};
22

3-
use rustc_ast::expand::typetree::{FncTree, TypeTree as RustTypeTree};
3+
use rustc_ast::expand::typetree::{FncTree, Kind, TypeTree as RustTypeTree};
4+
use rustc_middle::ty::TyCtxt;
45

56
use crate::attributes;
67
use crate::llvm::{self, EnzymeWrapper, Value};
78

89
fn to_enzyme_typetree(
9-
rust_typetree: RustTypeTree,
10+
rust_typetree: &RustTypeTree,
1011
_data_layout: &str,
1112
llcx: &llvm::Context,
12-
) -> llvm::TypeTree {
13+
) -> (llvm::TypeTree, Vec<llvm::TypeTree>) {
1314
let mut enzyme_tt = llvm::TypeTree::new();
14-
process_typetree_recursive(&mut enzyme_tt, &rust_typetree, &[], llcx);
15-
enzyme_tt
15+
let extra_ints = process_typetree_recursive(&mut enzyme_tt, &rust_typetree, &[], llcx);
16+
17+
let mut int_vec = vec![];
18+
for _ in 0..extra_ints {
19+
let mut int_tt = llvm::TypeTree::new();
20+
int_tt.insert(&[0], llvm::CConcreteType::DT_Integer, llcx);
21+
int_vec.push(int_tt);
22+
}
23+
24+
(enzyme_tt, int_vec)
1625
}
26+
1727
fn process_typetree_recursive(
1828
enzyme_tt: &mut llvm::TypeTree,
1929
rust_typetree: &RustTypeTree,
2030
parent_indices: &[i64],
2131
llcx: &llvm::Context,
22-
) {
32+
) -> u32 {
33+
let mut extra_ints = 0;
2334
for rust_type in &rust_typetree.0 {
2435
let concrete_type = match rust_type.kind {
25-
rustc_ast::expand::typetree::Kind::Anything => llvm::CConcreteType::DT_Anything,
26-
rustc_ast::expand::typetree::Kind::Integer => llvm::CConcreteType::DT_Integer,
27-
rustc_ast::expand::typetree::Kind::Pointer => llvm::CConcreteType::DT_Pointer,
28-
rustc_ast::expand::typetree::Kind::Half => llvm::CConcreteType::DT_Half,
29-
rustc_ast::expand::typetree::Kind::Float => llvm::CConcreteType::DT_Float,
30-
rustc_ast::expand::typetree::Kind::Double => llvm::CConcreteType::DT_Double,
31-
rustc_ast::expand::typetree::Kind::F128 => llvm::CConcreteType::DT_FP128,
32-
rustc_ast::expand::typetree::Kind::Unknown => llvm::CConcreteType::DT_Unknown,
36+
Kind::Anything => llvm::CConcreteType::DT_Anything,
37+
Kind::Integer => llvm::CConcreteType::DT_Integer,
38+
Kind::Pointer => llvm::CConcreteType::DT_Pointer,
39+
Kind::RustSlice => llvm::CConcreteType::DT_Pointer,
40+
Kind::Half => llvm::CConcreteType::DT_Half,
41+
Kind::Float => llvm::CConcreteType::DT_Float,
42+
Kind::Double => llvm::CConcreteType::DT_Double,
43+
Kind::F128 => llvm::CConcreteType::DT_FP128,
44+
Kind::Unknown => llvm::CConcreteType::DT_Unknown,
3345
};
3446

3547
let mut indices = parent_indices.to_vec();
@@ -43,18 +55,31 @@ fn process_typetree_recursive(
4355

4456
enzyme_tt.insert(&indices, concrete_type, llcx);
4557

46-
if rust_type.kind == rustc_ast::expand::typetree::Kind::Pointer
58+
if matches!(rust_type.kind, Kind::RustSlice) {
59+
// We lower slices to `ptr,int`, so add the int here.
60+
extra_ints += 1;
61+
}
62+
63+
if matches!(rust_type.kind, Kind::Pointer | Kind::RustSlice)
4764
&& !rust_type.child.0.is_empty()
4865
{
4966
process_typetree_recursive(enzyme_tt, &rust_type.child, &indices, llcx);
5067
}
5168
}
69+
extra_ints
70+
}
71+
72+
// Describes all the locations in which we know how to apply an Enzyme TypeTree.
73+
enum TTLocation {
74+
Definition,
75+
Callsite,
5276
}
5377

5478
#[cfg_attr(not(feature = "llvm_enzyme"), allow(unused))]
55-
pub(crate) fn add_tt<'ll>(
79+
pub(crate) fn add_tt<'tcx, 'll>(
5680
llmod: &'ll llvm::Module,
5781
llcx: &'ll llvm::Context,
82+
tcx: TyCtxt<'tcx>,
5883
fn_def: &'ll Value,
5984
tt: FncTree,
6085
) {
@@ -66,6 +91,13 @@ pub(crate) fn add_tt<'ll>(
6691
#[cfg(not(feature = "llvm_enzyme"))]
6792
return;
6893

94+
if !tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::Enable) {
95+
return;
96+
}
97+
if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
98+
return;
99+
}
100+
69101
let inputs = tt.args;
70102
let ret_tt: RustTypeTree = tt.ret;
71103

@@ -77,41 +109,81 @@ pub(crate) fn add_tt<'ll>(
77109
let attr_name = "enzyme_type";
78110
let c_attr_name = CString::new(attr_name).unwrap();
79111

112+
let tt_location: TTLocation =
113+
if llvm::LLVMRustIsCall(fn_def) { TTLocation::Callsite } else { TTLocation::Definition };
114+
115+
let mut offset = 0;
80116
for (i, input) in inputs.iter().enumerate() {
81-
unsafe {
82-
let enzyme_tt = to_enzyme_typetree(input.clone(), llvm_data_layout, llcx);
117+
let (enzyme_tt, extra_ints) = to_enzyme_typetree(&input, llvm_data_layout, llcx);
118+
119+
// This scope is just a visual reminder that we *must* drop the enzyme_wrapper before
120+
// we drop any typetrees (mainly enzyme_tt and extra_ints). Drop calls can not accept
121+
// arguments like an enzyme_wrapper, so the typetree drop impl has to call get_instance
122+
// on the static enzyme instance, which is behind a Mutex. Therefore we'd deadlock if we
123+
// hold the enzyme_wrapper while dropping the typetrees.
124+
{
83125
let enzyme_wrapper = EnzymeWrapper::get_instance();
84-
let c_str = enzyme_wrapper.tree_to_string(enzyme_tt.inner);
85-
let c_str = std::ffi::CStr::from_ptr(c_str);
86-
87-
let attr = llvm::LLVMCreateStringAttribute(
88-
llcx,
89-
c_attr_name.as_ptr(),
90-
c_attr_name.as_bytes().len() as c_uint,
91-
c_str.as_ptr(),
92-
c_str.to_bytes().len() as c_uint,
93-
);
94-
95-
attributes::apply_to_llfn(fn_def, llvm::AttributePlace::Argument(i as u32), &[attr]);
126+
let c_str = enzyme_wrapper.tree_to_cstr(enzyme_tt.inner);
127+
128+
let attr = llvm::CreateAttrStringValueFromCStr(llcx, &c_attr_name, &c_str);
129+
let arg_pos = llvm::AttributePlace::Argument(i as u32 + offset);
130+
// FIXME(autodiff): We currently know that this is correct for all the cases in which we
131+
// call this function. But we should make it more robust for the future.
132+
match tt_location {
133+
TTLocation::Definition => {
134+
attributes::apply_to_llfn(fn_def, arg_pos, &[attr]);
135+
}
136+
TTLocation::Callsite => {
137+
attributes::apply_to_callsite(fn_def, arg_pos, &[attr]);
138+
}
139+
}
96140
enzyme_wrapper.tree_to_string_free(c_str.as_ptr());
141+
for v in &extra_ints {
142+
offset += 1;
143+
let c_str = enzyme_wrapper.tree_to_cstr(v.inner);
144+
let int_attr = llvm::CreateAttrStringValueFromCStr(llcx, &c_attr_name, &c_str);
145+
let arg_pos = llvm::AttributePlace::Argument(i as u32 + offset);
146+
match tt_location {
147+
TTLocation::Definition => {
148+
attributes::apply_to_llfn(fn_def, arg_pos, &[int_attr]);
149+
}
150+
TTLocation::Callsite => {
151+
attributes::apply_to_callsite(fn_def, arg_pos, &[int_attr]);
152+
}
153+
}
154+
enzyme_wrapper.tree_to_string_free(c_str.as_ptr());
155+
}
156+
}
157+
}
158+
// We will only fail this if Rust types got lowered to LLVM in a way that we didn't predict.
159+
// Error, so we can learn from our mistakes.
160+
if matches!(tt_location, TTLocation::Definition) {
161+
let expected = offset as usize + inputs.len();
162+
let actual = llvm::count_params(fn_def) as usize;
163+
if expected != actual {
164+
tcx.dcx().warn(format!(
165+
"autodiff type-tree failure. We expected {expected} LLVM argument(s), \
166+
but the generated LLVM function has {actual} parameter(s)"
167+
));
97168
}
98169
}
99170

100-
unsafe {
101-
let enzyme_tt = to_enzyme_typetree(ret_tt, llvm_data_layout, llcx);
171+
// FIXME(autodiff): We should think more about what it means if a function returns a slice or
172+
// other fat ptrs.
173+
let (enzyme_tt, _extra_ints) = to_enzyme_typetree(&ret_tt, llvm_data_layout, llcx);
174+
if ret_tt != RustTypeTree::new() {
102175
let enzyme_wrapper = EnzymeWrapper::get_instance();
103-
let c_str = enzyme_wrapper.tree_to_string(enzyme_tt.inner);
104-
let c_str = std::ffi::CStr::from_ptr(c_str);
105-
106-
let ret_attr = llvm::LLVMCreateStringAttribute(
107-
llcx,
108-
c_attr_name.as_ptr(),
109-
c_attr_name.as_bytes().len() as c_uint,
110-
c_str.as_ptr(),
111-
c_str.to_bytes().len() as c_uint,
112-
);
113-
114-
attributes::apply_to_llfn(fn_def, llvm::AttributePlace::ReturnValue, &[ret_attr]);
176+
let c_str = enzyme_wrapper.tree_to_cstr(enzyme_tt.inner);
177+
let ret_attr = llvm::CreateAttrStringValueFromCStr(llcx, &c_attr_name, &c_str);
178+
let arg_pos = llvm::AttributePlace::ReturnValue;
179+
match tt_location {
180+
TTLocation::Definition => {
181+
attributes::apply_to_llfn(fn_def, arg_pos, &[ret_attr]);
182+
}
183+
TTLocation::Callsite => {
184+
attributes::apply_to_callsite(fn_def, arg_pos, &[ret_attr]);
185+
}
186+
}
115187
enzyme_wrapper.tree_to_string_free(c_str.as_ptr());
116188
}
117189
}

‎compiler/rustc_codegen_ssa/src/traits/builder.rs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@ use std::assert_matches;
22
use std::ops::Deref;
33

44
use rustc_abi::{Align, Scalar, Size, WrappingRange};
5+
use rustc_ast::expand::typetree::{FncTree, TypeTree};
56
use rustc_hir::attrs::AttributeKind;
67
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
78
use rustc_middle::mir;
89
use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, TyAndLayout};
10+
use rustc_middle::ty::typetree::typetree_from_ty;
911
use rustc_middle::ty::{AtomicOrdering, Instance, Ty};
1012
use rustc_session::config::OptLevel;
1113
use rustc_span::Span;
@@ -456,7 +458,7 @@ pub trait BuilderMethods<'a, 'tcx>:
456458
src_align: Align,
457459
size: Self::Value,
458460
flags: MemFlags,
459-
tt: Option<rustc_ast::expand::typetree::FncTree>,
461+
tt: Option<FncTree>,
460462
);
461463
fn memmove(
462464
&mut self,
@@ -517,14 +519,18 @@ pub trait BuilderMethods<'a, 'tcx>:
517519
let temp = self.load_operand(src.with_type(layout));
518520
temp.val.store_with_flags(self, dst.with_type(layout), flags);
519521
} else if !layout.is_zst() {
522+
let tt = typetree_from_ty(self.tcx(), layout.ty);
523+
// We seem to pass all values to memcpy with one more indirection.
524+
let tt = tt.add_indirection();
525+
let fnc_tree = FncTree { args: vec![tt.clone(), tt], ret: TypeTree::new() };
520526
let bytes = self.const_usize(layout.size.bytes());
521527
let bytes = if layout.peel_transparent_wrappers(self).ty.is_scalable_vector() {
522528
let vscale = self.vscale(self.type_i64());
523529
self.mul(vscale, bytes)
524530
} else {
525531
bytes
526532
};
527-
self.memcpy(dst.llval, dst.align, src.llval, src.align, bytes, flags, None);
533+
self.memcpy(dst.llval, dst.align, src.llval, src.align, bytes, flags, Some(fnc_tree));
528534
}
529535
}
530536

‎compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,10 @@ extern "C" void LLVMRustPrintStatisticsJSON(RustStringRef OutBuf) {
160160
llvm::PrintStatisticsJSON(OS);
161161
}
162162

163+
extern "C" bool LLVMRustIsCall(LLVMValueRef V) {
164+
return llvm::isa<llvm::CallBase>(llvm::unwrap(V));
165+
}
166+
163167
// Some of the functions here rely on LLVM modules that may not always be
164168
// available. As such, we only try to build it in the first place, if
165169
// llvm.offload is enabled.

0 commit comments

Comments
 (0)