Skip to main content

rustc_middle/ty/
typetree.rs

1use rustc_ast::expand::typetree::{FncTree, Kind, Type, TypeTree};
2use tracing::trace;
3
4use crate::ty::context::TyCtxt;
5use crate::ty::{self, Ty};
6
7/// Generate TypeTree information for autodiff.
8/// This function creates TypeTree metadata that describes the memory layout
9/// of function parameters and return types for Enzyme autodiff.
10pub fn fnc_typetrees<'tcx>(tcx: TyCtxt<'tcx>, fn_ty: Ty<'tcx>) -> FncTree {
11    // Check if TypeTrees are disabled via NoTT flag
12    if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
13        return FncTree { args: ::alloc::vec::Vec::new()vec![], ret: TypeTree::new() };
14    }
15
16    // Check if this is actually a function type
17    if !fn_ty.is_fn() {
18        return FncTree { args: ::alloc::vec::Vec::new()vec![], ret: TypeTree::new() };
19    }
20
21    // Get the function signature
22    let fn_sig = fn_ty.fn_sig(tcx);
23    let sig = tcx.instantiate_bound_regions_with_erased(fn_sig);
24
25    // Create TypeTrees for each input parameter
26    let mut args = ::alloc::vec::Vec::new()vec![];
27    for ty in sig.inputs().iter() {
28        let type_tree = typetree_from_ty(tcx, *ty);
29        args.push(type_tree);
30    }
31
32    // Create TypeTree for return type
33    let ret = typetree_from_ty(tcx, sig.output());
34
35    let f = FncTree { args, ret };
36    f
37}
38
39/// Generate a TypeTree for a specific type.
40/// Mainly a convenience wrapper around the actual implementation.
41pub fn typetree_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> TypeTree {
42    if !tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::Enable) {
43        return TypeTree::new();
44    }
45    if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
46        return TypeTree::new();
47    }
48    let mut visited = Vec::new();
49    typetree_from_ty_impl_inner(tcx, ty, 0, &mut visited, false)
50}
51
52/// Maximum recursion depth for TypeTree generation to prevent stack overflow
53/// from pathological deeply nested types. Combined with cycle detection.
54const MAX_TYPETREE_DEPTH: usize = 6;
55
56fn handle_indirection<'a>(
57    ty: Ty<'a>,
58    tcx: TyCtxt<'a>,
59    depth: usize,
60    visited: &mut Vec<Ty<'a>>,
61) -> TypeTree {
62    let Some(inner_ty) = ty.builtin_deref(true) else {
63        crate::util::bug::bug_fmt(format_args!("incorrect autodiff typetree handling for type: {0}",
        ty));bug!("incorrect autodiff typetree handling for type: {}", ty);
64    };
65    // slices are represented as `&'{erased} mut [f32]`
66    // This reads as a reference to a slice of f32.
67    // So we'd end up with ptr->RustSlice->f32 without this extra handling
68    if inner_ty.is_slice() {
69        if let ty::Slice(element_ty) = inner_ty.kind() {
70            let element_tree =
71                typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
72            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: element_tree,
                }]))vec![Type {
73                offset: -1,
74                size: tcx.data_layout.pointer_size().bytes_usize(),
75                kind: Kind::RustSlice,
76                child: element_tree,
77            }]);
78        }
79    }
80
81    let child = typetree_from_ty_impl_inner(tcx, inner_ty, depth + 1, visited, true);
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::Pointer,
                    child,
                }]))vec![Type {
83        offset: -1,
84        size: tcx.data_layout.pointer_size().bytes_usize(),
85        kind: Kind::Pointer,
86        child,
87    }]);
88}
89
90/// Internal implementation with context about whether this is for a reference target.
91fn typetree_from_ty_impl_inner<'tcx>(
92    tcx: TyCtxt<'tcx>,
93    ty: Ty<'tcx>,
94    depth: usize,
95    visited: &mut Vec<Ty<'tcx>>,
96    is_reference_target: bool,
97) -> TypeTree {
98    if depth >= MAX_TYPETREE_DEPTH {
99        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/typetree.rs:99",
                        "rustc_middle::ty::typetree", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/typetree.rs"),
                        ::tracing_core::__macro_support::Option::Some(99u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("typetree depth limit {0} reached for type: {1}",
                                                    MAX_TYPETREE_DEPTH, ty) as &dyn Value))])
            });
    } else { ; }
};trace!("typetree depth limit {} reached for type: {}", MAX_TYPETREE_DEPTH, ty);
100        return TypeTree::new();
101    }
102
103    if visited.contains(&ty) {
104        return TypeTree::new();
105    }
106    visited.push(ty);
107
108    match ty.kind() {
109        // See handle_indirection for an explanation on why we don't handle it here.
110        ty::Slice(..) => crate::util::bug::bug_fmt(format_args!("incorrect autodiff typetree handling for slice: {0}",
        ty))bug!("incorrect autodiff typetree handling for slice: {}", ty),
111        ty::Ref(..) | ty::RawPtr(..) => handle_indirection(ty, tcx, depth, visited),
112        ty::Adt(def, _) if def.is_box() => handle_indirection(ty, tcx, depth, visited),
113        ty::Array(element_ty, len_const) => {
114            let len = len_const.try_to_target_usize(tcx).unwrap_or(0);
115            if len == 0 {
116                return TypeTree::new();
117            }
118            let element_tree =
119                typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
120            let mut types = Vec::new();
121            for elem_type in &element_tree.0 {
122                types.push(Type::from_ty(-1, elem_type));
123            }
124
125            TypeTree(types)
126        }
127        ty::Tuple(tuple_types) => {
128            if tuple_types.is_empty() {
129                return TypeTree::new();
130            }
131
132            let mut types = Vec::new();
133            let mut current_offset = 0;
134
135            for tuple_ty in tuple_types.iter() {
136                let element_tree =
137                    typetree_from_ty_impl_inner(tcx, tuple_ty, depth + 1, visited, false);
138
139                let element_layout = tcx
140                    .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(tuple_ty))
141                    .ok()
142                    .map(|layout| layout.size.bytes_usize())
143                    .unwrap_or(0);
144
145                for elem_type in &element_tree.0 {
146                    let offset = if elem_type.offset == -1 {
147                        current_offset as isize
148                    } else {
149                        current_offset as isize + elem_type.offset
150                    };
151                    types.push(Type::from_ty(offset, elem_type));
152                }
153
154                current_offset += element_layout;
155            }
156
157            TypeTree(types)
158        }
159        ty::Adt(adt_def, args) if adt_def.is_struct() => {
160            let struct_layout =
161                tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty));
162            if let Ok(layout) = struct_layout {
163                let mut types = Vec::new();
164
165                for (field_idx, field_def) in adt_def.all_fields().enumerate() {
166                    let field_ty = field_def.ty(tcx, args);
167                    let field_tree = typetree_from_ty_impl_inner(
168                        tcx,
169                        field_ty.skip_norm_wip(),
170                        depth + 1,
171                        visited,
172                        false,
173                    );
174
175                    let field_offset = layout.fields.offset(field_idx).bytes_usize();
176
177                    for elem_type in &field_tree.0 {
178                        let offset = if elem_type.offset == -1 {
179                            field_offset as isize
180                        } else {
181                            field_offset as isize + elem_type.offset
182                        };
183                        types.push(Type::from_ty(offset, elem_type));
184                    }
185                }
186
187                TypeTree(types)
188            } else {
189                TypeTree::new()
190            }
191        }
192        ty::Char | ty::Bool | ty::Infer(ty::IntVar(_)) | ty::Int(_) | ty::Uint(_) => {
193            let kind = Kind::Integer;
194            let size = ty.primitive_size(tcx).bytes_usize();
195            let offset = if is_reference_target { 0 } else { -1 };
196            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() }])
197        }
198        ty::Float(_) | ty::Infer(ty::FloatVar(_)) => {
199            let (enzyme_ty, size) = match ty {
200                x if x == tcx.types.f16 => (Kind::Half, 2),
201                x if x == tcx.types.f32 => (Kind::Float, 4),
202                x if x == tcx.types.f64 => (Kind::Double, 8),
203                x if x == tcx.types.f128 => (Kind::F128, 16),
204                _ => crate::util::bug::bug_fmt(format_args!("Unexpected floating point type: {0:?}",
        ty))bug!("Unexpected floating point type: {:?}", ty),
205            };
206            let offset = if is_reference_target { 0 } else { -1 };
207            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() }])
208        }
209        _ => TypeTree::new(),
210    }
211}