rustc_monomorphize/collector/
autodiff.rs

1use rustc_middle::bug;
2use rustc_middle::ty::{self, GenericArg, IntrinsicDef, TyCtxt};
3
4use crate::collector::{MonoItems, create_fn_mono_item};
5
6// Here, we force both primal and diff function to be collected in
7// mono so this does not interfere in `autodiff` intrinsics
8// codegen process. If they are unused, LLVM will remove them when
9// compiling with O3.
10// FIXME(autodiff): Remove this whole file, as per discussion in
11// https://github.com/rust-lang/rust/pull/149033#discussion_r2535465880
12pub(crate) fn collect_autodiff_fn<'tcx>(
13    tcx: TyCtxt<'tcx>,
14    instance: ty::Instance<'tcx>,
15    intrinsic: IntrinsicDef,
16    output: &mut MonoItems<'tcx>,
17) {
18    if intrinsic.name != rustc_span::sym::autodiff {
19        return;
20    };
21
22    collect_autodiff_fn_from_arg(instance.args[0], tcx, output);
23}
24
25fn collect_autodiff_fn_from_arg<'tcx>(
26    arg: GenericArg<'tcx>,
27    tcx: TyCtxt<'tcx>,
28    output: &mut MonoItems<'tcx>,
29) {
30    let (instance, span) = match arg.kind() {
31        ty::GenericArgKind::Type(ty) => match ty.kind() {
32            ty::FnDef(def_id, substs) => {
33                let span = tcx.def_span(def_id);
34                let instance = ty::Instance::expect_resolve(
35                    tcx,
36                    ty::TypingEnv::non_body_analysis(tcx, def_id),
37                    *def_id,
38                    substs,
39                    span,
40                );
41
42                (instance, span)
43            }
44            _ => bug!("expected autodiff function"),
45        },
46        _ => bug!("expected type when matching autodiff arg"),
47    };
48
49    output.push(create_fn_mono_item(tcx, instance, span));
50}