Skip to main content

rustc_codegen_ssa/mir/
constant.rs

1use rustc_abi::BackendRepr;
2use rustc_middle::mir;
3use rustc_middle::mir::interpret::ErrorHandled;
4use rustc_middle::ty::consts::ConstExt;
5use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv};
6use rustc_middle::ty::{self, Ty};
7use rustc_span::{bug, span_bug};
8
9use super::FunctionCx;
10use crate::diagnostics;
11use crate::mir::operand::OperandRef;
12use crate::traits::*;
13
14impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
15    pub(crate) fn eval_mir_constant_to_operand(
16        &self,
17        bx: &mut Bx,
18        constant: &mir::ConstOperand<'tcx>,
19    ) -> OperandRef<'tcx, Bx::Value> {
20        let val = self.eval_mir_constant(constant);
21        let ty = self.monomorphize(constant.ty());
22        OperandRef::from_const(bx, val, ty)
23    }
24
25    pub fn eval_mir_constant(&self, constant: &mir::ConstOperand<'tcx>) -> mir::ConstValue {
26        // `MirUsedCollector` visited all required_consts before codegen began, so if we got here
27        // there can be no more constants that fail to evaluate.
28        self.monomorphize(constant.const_)
29            .eval(self.cx.tcx(), self.cx.typing_env(), constant.span)
30            .expect("erroneous constant missed by mono item collection")
31    }
32
33    /// This is a convenience helper for `immediate_const_vector`. It has the precondition
34    /// that the given `constant` is an `Const::Unevaluated` and must be convertible to
35    /// a `ValTree`. If you want a more general version of this, talk to `wg-const-eval` on zulip.
36    ///
37    /// Note that this function is cursed, since usually MIR consts should not be evaluated to
38    /// valtrees!
39    fn eval_unevaluated_mir_constant_to_valtree(
40        &self,
41        constant: &mir::ConstOperand<'tcx>,
42    ) -> Result<Result<ty::ValTree<'tcx>, Ty<'tcx>>, ErrorHandled> {
43        let tcx = self.cx.tcx();
44        let uv = match self.monomorphize(constant.const_) {
45            mir::Const::Unevaluated(uv, _) => uv.shrink(tcx),
46            mir::Const::Ty(_, c) => match c.kind() {
47                // A constant that came from a const generic but was then used as an argument to
48                // old-style simd_shuffle (passing as argument instead of as a generic param).
49                ty::ConstKind::Value(cv) => return Ok(Ok(cv.valtree)),
50                other => ::rustc_span::macros::bug_impl(Some(constant.span),
    format_args!("{0:#?}", other), Location::caller())span_bug!(constant.span, "{other:#?}"),
51            },
52            // We should never encounter `Const::Val` unless MIR opts (like const prop) evaluate
53            // a constant and write that value back into `Operand`s. This could happen, but is
54            // unlikely. Also: all users of `simd_shuffle` are on unstable and already need to take
55            // a lot of care around intrinsics. For an issue to happen here, it would require a
56            // macro expanding to a `simd_shuffle` call without wrapping the constant argument in a
57            // `const {}` block, but the user pass through arbitrary expressions.
58            // FIXME(oli-obk): replace the magic const generic argument of `simd_shuffle` with a
59            // real const generic, and get rid of this entire function.
60            other => ::rustc_span::macros::bug_impl(Some(constant.span),
    format_args!("{0:#?}", other), Location::caller())span_bug!(constant.span, "{other:#?}"),
61        };
62        let uv = self.monomorphize(uv);
63        tcx.const_eval_resolve_for_typeck(self.cx.typing_env(), uv, constant.span)
64    }
65
66    /// process constant containing SIMD shuffle indices & constant vectors
67    pub fn immediate_const_vector(
68        &mut self,
69        bx: &Bx,
70        constant: &mir::ConstOperand<'tcx>,
71    ) -> (Bx::Value, Ty<'tcx>) {
72        let ty = self.monomorphize(constant.ty());
73        if !ty.is_simd() {
    ::core::panicking::panic("assertion failed: ty.is_simd()")
};assert!(ty.is_simd());
74        let field_ty = ty.simd_size_and_type(bx.tcx()).1;
75
76        let val = self
77            .eval_unevaluated_mir_constant_to_valtree(constant)
78            .ok()
79            .map(|x| x.ok())
80            .flatten()
81            .map(|val| {
82                // A SIMD type has a single field, which is an array.
83                let fields = val.to_branch();
84                {
    match (&fields.len(), &1) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(fields.len(), 1);
85                let array = fields[0].to_branch();
86                // Iterate over the array elements to obtain the values in the vector.
87                let values: Vec<_> = array
88                    .iter()
89                    .map(|field| {
90                        let Some(prim) = field.try_to_scalar() else {
91                            ::rustc_span::macros::bug_impl(None,
    format_args!("field is not a scalar {0:?}", field), Location::caller())bug!("field is not a scalar {:?}", field)
92                        };
93                        let layout = bx.layout_of(field_ty);
94                        let BackendRepr::Scalar(scalar) = layout.backend_repr else {
95                            ::rustc_span::macros::bug_impl(None,
    format_args!("from_const: invalid ByVal layout: {0:#?}", layout),
    Location::caller());bug!("from_const: invalid ByVal layout: {:#?}", layout);
96                        };
97                        bx.scalar_to_backend(prim, scalar, bx.immediate_backend_type(layout))
98                    })
99                    .collect();
100                bx.const_vector(&values)
101            })
102            .unwrap_or_else(|| {
103                bx.tcx()
104                    .dcx()
105                    .emit_err(diagnostics::ShuffleIndicesEvaluation { span: constant.span });
106                // We've errored, so we don't have to produce working code.
107                let llty = bx.backend_type(bx.layout_of(ty));
108                bx.const_undef(llty)
109            });
110        (val, ty)
111    }
112}