Skip to main content

rustc_const_eval/const_eval/
valtrees.rs

1use rustc_abi::{BackendRepr, FieldIdx, VariantIdx};
2use rustc_data_structures::fx::{FxHashMap, FxHashSet};
3use rustc_data_structures::stack::ensure_sufficient_stack;
4use rustc_middle::mir::interpret::{EvalToValTreeResult, GlobalId, ValTreeCreationError};
5use rustc_middle::traits::ObligationCause;
6use rustc_middle::ty::layout::{LayoutCx, TyAndLayout};
7use rustc_middle::ty::{self, Ty, TyCtxt};
8use rustc_middle::{bug, mir};
9use rustc_span::DUMMY_SP;
10use tracing::{debug, instrument, trace};
11
12use super::VALTREE_MAX_NODES;
13use super::eval_queries::{mk_eval_cx_to_read_const_val, op_to_const};
14use super::machine::CompileTimeInterpCx;
15use crate::const_eval::CanAccessMutGlobal;
16use crate::interpret::{
17    ImmTy, Immediate, InternKind, MPlaceTy, MemPlaceMeta, MemoryKind, PlaceTy, Projectable, Scalar,
18    intern_const_alloc_recursive,
19};
20
21#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("branches",
                                    "rustc_const_eval::const_eval::valtrees",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                    ::tracing_core::__macro_support::Option::Some(21u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                    ::tracing_core::field::FieldSet::new(&["place",
                                                    "field_count", "variant", "num_nodes"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&field_count as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&variant)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&num_nodes as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: EvalToValTreeResult<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let place =
                match variant {
                    Some(variant) =>
                        ecx.project_downcast(place, variant).unwrap(),
                    None => place.clone(),
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:35",
                                    "rustc_const_eval::const_eval::valtrees",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                    ::tracing_core::__macro_support::Option::Some(35u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                    ::tracing_core::field::FieldSet::new(&["place"],
                                        ::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};
                            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(&debug(&place) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            let mut branches =
                Vec::with_capacity(field_count + variant.is_some() as usize);
            if let Some(variant) = variant {
                branches.push(ty::Const::new_value(*ecx.tcx,
                        ty::ValTree::from_scalar_int(*ecx.tcx,
                            variant.as_u32().into()), ecx.tcx.types.u32));
            }
            for i in 0..field_count {
                let field =
                    ecx.project_field(&place, FieldIdx::from_usize(i)).unwrap();
                let valtree =
                    const_to_valtree_inner(ecx, &field, num_nodes, visited,
                            settled)?;
                branches.push(ty::Const::new_value(*ecx.tcx, valtree,
                        field.layout.ty));
            }
            if branches.len() == 0 { *num_nodes += 1; }
            Ok(ty::ValTree::from_branches(*ecx.tcx, branches))
        }
    }
}#[instrument(skip(ecx, visited, settled), level = "debug")]
22fn branches<'tcx>(
23    ecx: &CompileTimeInterpCx<'tcx>,
24    place: &MPlaceTy<'tcx>,
25    field_count: usize,
26    variant: Option<VariantIdx>,
27    num_nodes: &mut usize,
28    visited: &mut FxHashSet<MPlaceTy<'tcx>>,
29    settled: &mut FxHashMap<MPlaceTy<'tcx>, EvalToValTreeResult<'tcx>>,
30) -> EvalToValTreeResult<'tcx> {
31    let place = match variant {
32        Some(variant) => ecx.project_downcast(place, variant).unwrap(),
33        None => place.clone(),
34    };
35    debug!(?place);
36
37    let mut branches = Vec::with_capacity(field_count + variant.is_some() as usize);
38
39    // For enums, we prepend their variant index before the variant's fields so we can figure out
40    // the variant again when just seeing a valtree.
41    if let Some(variant) = variant {
42        branches.push(ty::Const::new_value(
43            *ecx.tcx,
44            ty::ValTree::from_scalar_int(*ecx.tcx, variant.as_u32().into()),
45            ecx.tcx.types.u32,
46        ));
47    }
48
49    for i in 0..field_count {
50        let field = ecx.project_field(&place, FieldIdx::from_usize(i)).unwrap();
51        let valtree = const_to_valtree_inner(ecx, &field, num_nodes, visited, settled)?;
52        branches.push(ty::Const::new_value(*ecx.tcx, valtree, field.layout.ty));
53    }
54
55    // Have to account for ZSTs here
56    if branches.len() == 0 {
57        *num_nodes += 1;
58    }
59
60    Ok(ty::ValTree::from_branches(*ecx.tcx, branches))
61}
62
63#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("slice_branches",
                                    "rustc_const_eval::const_eval::valtrees",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                    ::tracing_core::__macro_support::Option::Some(63u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                    ::tracing_core::field::FieldSet::new(&["place",
                                                    "num_nodes"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&num_nodes as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: EvalToValTreeResult<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let n =
                place.len(ecx).unwrap_or_else(|_|
                        {
                            ::core::panicking::panic_fmt(format_args!("expected to use len of place {0:?}",
                                    place));
                        });
            let mut elems = Vec::with_capacity(n as usize);
            for i in 0..n {
                let place_elem = ecx.project_index(place, i).unwrap();
                let valtree =
                    const_to_valtree_inner(ecx, &place_elem, num_nodes, visited,
                            settled)?;
                elems.push(ty::Const::new_value(*ecx.tcx, valtree,
                        place_elem.layout.ty));
            }
            Ok(ty::ValTree::from_branches(*ecx.tcx, elems))
        }
    }
}#[instrument(skip(ecx, visited, settled), level = "debug")]
64fn slice_branches<'tcx>(
65    ecx: &CompileTimeInterpCx<'tcx>,
66    place: &MPlaceTy<'tcx>,
67    num_nodes: &mut usize,
68    visited: &mut FxHashSet<MPlaceTy<'tcx>>,
69    settled: &mut FxHashMap<MPlaceTy<'tcx>, EvalToValTreeResult<'tcx>>,
70) -> EvalToValTreeResult<'tcx> {
71    let n = place.len(ecx).unwrap_or_else(|_| panic!("expected to use len of place {place:?}"));
72
73    let mut elems = Vec::with_capacity(n as usize);
74    for i in 0..n {
75        let place_elem = ecx.project_index(place, i).unwrap();
76        let valtree = const_to_valtree_inner(ecx, &place_elem, num_nodes, visited, settled)?;
77        elems.push(ty::Const::new_value(*ecx.tcx, valtree, place_elem.layout.ty));
78    }
79
80    Ok(ty::ValTree::from_branches(*ecx.tcx, elems))
81}
82
83#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("const_to_valtree_inner",
                                    "rustc_const_eval::const_eval::valtrees",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                    ::tracing_core::__macro_support::Option::Some(83u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                    ::tracing_core::field::FieldSet::new(&["place",
                                                    "num_nodes"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&num_nodes as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: EvalToValTreeResult<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = *ecx.tcx;
            let ty = place.layout.ty;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:93",
                                    "rustc_const_eval::const_eval::valtrees",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                    ::tracing_core::__macro_support::Option::Some(93u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                    ::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};
                            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!("ty kind: {0:?}",
                                                                ty.kind()) as &dyn Value))])
                        });
                } else { ; }
            };
            if let Some(&result) = settled.get(place) { return result; }
            if visited.contains(place) {
                return Err(ValTreeCreationError::CyclicConst);
            }
            if *num_nodes >= VALTREE_MAX_NODES {
                return Err(ValTreeCreationError::NodesOverflow);
            }
            visited.insert(place.clone());
            let result =
                ensure_sufficient_stack(||
                        match ty.kind() {
                            ty::FnDef(..) => {
                                *num_nodes += 1;
                                Ok(ty::ValTree::zst(tcx))
                            }
                            ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) |
                                ty::Char => {
                                let val = ecx.read_immediate(place).report_err()?;
                                let val = val.to_scalar_int().unwrap();
                                *num_nodes += 1;
                                Ok(ty::ValTree::from_scalar_int(tcx, val))
                            }
                            ty::Pat(base, ..) => {
                                let mut place = place.clone();
                                place.layout = ecx.layout_of(*base).unwrap();
                                const_to_valtree_inner(ecx, &place, num_nodes, visited,
                                    settled)
                            }
                            ty::RawPtr(_, _) => {
                                let val = ecx.read_immediate(place).report_err()?;
                                if #[allow(non_exhaustive_omitted_patterns)] match val.layout.backend_repr
                                        {
                                        BackendRepr::ScalarPair { .. } => true,
                                        _ => false,
                                    } {
                                    Err(ValTreeCreationError::NonSupportedType(ty))
                                } else {
                                    let val = val.to_scalar();
                                    match val.try_to_scalar_int() {
                                        Ok(val) => Ok(ty::ValTree::from_scalar_int(tcx, val)),
                                        Err(_) => Err(ValTreeCreationError::NonSupportedType(ty)),
                                    }
                                }
                            }
                            ty::FnPtr(..) =>
                                Err(ValTreeCreationError::NonSupportedType(ty)),
                            ty::Ref(_, _, _) => {
                                let derefd_place = ecx.deref_pointer(place).report_err()?;
                                const_to_valtree_inner(ecx, &derefd_place, num_nodes,
                                    visited, settled)
                            }
                            ty::Str | ty::Slice(_) | ty::Array(_, _) => {
                                slice_branches(ecx, place, num_nodes, visited, settled)
                            }
                            ty::Dynamic(..) =>
                                Err(ValTreeCreationError::NonSupportedType(ty)),
                            ty::Tuple(elem_tys) => {
                                branches(ecx, place, elem_tys.len(), None, num_nodes,
                                    visited, settled)
                            }
                            ty::Adt(def, _) => {
                                if def.is_union() {
                                    Err(ValTreeCreationError::NonSupportedType(ty))
                                } else if def.variants().is_empty() {
                                    ::rustc_middle::util::bug::bug_fmt(format_args!("uninhabited types should have errored and never gotten converted to valtree"))
                                } else {
                                    let variant = ecx.read_discriminant(place).report_err()?;
                                    branches(ecx, place, def.variant(variant).fields.len(),
                                        def.is_enum().then_some(variant), num_nodes, visited,
                                        settled)
                                }
                            }
                            ty::Alias(..) =>
                                Err(ValTreeCreationError::NonSupportedType(ty)),
                            ty::Closure(..) =>
                                Err(ValTreeCreationError::NonSupportedType(ty)),
                            ty::Never | ty::Error(_) | ty::Foreign(..) |
                                ty::Infer(ty::FreshIntTy(_)) |
                                ty::Infer(ty::FreshFloatTy(_)) | ty::Param(_) |
                                ty::Bound(..) | ty::Placeholder(..) | ty::Infer(_) |
                                ty::CoroutineClosure(..) | ty::Coroutine(..) |
                                ty::CoroutineWitness(..) | ty::UnsafeBinder(_) =>
                                Err(ValTreeCreationError::NonSupportedType(ty)),
                        });
            visited.remove(place);
            settled.insert(place.clone(), result);
            result
        }
    }
}#[instrument(skip(ecx, visited, settled), level = "debug")]
84fn const_to_valtree_inner<'tcx>(
85    ecx: &CompileTimeInterpCx<'tcx>,
86    place: &MPlaceTy<'tcx>,
87    num_nodes: &mut usize,
88    visited: &mut FxHashSet<MPlaceTy<'tcx>>,
89    settled: &mut FxHashMap<MPlaceTy<'tcx>, EvalToValTreeResult<'tcx>>,
90) -> EvalToValTreeResult<'tcx> {
91    let tcx = *ecx.tcx;
92    let ty = place.layout.ty;
93    debug!("ty kind: {:?}", ty.kind());
94
95    if let Some(&result) = settled.get(place) {
96        return result;
97    }
98
99    if visited.contains(place) {
100        return Err(ValTreeCreationError::CyclicConst);
101    }
102
103    if *num_nodes >= VALTREE_MAX_NODES {
104        return Err(ValTreeCreationError::NodesOverflow);
105    }
106
107    visited.insert(place.clone());
108
109    let result = ensure_sufficient_stack(|| match ty.kind() {
110        ty::FnDef(..) => {
111            *num_nodes += 1;
112            Ok(ty::ValTree::zst(tcx))
113        }
114        ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char => {
115            let val = ecx.read_immediate(place).report_err()?;
116            let val = val.to_scalar_int().unwrap();
117            *num_nodes += 1;
118
119            Ok(ty::ValTree::from_scalar_int(tcx, val))
120        }
121
122        ty::Pat(base, ..) => {
123            let mut place = place.clone();
124            // The valtree of the base type is the same as the valtree of the pattern type.
125            // Since the returned valtree does not contain the type or layout, we can just
126            // switch to the base type.
127            place.layout = ecx.layout_of(*base).unwrap();
128            const_to_valtree_inner(ecx, &place, num_nodes, visited, settled)
129        }
130
131        ty::RawPtr(_, _) => {
132            // Not all raw pointers are allowed, as we cannot properly test them for
133            // equality at compile-time (see `ptr_guaranteed_cmp`).
134            // However we allow those that are just integers in disguise.
135            // First, get the pointer. Remember it might be wide!
136            let val = ecx.read_immediate(place).report_err()?;
137            // We could allow wide raw pointers where both sides are integers in the future,
138            // but for now we reject them.
139            if matches!(val.layout.backend_repr, BackendRepr::ScalarPair { .. }) {
140                Err(ValTreeCreationError::NonSupportedType(ty))
141            } else {
142                let val = val.to_scalar();
143                // We are in the CTFE machine, so ptr-to-int casts will fail.
144                // This can only be `Ok` if `val` already is an integer.
145                match val.try_to_scalar_int() {
146                    Ok(val) => Ok(ty::ValTree::from_scalar_int(tcx, val)),
147                    Err(_) => Err(ValTreeCreationError::NonSupportedType(ty)),
148                }
149            }
150        }
151
152        // Technically we could allow function pointers (represented as `ty::Instance`), but this is not guaranteed to
153        // agree with runtime equality tests.
154        ty::FnPtr(..) => Err(ValTreeCreationError::NonSupportedType(ty)),
155
156        ty::Ref(_, _, _) => {
157            let derefd_place = ecx.deref_pointer(place).report_err()?;
158            const_to_valtree_inner(ecx, &derefd_place, num_nodes, visited, settled)
159        }
160
161        ty::Str | ty::Slice(_) | ty::Array(_, _) => {
162            slice_branches(ecx, place, num_nodes, visited, settled)
163        }
164        // Trait objects are not allowed in type level constants, as we have no concept for
165        // resolving their backing type, even if we can do that at const eval time. We may
166        // hypothetically be able to allow `dyn StructuralPartialEq` trait objects in the future,
167        // but it is unclear if this is useful.
168        ty::Dynamic(..) => Err(ValTreeCreationError::NonSupportedType(ty)),
169
170        ty::Tuple(elem_tys) => {
171            branches(ecx, place, elem_tys.len(), None, num_nodes, visited, settled)
172        }
173
174        ty::Adt(def, _) => {
175            if def.is_union() {
176                Err(ValTreeCreationError::NonSupportedType(ty))
177            } else if def.variants().is_empty() {
178                bug!("uninhabited types should have errored and never gotten converted to valtree")
179            } else {
180                let variant = ecx.read_discriminant(place).report_err()?;
181                branches(
182                    ecx,
183                    place,
184                    def.variant(variant).fields.len(),
185                    def.is_enum().then_some(variant),
186                    num_nodes,
187                    visited,
188                    settled,
189                )
190            }
191        }
192
193        // FIXME(oli-obk): we could look behind opaque types
194        ty::Alias(..) => Err(ValTreeCreationError::NonSupportedType(ty)),
195
196        // FIXME(oli-obk): we can probably encode closures just like structs
197        ty::Closure(..) => Err(ValTreeCreationError::NonSupportedType(ty)),
198
199        ty::Never
200        | ty::Error(_)
201        | ty::Foreign(..)
202        | ty::Infer(ty::FreshIntTy(_))
203        | ty::Infer(ty::FreshFloatTy(_))
204        | ty::Param(_)
205        | ty::Bound(..)
206        | ty::Placeholder(..)
207        | ty::Infer(_)
208        | ty::CoroutineClosure(..)
209        | ty::Coroutine(..)
210        | ty::CoroutineWitness(..)
211        | ty::UnsafeBinder(_) => Err(ValTreeCreationError::NonSupportedType(ty)),
212    });
213
214    visited.remove(place);
215    settled.insert(place.clone(), result);
216    result
217}
218
219/// Valtrees don't store the `MemPlaceMeta` that all dynamically sized values have in the interpreter.
220/// This function reconstructs it.
221fn reconstruct_place_meta<'tcx>(
222    layout: TyAndLayout<'tcx>,
223    valtree: ty::ValTree<'tcx>,
224    tcx: TyCtxt<'tcx>,
225) -> MemPlaceMeta {
226    if layout.is_sized() {
227        return MemPlaceMeta::None;
228    }
229
230    let mut last_valtree = valtree;
231    // Traverse the type, and update `last_valtree` as we go.
232    //
233    // FIXME(#155345): Missing normalization call
234    let tail = tcx.struct_tail_raw(
235        layout.ty,
236        &ObligationCause::dummy(),
237        |ty| ty.skip_norm_wip(),
238        || {
239            let branches = last_valtree.to_branch();
240            last_valtree = branches.last().unwrap().to_value().valtree;
241            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:241",
                        "rustc_const_eval::const_eval::valtrees",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                        ::tracing_core::__macro_support::Option::Some(241u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                        ::tracing_core::field::FieldSet::new(&["branches",
                                        "last_valtree"],
                            ::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};
                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(&debug(&branches)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&last_valtree)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?branches, ?last_valtree);
242        },
243    );
244    // Sanity-check that we got a tail we support.
245    match tail.kind() {
246        ty::Slice(..) | ty::Str => {}
247        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unsized tail of a valtree must be Slice or Str"))bug!("unsized tail of a valtree must be Slice or Str"),
248    };
249
250    // Get the number of elements in the unsized field.
251    let num_elems = last_valtree.to_branch().len();
252    MemPlaceMeta::Meta(Scalar::from_target_usize(num_elems as u64, &tcx))
253}
254
255x;#[instrument(skip(ecx), level = "debug", ret)]
256fn create_valtree_place<'tcx>(
257    ecx: &mut CompileTimeInterpCx<'tcx>,
258    layout: TyAndLayout<'tcx>,
259    valtree: ty::ValTree<'tcx>,
260) -> MPlaceTy<'tcx> {
261    let meta = reconstruct_place_meta(layout, valtree, ecx.tcx.tcx);
262    ecx.allocate_dyn(layout, MemoryKind::Stack, meta).unwrap()
263}
264
265/// Evaluates a constant and turns it into a type-level constant value.
266pub(crate) fn eval_to_valtree<'tcx>(
267    tcx: TyCtxt<'tcx>,
268    typing_env: ty::TypingEnv<'tcx>,
269    cid: GlobalId<'tcx>,
270) -> EvalToValTreeResult<'tcx> {
271    crate::assert_typing_mode(typing_env.typing_mode());
272    let const_alloc = tcx.eval_to_allocation_raw(typing_env.as_query_input(cid))?;
273
274    // FIXME Need to provide a span to `eval_to_valtree`
275    let ecx = mk_eval_cx_to_read_const_val(
276        tcx,
277        DUMMY_SP,
278        typing_env,
279        // It is absolutely crucial for soundness that
280        // we do not read from mutable memory.
281        CanAccessMutGlobal::No,
282    );
283    let place = ecx.raw_const_to_mplace(const_alloc).unwrap();
284    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:284",
                        "rustc_const_eval::const_eval::valtrees",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                        ::tracing_core::__macro_support::Option::Some(284u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                        ::tracing_core::field::FieldSet::new(&["place"],
                            ::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};
                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(&debug(&place) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?place);
285
286    let mut num_nodes = 0;
287    let mut visited = FxHashSet::default();
288    let mut settled = FxHashMap::default();
289    const_to_valtree_inner(&ecx, &place, &mut num_nodes, &mut visited, &mut settled)
290}
291
292/// Converts a `ValTree` to a `ConstValue`, which is needed after mir
293/// construction has finished.
294// FIXME(valtrees): Merge `valtree_to_const_value` and `valtree_into_mplace` into one function
295x;#[instrument(skip(tcx), level = "debug", ret)]
296pub fn valtree_to_const_value<'tcx>(
297    tcx: TyCtxt<'tcx>,
298    typing_env: ty::TypingEnv<'tcx>,
299    cv: ty::Value<'tcx>,
300) -> mir::ConstValue {
301    // Basic idea: We directly construct `Scalar` values from trivial `ValTree`s
302    // (those for constants with type bool, int, uint, float or char).
303    // For all other types we create an `MPlace` and fill that by walking
304    // the `ValTree` and using `place_projection` and `place_field` to
305    // create inner `MPlace`s which are filled recursively.
306    // FIXME: Does this need an example?
307    match *cv.ty.kind() {
308        ty::FnDef(..) => {
309            assert!(cv.valtree.is_zst());
310            mir::ConstValue::ZeroSized
311        }
312        ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char | ty::RawPtr(_, _) => {
313            mir::ConstValue::Scalar(Scalar::Int(cv.to_leaf()))
314        }
315        ty::Pat(ty, _) => {
316            let cv = ty::Value { valtree: cv.valtree, ty };
317            valtree_to_const_value(tcx, typing_env, cv)
318        }
319        ty::Ref(_, inner_ty, _) => {
320            let mut ecx =
321                mk_eval_cx_to_read_const_val(tcx, DUMMY_SP, typing_env, CanAccessMutGlobal::No);
322            let imm = valtree_to_ref(&mut ecx, cv.valtree, inner_ty);
323            let imm = ImmTy::from_immediate(
324                imm,
325                tcx.layout_of(typing_env.as_query_input(cv.ty)).unwrap(),
326            );
327            op_to_const(&ecx, &imm.into(), /* for diagnostics */ false)
328        }
329        ty::Tuple(_) | ty::Array(_, _) | ty::Adt(..) => {
330            let layout = tcx.layout_of(typing_env.as_query_input(cv.ty)).unwrap();
331            if layout.is_zst() {
332                // Fast path to avoid some allocations.
333                return mir::ConstValue::ZeroSized;
334            }
335            if layout.backend_repr.is_scalar()
336                && (matches!(cv.ty.kind(), ty::Tuple(_))
337                    || matches!(cv.ty.kind(), ty::Adt(def, _) if def.is_struct()))
338            {
339                // A Scalar tuple/struct; we can avoid creating an allocation.
340                let branches = cv.to_branch();
341                // Find the non-ZST field. (There can be aligned ZST!)
342                for (i, &inner_valtree) in branches.iter().enumerate() {
343                    let field = layout.field(&LayoutCx::new(tcx, typing_env), i);
344                    if !field.is_zst() {
345                        let cv =
346                            ty::Value { valtree: inner_valtree.to_value().valtree, ty: field.ty };
347                        return valtree_to_const_value(tcx, typing_env, cv);
348                    }
349                }
350                bug!("could not find non-ZST field during in {layout:#?}");
351            }
352
353            let mut ecx =
354                mk_eval_cx_to_read_const_val(tcx, DUMMY_SP, typing_env, CanAccessMutGlobal::No);
355
356            // Need to create a place for this valtree.
357            let place = create_valtree_place(&mut ecx, layout, cv.valtree);
358
359            valtree_into_mplace(&mut ecx, &place, cv.valtree);
360            dump_place(&ecx, &place);
361            intern_const_alloc_recursive(&mut ecx, InternKind::Constant, &place).unwrap();
362
363            op_to_const(&ecx, &place.into(), /* for diagnostics */ false)
364        }
365        ty::Never
366        | ty::Error(_)
367        | ty::Foreign(..)
368        | ty::Infer(ty::FreshIntTy(_))
369        | ty::Infer(ty::FreshFloatTy(_))
370        | ty::Alias(..)
371        | ty::Param(_)
372        | ty::Bound(..)
373        | ty::Placeholder(..)
374        | ty::Infer(_)
375        | ty::Closure(..)
376        | ty::CoroutineClosure(..)
377        | ty::Coroutine(..)
378        | ty::CoroutineWitness(..)
379        | ty::FnPtr(..)
380        | ty::Str
381        | ty::Slice(_)
382        | ty::Dynamic(..)
383        | ty::UnsafeBinder(_) => {
384            bug!("no ValTree should have been created for type {:?}", cv.ty.kind())
385        }
386    }
387}
388
389/// Put a valtree into memory and return a reference to that.
390fn valtree_to_ref<'tcx>(
391    ecx: &mut CompileTimeInterpCx<'tcx>,
392    valtree: ty::ValTree<'tcx>,
393    pointee_ty: Ty<'tcx>,
394) -> Immediate {
395    let pointee_place = create_valtree_place(ecx, ecx.layout_of(pointee_ty).unwrap(), valtree);
396    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:396",
                        "rustc_const_eval::const_eval::valtrees",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                        ::tracing_core::__macro_support::Option::Some(396u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                        ::tracing_core::field::FieldSet::new(&["pointee_place"],
                            ::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};
                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(&debug(&pointee_place)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?pointee_place);
397
398    valtree_into_mplace(ecx, &pointee_place, valtree);
399    dump_place(ecx, &pointee_place);
400    intern_const_alloc_recursive(ecx, InternKind::Constant, &pointee_place).unwrap();
401
402    pointee_place.to_ref(&ecx.tcx)
403}
404
405#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("valtree_into_mplace",
                                    "rustc_const_eval::const_eval::valtrees",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                    ::tracing_core::__macro_support::Option::Some(405u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                    ::tracing_core::field::FieldSet::new(&["place", "valtree"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&valtree)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty = place.layout.ty;
            match ty.kind() {
                ty::FnDef(_, _) => {}
                ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char
                    | ty::RawPtr(..) => {
                    let scalar_int = valtree.to_leaf();
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:422",
                                            "rustc_const_eval::const_eval::valtrees",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                            ::tracing_core::__macro_support::Option::Some(422u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                            ::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};
                                    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!("writing trivial valtree {0:?} to place {1:?}",
                                                                        scalar_int, place) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    ecx.write_immediate(Immediate::Scalar(scalar_int.into()),
                            place).unwrap();
                }
                ty::Ref(_, inner_ty, _) => {
                    let imm = valtree_to_ref(ecx, valtree, *inner_ty);
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:427",
                                            "rustc_const_eval::const_eval::valtrees",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                            ::tracing_core::__macro_support::Option::Some(427u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                            ::tracing_core::field::FieldSet::new(&["imm"],
                                                ::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};
                                    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(&debug(&imm) as
                                                                &dyn Value))])
                                });
                        } else { ; }
                    };
                    ecx.write_immediate(imm, place).unwrap();
                }
                ty::Adt(_, _) | ty::Tuple(_) | ty::Array(_, _) | ty::Str |
                    ty::Slice(_) => {
                    let branches = valtree.to_branch();
                    let (place_adjusted, branches, variant_idx) =
                        match ty.kind() {
                            ty::Adt(def, _) if def.is_enum() => {
                                let scalar_int = branches[0].to_leaf();
                                let variant_idx = VariantIdx::from_u32(scalar_int.to_u32());
                                let variant = def.variant(variant_idx);
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:440",
                                                        "rustc_const_eval::const_eval::valtrees",
                                                        ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(440u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                                        ::tracing_core::field::FieldSet::new(&["variant"],
                                                            ::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};
                                                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(&debug(&variant) as
                                                                            &dyn Value))])
                                            });
                                    } else { ; }
                                };
                                (ecx.project_downcast(place, variant_idx).unwrap(),
                                    &branches[1..], Some(variant_idx))
                            }
                            _ => (place.clone(), branches.as_slice(), None),
                        };
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:450",
                                            "rustc_const_eval::const_eval::valtrees",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                            ::tracing_core::__macro_support::Option::Some(450u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                            ::tracing_core::field::FieldSet::new(&["place_adjusted",
                                                            "branches"],
                                                ::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};
                                    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(&debug(&place_adjusted)
                                                                as &dyn Value)),
                                                    (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&branches)
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    for (i, inner_valtree) in branches.iter().enumerate() {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:455",
                                                "rustc_const_eval::const_eval::valtrees",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                                ::tracing_core::__macro_support::Option::Some(455u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                                ::tracing_core::field::FieldSet::new(&["i",
                                                                "inner_valtree"],
                                                    ::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};
                                        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(&debug(&i) as
                                                                    &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&inner_valtree)
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        let place_inner =
                            match ty.kind() {
                                ty::Str | ty::Slice(_) | ty::Array(..) => {
                                    ecx.project_index(place, i as u64).unwrap()
                                }
                                _ =>
                                    ecx.project_field(&place_adjusted,
                                            FieldIdx::from_usize(i)).unwrap(),
                            };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:464",
                                                "rustc_const_eval::const_eval::valtrees",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                                ::tracing_core::__macro_support::Option::Some(464u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                                ::tracing_core::field::FieldSet::new(&["place_inner"],
                                                    ::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};
                                        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(&debug(&place_inner)
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        valtree_into_mplace(ecx, &place_inner,
                            inner_valtree.to_value().valtree);
                        dump_place(ecx, &place_inner);
                    }
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:469",
                                            "rustc_const_eval::const_eval::valtrees",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                            ::tracing_core::__macro_support::Option::Some(469u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                            ::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};
                                    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!("dump of place_adjusted:")
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    dump_place(ecx, &place_adjusted);
                    if let Some(variant_idx) = variant_idx {
                        ecx.write_discriminant(variant_idx, place).unwrap();
                    }
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:477",
                                            "rustc_const_eval::const_eval::valtrees",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                                            ::tracing_core::__macro_support::Option::Some(477u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                                            ::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};
                                    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!("dump of place after writing discriminant:")
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    dump_place(ecx, place);
                }
                _ =>
                    ::rustc_middle::util::bug::bug_fmt(format_args!("shouldn\'t have created a ValTree for {0:?}",
                            ty)),
            }
        }
    }
}#[instrument(skip(ecx), level = "debug")]
406fn valtree_into_mplace<'tcx>(
407    ecx: &mut CompileTimeInterpCx<'tcx>,
408    place: &MPlaceTy<'tcx>,
409    valtree: ty::ValTree<'tcx>,
410) {
411    // This will match on valtree and write the value(s) corresponding to the ValTree
412    // inside the place recursively.
413
414    let ty = place.layout.ty;
415
416    match ty.kind() {
417        ty::FnDef(_, _) => {
418            // Zero-sized type, nothing to do.
419        }
420        ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char | ty::RawPtr(..) => {
421            let scalar_int = valtree.to_leaf();
422            debug!("writing trivial valtree {:?} to place {:?}", scalar_int, place);
423            ecx.write_immediate(Immediate::Scalar(scalar_int.into()), place).unwrap();
424        }
425        ty::Ref(_, inner_ty, _) => {
426            let imm = valtree_to_ref(ecx, valtree, *inner_ty);
427            debug!(?imm);
428            ecx.write_immediate(imm, place).unwrap();
429        }
430        ty::Adt(_, _) | ty::Tuple(_) | ty::Array(_, _) | ty::Str | ty::Slice(_) => {
431            let branches = valtree.to_branch();
432
433            // Need to downcast place for enums
434            let (place_adjusted, branches, variant_idx) = match ty.kind() {
435                ty::Adt(def, _) if def.is_enum() => {
436                    // First element of valtree corresponds to variant
437                    let scalar_int = branches[0].to_leaf();
438                    let variant_idx = VariantIdx::from_u32(scalar_int.to_u32());
439                    let variant = def.variant(variant_idx);
440                    debug!(?variant);
441
442                    (
443                        ecx.project_downcast(place, variant_idx).unwrap(),
444                        &branches[1..],
445                        Some(variant_idx),
446                    )
447                }
448                _ => (place.clone(), branches.as_slice(), None),
449            };
450            debug!(?place_adjusted, ?branches);
451
452            // Create the places (by indexing into `place`) for the fields and fill
453            // them recursively
454            for (i, inner_valtree) in branches.iter().enumerate() {
455                debug!(?i, ?inner_valtree);
456
457                let place_inner = match ty.kind() {
458                    ty::Str | ty::Slice(_) | ty::Array(..) => {
459                        ecx.project_index(place, i as u64).unwrap()
460                    }
461                    _ => ecx.project_field(&place_adjusted, FieldIdx::from_usize(i)).unwrap(),
462                };
463
464                debug!(?place_inner);
465                valtree_into_mplace(ecx, &place_inner, inner_valtree.to_value().valtree);
466                dump_place(ecx, &place_inner);
467            }
468
469            debug!("dump of place_adjusted:");
470            dump_place(ecx, &place_adjusted);
471
472            if let Some(variant_idx) = variant_idx {
473                // don't forget filling the place with the discriminant of the enum
474                ecx.write_discriminant(variant_idx, place).unwrap();
475            }
476
477            debug!("dump of place after writing discriminant:");
478            dump_place(ecx, place);
479        }
480        _ => bug!("shouldn't have created a ValTree for {:?}", ty),
481    }
482}
483
484fn dump_place<'tcx>(ecx: &CompileTimeInterpCx<'tcx>, place: &MPlaceTy<'tcx>) {
485    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/const_eval/valtrees.rs:485",
                        "rustc_const_eval::const_eval::valtrees",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/const_eval/valtrees.rs"),
                        ::tracing_core::__macro_support::Option::Some(485u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::valtrees"),
                        ::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!("{0:?}",
                                                    ecx.dump_place(&PlaceTy::from(place.clone()))) as
                                            &dyn Value))])
            });
    } else { ; }
};trace!("{:?}", ecx.dump_place(&PlaceTy::from(place.clone())));
486}