Skip to main content

rustc_middle/ty/
typetree.rs

1use rustc_ast::expand::typetree::{FncTree, Kind, Type, TypeTree};
2use rustc_span::bug;
3use tracing::trace;
4
5use crate::ty::context::TyCtxt;
6use crate::ty::{self, Ty};
7
8/// Generate TypeTree information for autodiff.
9/// This function creates TypeTree metadata that describes the memory layout
10/// of function parameters and return types for Enzyme autodiff.
11pub fn fnc_typetrees<'tcx>(tcx: TyCtxt<'tcx>, fn_ty: Ty<'tcx>) -> FncTree {
12    // Check if TypeTrees are disabled via NoTT flag
13    if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
14        return FncTree { args: ::alloc::vec::Vec::new()vec![], ret: TypeTree::new() };
15    }
16
17    // Check if this is actually a function type
18    if !fn_ty.is_fn() {
19        return FncTree { args: ::alloc::vec::Vec::new()vec![], ret: TypeTree::new() };
20    }
21
22    // Get the function signature
23    let fn_sig = fn_ty.fn_sig(tcx);
24    let sig = tcx.instantiate_bound_regions_with_erased(fn_sig);
25
26    // Create TypeTrees for each input parameter
27    let mut args = ::alloc::vec::Vec::new()vec![];
28    for ty in sig.inputs().iter() {
29        let type_tree = typetree_from_ty(tcx, *ty);
30        args.push(type_tree);
31    }
32
33    // Create TypeTree for return type
34    let ret = typetree_from_ty(tcx, sig.output());
35
36    let f = FncTree { args, ret };
37    f
38}
39
40/// Generate a TypeTree for a specific type.
41/// Mainly a convenience wrapper around the actual implementation.
42pub fn typetree_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> TypeTree {
43    if !tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::Enable) {
44        return TypeTree::new();
45    }
46    if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
47        return TypeTree::new();
48    }
49    let mut visited = Vec::new();
50    typetree_from_ty_impl_inner(tcx, ty, 0, &mut visited, false)
51}
52
53/// Maximum recursion depth for TypeTree generation to prevent stack overflow
54/// from pathological deeply nested types. Combined with cycle detection.
55const MAX_TYPETREE_DEPTH: usize = 6;
56
57fn handle_indirection<'a>(
58    ty: Ty<'a>,
59    tcx: TyCtxt<'a>,
60    depth: usize,
61    visited: &mut Vec<Ty<'a>>,
62) -> TypeTree {
63    let Some(inner_ty) = ty.builtin_deref(true) else {
64        bug_impl(None,
    format_args!("incorrect autodiff typetree handling for type: {0}", ty),
    Location::caller());bug!("incorrect autodiff typetree handling for type: {}", ty);
65    };
66    // A pointer to a slice-tailed DST is a fat pointer `{data, len}`. `RustSlice` describes both
67    // LLVM arguments, while its child describes the memory reached through `data`.
68    let typing_env = ty::TypingEnv::fully_monomorphized();
69    if let ty::Slice(element_ty) = tcx.struct_tail_for_codegen(inner_ty, typing_env).kind() {
70        // `layout.size` here is the sized prefix of `inner_ty`, not the slice element size.
71        // Direct slices, transparent wrappers (`OsStr`), and ZST-prefixed DSTs have no byte
72        // offset to preserve. Nonzero prefixes (e.g. `Header<[f32]>`) keep field offsets.
73        // ZST elements still take this path and yield an empty child TypeTree (size 0).
74        let child = if tcx
75            .layout_of(typing_env.as_query_input(inner_ty))
76            .is_ok_and(|layout| layout.size.bytes() == 0)
77        {
78            typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false)
79        } else {
80            typetree_from_ty_impl_inner(tcx, inner_ty, depth + 1, visited, true)
81        };
82        return TypeTree(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Type {
                    offset: -1,
                    size: tcx.data_layout.pointer_size().bytes_usize(),
                    kind: Kind::RustSlice,
                    child,
                }]))vec![Type {
83            offset: -1,
84            size: tcx.data_layout.pointer_size().bytes_usize(),
85            kind: Kind::RustSlice,
86            child,
87        }]);
88    }
89
90    let child = typetree_from_ty_impl_inner(tcx, inner_ty, depth + 1, visited, true);
91    return TypeTree(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Type {
                    offset: -1,
                    size: tcx.data_layout.pointer_size().bytes_usize(),
                    kind: Kind::Pointer,
                    child,
                }]))vec![Type {
92        offset: -1,
93        size: tcx.data_layout.pointer_size().bytes_usize(),
94        kind: Kind::Pointer,
95        child,
96    }]);
97}
98
99/// Internal implementation with context about whether this is for a reference target.
100fn typetree_from_ty_impl_inner<'tcx>(
101    tcx: TyCtxt<'tcx>,
102    ty: Ty<'tcx>,
103    depth: usize,
104    visited: &mut Vec<Ty<'tcx>>,
105    is_reference_target: bool,
106) -> TypeTree {
107    if depth >= MAX_TYPETREE_DEPTH {
108        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_middle/src/ty/typetree.rs:108",
                        "rustc_middle::ty::typetree", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_middle/src/ty/typetree.rs"),
                        ::tracing_core::__macro_support::Option::Some(108u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::typetree"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("typetree depth limit {0} reached for type: {1}",
                                                    MAX_TYPETREE_DEPTH, ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("typetree depth limit {} reached for type: {}", MAX_TYPETREE_DEPTH, ty);
109        return TypeTree::new();
110    }
111
112    if visited.contains(&ty) {
113        return TypeTree::new();
114    }
115    visited.push(ty);
116
117    let tree = match ty.kind() {
118        // Direct slices are handled by `handle_indirection`. This arm describes a slice tail while
119        // recursing through a prefixed DST, so its caller can add the field offset.
120        ty::Slice(element_ty) => {
121            typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false)
122        }
123        ty::Ref(..) | ty::RawPtr(..) => handle_indirection(ty, tcx, depth, visited),
124        ty::Adt(def, _) if def.is_box() => handle_indirection(ty, tcx, depth, visited),
125        ty::Array(element_ty, len_const) => {
126            let len = len_const.try_to_target_usize(tcx).unwrap_or(0);
127            if len == 0 {
128                TypeTree::new()
129            } else {
130                let element_tree =
131                    typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
132                let mut types = Vec::new();
133                for elem_type in &element_tree.0 {
134                    types.push(Type::from_ty(-1, elem_type));
135                }
136
137                TypeTree(types)
138            }
139        }
140        ty::Tuple(tuple_types) => {
141            if tuple_types.is_empty() {
142                TypeTree::new()
143            } else {
144                let mut types = Vec::new();
145                let mut current_offset = 0;
146
147                for tuple_ty in tuple_types.iter() {
148                    let element_tree =
149                        typetree_from_ty_impl_inner(tcx, tuple_ty, depth + 1, visited, false);
150
151                    let element_layout = tcx
152                        .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(tuple_ty))
153                        .ok()
154                        .map(|layout| layout.size.bytes_usize())
155                        .unwrap_or(0);
156
157                    for elem_type in &element_tree.0 {
158                        let offset = if elem_type.offset == -1 {
159                            current_offset as isize
160                        } else {
161                            current_offset as isize + elem_type.offset
162                        };
163                        types.push(Type::from_ty(offset, elem_type));
164                    }
165
166                    current_offset += element_layout;
167                }
168
169                TypeTree(types)
170            }
171        }
172        ty::Adt(adt_def, args) if adt_def.is_struct() => {
173            let struct_layout =
174                tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty));
175            if let Ok(layout) = struct_layout {
176                let mut types = Vec::new();
177
178                for (field_idx, field_def) in adt_def.all_fields().enumerate() {
179                    let field_ty = field_def.ty(tcx, args);
180                    let field_tree = typetree_from_ty_impl_inner(
181                        tcx,
182                        field_ty.skip_norm_wip(),
183                        depth + 1,
184                        visited,
185                        false,
186                    );
187
188                    let field_offset = layout.fields.offset(field_idx).bytes_usize();
189
190                    for elem_type in &field_tree.0 {
191                        let offset = if elem_type.offset == -1 {
192                            field_offset as isize
193                        } else {
194                            field_offset as isize + elem_type.offset
195                        };
196                        types.push(Type::from_ty(offset, elem_type));
197                    }
198                }
199
200                TypeTree(types)
201            } else {
202                TypeTree::new()
203            }
204        }
205        ty::Char | ty::Bool | ty::Infer(ty::IntVar(_)) | ty::Int(_) | ty::Uint(_) => {
206            let kind = Kind::Integer;
207            let size = ty.primitive_size(tcx).bytes_usize();
208            let offset = if is_reference_target { 0 } else { -1 };
209            TypeTree(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Type { offset, size, kind, child: TypeTree::new() }]))vec![Type { offset, size, kind, child: TypeTree::new() }])
210        }
211        ty::Float(_) | ty::Infer(ty::FloatVar(_)) => {
212            let (enzyme_ty, size) = match ty {
213                x if x == tcx.types.f16 => (Kind::Half, 2),
214                x if x == tcx.types.f32 => (Kind::Float, 4),
215                x if x == tcx.types.f64 => (Kind::Double, 8),
216                x if x == tcx.types.f128 => (Kind::F128, 16),
217                _ => bug_impl(None, format_args!("Unexpected floating point type: {0:?}", ty),
    Location::caller())bug!("Unexpected floating point type: {:?}", ty),
218            };
219            let offset = if is_reference_target { 0 } else { -1 };
220            TypeTree(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Type { offset, size, kind: enzyme_ty, child: TypeTree::new() }]))vec![Type { offset, size, kind: enzyme_ty, child: TypeTree::new() }])
221        }
222        _ => TypeTree::new(),
223    };
224
225    let popped = visited.pop();
226    if true {
    {
        match (&popped, &Some(ty)) {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(popped, Some(ty));
227    tree
228}