Skip to main content

rustc_const_eval/interpret/
intrinsics.rs

1//! Intrinsics and other functions that the interpreter executes without
2//! looking at their MIR. Intrinsics/functions supported here are shared by CTFE
3//! and miri.
4
5mod simd;
6
7use std::assert_matches;
8
9use rustc_abi::{FieldIdx, HasDataLayout, Size, VariantIdx};
10use rustc_apfloat::ieee::{Double, Half, Quad, Single};
11use rustc_errors::msg;
12use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, read_target_uint, write_target_uint};
13use rustc_middle::mir::{self, BinOp, ConstValue, NonDivergingIntrinsic};
14use rustc_middle::ty::layout::TyAndLayout;
15use rustc_middle::ty::{FloatTy, Ty, TyCtxt, TypeVisitableExt};
16use rustc_middle::{bug, span_bug, ty};
17use rustc_span::{Symbol, sym};
18use tracing::trace;
19
20use super::memory::MemoryKind;
21use super::util::ensure_monomorphic_enough;
22use super::{
23    AllocId, CheckInAllocMsg, ImmTy, InterpCx, InterpResult, Machine, OpTy, PlaceTy, Pointer,
24    PointerArithmetic, Projectable, Provenance, Scalar, err_ub_custom, err_unsup_format, interp_ok,
25    throw_inval, throw_ub, throw_ub_custom, throw_ub_format, throw_unsup_format,
26};
27use crate::interpret::Writeable;
28
29#[derive(#[automatically_derived]
impl ::core::marker::Copy for MulAddType { }Copy, #[automatically_derived]
impl ::core::clone::Clone for MulAddType {
    #[inline]
    fn clone(&self) -> MulAddType { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for MulAddType {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                MulAddType::Fused => "Fused",
                MulAddType::Nondeterministic => "Nondeterministic",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for MulAddType {
    #[inline]
    fn eq(&self, other: &MulAddType) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MulAddType {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
30enum MulAddType {
31    /// Used with `fma` and `simd_fma`, always uses fused-multiply-add
32    Fused,
33    /// Used with `fmuladd` and `simd_relaxed_fma`, nondeterministically determines whether to use
34    /// fma or simple multiply-add
35    Nondeterministic,
36}
37
38#[derive(#[automatically_derived]
impl ::core::marker::Copy for MinMax { }Copy, #[automatically_derived]
impl ::core::clone::Clone for MinMax {
    #[inline]
    fn clone(&self) -> MinMax { *self }
}Clone)]
39pub(crate) enum MinMax {
40    /// The IEEE-2019 `minimum` operation - see `f32::minimum` etc.
41    /// In particular, `-0.0` is considered smaller than `+0.0` and
42    /// if either input is NaN, the result is NaN.
43    Minimum,
44    /// The IEEE-2008 `minNum` operation with the SNaN handling of the
45    /// IEEE-2019 `minimumNumber` operation - see `f32::min` etc.
46    /// In particular, if the inputs are `-0.0` and `+0.0`, the result is non-deterministic,
47    /// and if one argument is NaN (quiet or signaling), the other one is returned.
48    MinimumNumber,
49    /// The IEEE-2019 `maximum` operation - see `f32::maximum` etc.
50    /// In particular, `-0.0` is considered smaller than `+0.0` and
51    /// if either input is NaN, the result is NaN.
52    Maximum,
53    /// The IEEE-2008 `maxNum` operation with the SNaN handling of the
54    /// IEEE-2019 `maximumNumber` operation - see `f32::max` etc.
55    /// In particular, if the inputs are `-0.0` and `+0.0`, the result is non-deterministic,
56    /// and if one argument is NaN (quiet or signaling), the other one is returned.
57    MaximumNumber,
58}
59
60/// Directly returns an `Allocation` containing an absolute path representation of the given type.
61pub(crate) fn alloc_type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (AllocId, u64) {
62    let path = crate::util::type_name(tcx, ty);
63    let bytes = path.into_bytes();
64    let len = bytes.len().try_into().unwrap();
65    (tcx.allocate_bytes_dedup(bytes, CTFE_ALLOC_SALT), len)
66}
67impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
68    /// Generates a value of `TypeId` for `ty` in-place.
69    pub(crate) fn write_type_id(
70        &mut self,
71        ty: Ty<'tcx>,
72        dest: &impl Writeable<'tcx, M::Provenance>,
73    ) -> InterpResult<'tcx, ()> {
74        if true {
    if !!ty.has_erasable_regions() {
        {
            ::core::panicking::panic_fmt(format_args!("type {0:?} has regions that need erasing before writing a TypeId",
                    ty));
        }
    };
};debug_assert!(
75            !ty.has_erasable_regions(),
76            "type {ty:?} has regions that need erasing before writing a TypeId",
77        );
78
79        let tcx = self.tcx;
80        let type_id_hash = tcx.type_id_hash(ty).as_u128();
81        let op = self.const_val_to_op(
82            ConstValue::Scalar(Scalar::from_u128(type_id_hash)),
83            tcx.types.u128,
84            None,
85        )?;
86        self.copy_op_allow_transmute(&op, dest)?;
87
88        // Give the each pointer-sized chunk provenance that knows about the type id.
89        // Here we rely on `TypeId` being a newtype around an array of pointers, so we
90        // first project to its only field and then the array elements.
91        let alloc_id = tcx.reserve_and_set_type_id_alloc(ty);
92        let arr = self.project_field(dest, FieldIdx::ZERO)?;
93        let mut elem_iter = self.project_array_fields(&arr)?;
94        while let Some((_, elem)) = elem_iter.next(self)? {
95            // Decorate this part of the hash with provenance; leave the integer part unchanged.
96            let hash_fragment = self.read_scalar(&elem)?.to_target_usize(&tcx)?;
97            let ptr = Pointer::new(alloc_id.into(), Size::from_bytes(hash_fragment));
98            let ptr = self.global_root_pointer(ptr)?;
99            let val = Scalar::from_pointer(ptr, &tcx);
100            self.write_scalar(val, &elem)?;
101        }
102        interp_ok(())
103    }
104
105    /// Read a value of type `TypeId`, returning the type it represents.
106    pub(crate) fn read_type_id(
107        &self,
108        op: &OpTy<'tcx, M::Provenance>,
109    ) -> InterpResult<'tcx, Ty<'tcx>> {
110        // `TypeId` is a newtype around an array of pointers. All pointers must have the same
111        // provenance, and that provenance represents the type.
112        let ptr_size = self.pointer_size().bytes_usize();
113        let arr = self.project_field(op, FieldIdx::ZERO)?;
114
115        let mut ty_and_hash = None;
116        let mut elem_iter = self.project_array_fields(&arr)?;
117        while let Some((idx, elem)) = elem_iter.next(self)? {
118            let elem = self.read_pointer(&elem)?;
119            let (elem_ty, elem_hash) = self.get_ptr_type_id(elem)?;
120            // If this is the first element, remember the type and its hash.
121            // If this is not the first element, ensure it is consistent with the previous ones.
122            let full_hash = match ty_and_hash {
123                None => {
124                    let hash = self.tcx.type_id_hash(elem_ty).as_u128();
125                    let mut hash_bytes = [0u8; 16];
126                    write_target_uint(self.data_layout().endian, &mut hash_bytes, hash).unwrap();
127                    ty_and_hash = Some((elem_ty, hash_bytes));
128                    hash_bytes
129                }
130                Some((ty, hash_bytes)) => {
131                    if ty != elem_ty {
132                        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `TypeId` value: not all bytes carry the same type id metadata"))
                })));throw_ub_format!(
133                            "invalid `TypeId` value: not all bytes carry the same type id metadata"
134                        );
135                    }
136                    hash_bytes
137                }
138            };
139            // Ensure the elem_hash matches the corresponding part of the full hash.
140            let hash_frag = &full_hash[(idx as usize) * ptr_size..][..ptr_size];
141            if read_target_uint(self.data_layout().endian, hash_frag).unwrap() != elem_hash.into() {
142                do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `TypeId` value: the hash does not match the type id metadata"))
                })));throw_ub_format!(
143                    "invalid `TypeId` value: the hash does not match the type id metadata"
144                );
145            }
146        }
147
148        interp_ok(ty_and_hash.unwrap().0)
149    }
150
151    /// Returns `true` if emulation happened.
152    /// Here we implement the intrinsics that are common to all Miri instances; individual machines can add their own
153    /// intrinsic handling.
154    pub fn eval_intrinsic(
155        &mut self,
156        instance: ty::Instance<'tcx>,
157        args: &[OpTy<'tcx, M::Provenance>],
158        dest: &PlaceTy<'tcx, M::Provenance>,
159        ret: Option<mir::BasicBlock>,
160    ) -> InterpResult<'tcx, bool> {
161        let instance_args = instance.args;
162        let intrinsic_name = self.tcx.item_name(instance.def_id());
163
164        if intrinsic_name.as_str().starts_with("simd_") {
165            return self.eval_simd_intrinsic(intrinsic_name, instance_args, args, dest, ret);
166        }
167
168        let tcx = self.tcx.tcx;
169
170        match intrinsic_name {
171            sym::type_name => {
172                let tp_ty = instance.args.type_at(0);
173                ensure_monomorphic_enough(tcx, tp_ty)?;
174                let (alloc_id, meta) = alloc_type_name(tcx, tp_ty);
175                let val = ConstValue::Slice { alloc_id, meta };
176                let val = self.const_val_to_op(val, dest.layout.ty, Some(dest.layout))?;
177                self.copy_op(&val, dest)?;
178            }
179            sym::needs_drop => {
180                let tp_ty = instance.args.type_at(0);
181                ensure_monomorphic_enough(tcx, tp_ty)?;
182                let val = ConstValue::from_bool(tp_ty.needs_drop(tcx, self.typing_env));
183                let val = self.const_val_to_op(val, tcx.types.bool, Some(dest.layout))?;
184                self.copy_op(&val, dest)?;
185            }
186            sym::type_id => {
187                let tp_ty = instance.args.type_at(0);
188                ensure_monomorphic_enough(tcx, tp_ty)?;
189                self.write_type_id(tp_ty, dest)?;
190            }
191            sym::type_id_eq => {
192                let a_ty = self.read_type_id(&args[0])?;
193                let b_ty = self.read_type_id(&args[1])?;
194                self.write_scalar(Scalar::from_bool(a_ty == b_ty), dest)?;
195            }
196            sym::size_of => {
197                let tp_ty = instance.args.type_at(0);
198                let layout = self.layout_of(tp_ty)?;
199                if !layout.is_sized() {
200                    ::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
    format_args!("unsized type for `size_of`"));span_bug!(self.cur_span(), "unsized type for `size_of`");
201                }
202                let val = layout.size.bytes();
203                self.write_scalar(Scalar::from_target_usize(val, self), dest)?;
204            }
205            sym::align_of => {
206                let tp_ty = instance.args.type_at(0);
207                let layout = self.layout_of(tp_ty)?;
208                if !layout.is_sized() {
209                    ::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
    format_args!("unsized type for `align_of`"));span_bug!(self.cur_span(), "unsized type for `align_of`");
210                }
211                let val = layout.align.bytes();
212                self.write_scalar(Scalar::from_target_usize(val, self), dest)?;
213            }
214            sym::offset_of => {
215                let tp_ty = instance.args.type_at(0);
216
217                let variant = self.read_scalar(&args[0])?.to_u32()?;
218                let field = self.read_scalar(&args[1])?.to_u32()? as usize;
219
220                let layout = self.layout_of(tp_ty)?;
221                let cx = ty::layout::LayoutCx::new(*self.tcx, self.typing_env);
222
223                let layout = layout.for_variant(&cx, VariantIdx::from_u32(variant));
224                let offset = layout.fields.offset(field).bytes();
225
226                self.write_scalar(Scalar::from_target_usize(offset, self), dest)?;
227            }
228            sym::variant_count => {
229                let tp_ty = instance.args.type_at(0);
230                let ty = match tp_ty.kind() {
231                    // Pattern types have the same number of variants as their base type.
232                    // Even if we restrict e.g. which variants are valid, the variants are essentially just uninhabited.
233                    // And `Result<(), !>` still has two variants according to `variant_count`.
234                    ty::Pat(base, _) => *base,
235                    _ => tp_ty,
236                };
237                let val = match ty.kind() {
238                    // Correctly handles non-monomorphic calls, so there is no need for ensure_monomorphic_enough.
239                    ty::Adt(adt, _) => {
240                        ConstValue::from_target_usize(adt.variants().len() as u64, &tcx)
241                    }
242                    ty::Alias(..) | ty::Param(_) | ty::Placeholder(_) | ty::Infer(_) => {
243                        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::TooGeneric)throw_inval!(TooGeneric)
244                    }
245                    ty::Pat(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
246                    ty::Bound(_, _) => ::rustc_middle::util::bug::bug_fmt(format_args!("bound ty during ctfe"))bug!("bound ty during ctfe"),
247                    ty::Bool
248                    | ty::Char
249                    | ty::Int(_)
250                    | ty::Uint(_)
251                    | ty::Float(_)
252                    | ty::Foreign(_)
253                    | ty::Str
254                    | ty::Array(_, _)
255                    | ty::Slice(_)
256                    | ty::RawPtr(_, _)
257                    | ty::Ref(_, _, _)
258                    | ty::FnDef(_, _)
259                    | ty::FnPtr(..)
260                    | ty::Dynamic(_, _)
261                    | ty::Closure(_, _)
262                    | ty::CoroutineClosure(_, _)
263                    | ty::Coroutine(_, _)
264                    | ty::CoroutineWitness(..)
265                    | ty::UnsafeBinder(_)
266                    | ty::Never
267                    | ty::Tuple(_)
268                    | ty::Error(_) => ConstValue::from_target_usize(0u64, &tcx),
269                };
270                let val = self.const_val_to_op(val, dest.layout.ty, Some(dest.layout))?;
271                self.copy_op(&val, dest)?;
272            }
273
274            sym::caller_location => {
275                let span = self.find_closest_untracked_caller_location();
276                let val = self.tcx.span_as_caller_location(span);
277                let val =
278                    self.const_val_to_op(val, self.tcx.caller_location_ty(), Some(dest.layout))?;
279                self.copy_op(&val, dest)?;
280            }
281
282            sym::align_of_val | sym::size_of_val => {
283                // Avoid `deref_pointer` -- this is not a deref, the ptr does not have to be
284                // dereferenceable!
285                let place = self.ref_to_mplace(&self.read_immediate(&args[0])?)?;
286                let (size, align) = self
287                    .size_and_align_of_val(&place)?
288                    .ok_or_else(|| ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("`extern type` does not have known layout"))
            })))err_unsup_format!("`extern type` does not have known layout"))?;
289
290                let result = match intrinsic_name {
291                    sym::align_of_val => align.bytes(),
292                    sym::size_of_val => size.bytes(),
293                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
294                };
295
296                self.write_scalar(Scalar::from_target_usize(result, self), dest)?;
297            }
298
299            sym::fadd_algebraic
300            | sym::fsub_algebraic
301            | sym::fmul_algebraic
302            | sym::fdiv_algebraic
303            | sym::frem_algebraic => {
304                let a = self.read_immediate(&args[0])?;
305                let b = self.read_immediate(&args[1])?;
306
307                let op = match intrinsic_name {
308                    sym::fadd_algebraic => BinOp::Add,
309                    sym::fsub_algebraic => BinOp::Sub,
310                    sym::fmul_algebraic => BinOp::Mul,
311                    sym::fdiv_algebraic => BinOp::Div,
312                    sym::frem_algebraic => BinOp::Rem,
313
314                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
315                };
316
317                let res = self.binary_op(op, &a, &b)?;
318                // `binary_op` already called `generate_nan` if needed.
319                let res = M::apply_float_nondet(self, res)?;
320                self.write_immediate(*res, dest)?;
321            }
322
323            sym::ctpop
324            | sym::cttz
325            | sym::cttz_nonzero
326            | sym::ctlz
327            | sym::ctlz_nonzero
328            | sym::bswap
329            | sym::bitreverse => {
330                let ty = instance_args.type_at(0);
331                let layout = self.layout_of(ty)?;
332                let val = self.read_scalar(&args[0])?;
333
334                let out_val = self.numeric_intrinsic(intrinsic_name, val, layout, dest.layout)?;
335                self.write_scalar(out_val, dest)?;
336            }
337            sym::saturating_add | sym::saturating_sub => {
338                let l = self.read_immediate(&args[0])?;
339                let r = self.read_immediate(&args[1])?;
340                let val = self.saturating_arith(
341                    if intrinsic_name == sym::saturating_add { BinOp::Add } else { BinOp::Sub },
342                    &l,
343                    &r,
344                )?;
345                self.write_scalar(val, dest)?;
346            }
347            sym::discriminant_value => {
348                let place = self.deref_pointer(&args[0])?;
349                let variant = self.read_discriminant(&place)?;
350                let discr = self.discriminant_for_variant(place.layout.ty, variant)?;
351                self.write_immediate(*discr, dest)?;
352            }
353            sym::exact_div => {
354                let l = self.read_immediate(&args[0])?;
355                let r = self.read_immediate(&args[1])?;
356                self.exact_div(&l, &r, dest)?;
357            }
358            sym::copy => {
359                self.copy_intrinsic(&args[0], &args[1], &args[2], /*nonoverlapping*/ false)?;
360            }
361            sym::write_bytes => {
362                self.write_bytes_intrinsic(&args[0], &args[1], &args[2], "write_bytes")?;
363            }
364            sym::compare_bytes => {
365                let result = self.compare_bytes_intrinsic(&args[0], &args[1], &args[2])?;
366                self.write_scalar(result, dest)?;
367            }
368            sym::arith_offset => {
369                let ptr = self.read_pointer(&args[0])?;
370                let offset_count = self.read_target_isize(&args[1])?;
371                let pointee_ty = instance_args.type_at(0);
372
373                let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
374                let offset_bytes = offset_count.wrapping_mul(pointee_size);
375                let offset_ptr = ptr.wrapping_signed_offset(offset_bytes, self);
376                self.write_pointer(offset_ptr, dest)?;
377            }
378            sym::ptr_offset_from | sym::ptr_offset_from_unsigned => {
379                let a = self.read_pointer(&args[0])?;
380                let b = self.read_pointer(&args[1])?;
381
382                let usize_layout = self.layout_of(self.tcx.types.usize)?;
383                let isize_layout = self.layout_of(self.tcx.types.isize)?;
384
385                // Get offsets for both that are at least relative to the same base.
386                // With `OFFSET_IS_ADDR` this is trivial; without it we need either
387                // two integers or two pointers into the same allocation.
388                let (a_offset, b_offset, is_addr) = if M::Provenance::OFFSET_IS_ADDR {
389                    (a.addr().bytes(), b.addr().bytes(), /*is_addr*/ true)
390                } else {
391                    match (self.ptr_try_get_alloc_id(a, 0), self.ptr_try_get_alloc_id(b, 0)) {
392                        (Err(a), Err(b)) => {
393                            // Neither pointer points to an allocation, so they are both absolute.
394                            (a, b, /*is_addr*/ true)
395                        }
396                        (Ok((a_alloc_id, a_offset, _)), Ok((b_alloc_id, b_offset, _)))
397                            if a_alloc_id == b_alloc_id =>
398                        {
399                            // Found allocation for both, and it's the same.
400                            // Use these offsets for distance calculation.
401                            (a_offset.bytes(), b_offset.bytes(), /*is_addr*/ false)
402                        }
403                        _ => {
404                            // Not into the same allocation -- this is UB.
405                            do yeet {
        let (name,) = (intrinsic_name,);
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                    msg: ||
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$name}` called on two different pointers that are not both derived from the same allocation")),
                    add_args: Box::new(move |mut set_arg|
                            {
                                set_arg("name".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(name, &mut None));
                            }),
                }))
    };throw_ub_custom!(
406                                msg!(
407                                    "`{$name}` called on two different pointers that are not both derived from the same allocation"
408                                ),
409                                name = intrinsic_name,
410                            );
411                        }
412                    }
413                };
414
415                // Compute distance: a - b.
416                let dist = {
417                    // Addresses are unsigned, so this is a `usize` computation. We have to do the
418                    // overflow check separately anyway.
419                    let (val, overflowed) = {
420                        let a_offset = ImmTy::from_uint(a_offset, usize_layout);
421                        let b_offset = ImmTy::from_uint(b_offset, usize_layout);
422                        self.binary_op(BinOp::SubWithOverflow, &a_offset, &b_offset)?
423                            .to_scalar_pair()
424                    };
425                    if overflowed.to_bool()? {
426                        // a < b
427                        if intrinsic_name == sym::ptr_offset_from_unsigned {
428                            do yeet {
        let (a_offset, b_offset, is_addr) = (a_offset, b_offset, is_addr);
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                    msg: ||
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`ptr_offset_from_unsigned` called when first pointer has smaller {$is_addr ->\n                                        [true] address\n                                        *[false] offset\n                                    } than second: {$a_offset} < {$b_offset}")),
                    add_args: Box::new(move |mut set_arg|
                            {
                                set_arg("a_offset".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(a_offset,
                                        &mut None));
                                set_arg("b_offset".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(b_offset,
                                        &mut None));
                                set_arg("is_addr".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(is_addr,
                                        &mut None));
                            }),
                }))
    };throw_ub_custom!(
429                                msg!(
430                                    "`ptr_offset_from_unsigned` called when first pointer has smaller {$is_addr ->
431                                        [true] address
432                                        *[false] offset
433                                    } than second: {$a_offset} < {$b_offset}"
434                                ),
435                                a_offset = a_offset,
436                                b_offset = b_offset,
437                                is_addr = is_addr,
438                            );
439                        }
440                        // The signed form of the intrinsic allows this. If we interpret the
441                        // difference as isize, we'll get the proper signed difference. If that
442                        // seems *positive* or equal to isize::MIN, they were more than isize::MAX apart.
443                        let dist = val.to_target_isize(self)?;
444                        if dist >= 0 || i128::from(dist) == self.pointer_size().signed_int_min() {
445                            do yeet {
        let (name,) = (intrinsic_name,);
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                    msg: ||
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$name}` called when first pointer is too far before second")),
                    add_args: Box::new(move |mut set_arg|
                            {
                                set_arg("name".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(name, &mut None));
                            }),
                }))
    };throw_ub_custom!(
446                                msg!(
447                                    "`{$name}` called when first pointer is too far before second"
448                                ),
449                                name = intrinsic_name,
450                            );
451                        }
452                        dist
453                    } else {
454                        // b >= a
455                        let dist = val.to_target_isize(self)?;
456                        // If converting to isize produced a *negative* result, we had an overflow
457                        // because they were more than isize::MAX apart.
458                        if dist < 0 {
459                            do yeet {
        let (name,) = (intrinsic_name,);
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                    msg: ||
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$name}` called when first pointer is too far ahead of second")),
                    add_args: Box::new(move |mut set_arg|
                            {
                                set_arg("name".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(name, &mut None));
                            }),
                }))
    };throw_ub_custom!(
460                                msg!(
461                                    "`{$name}` called when first pointer is too far ahead of second"
462                                ),
463                                name = intrinsic_name,
464                            );
465                        }
466                        dist
467                    }
468                };
469
470                // Check that the memory between them is dereferenceable at all, starting from the
471                // origin pointer: `dist` is `a - b`, so it is based on `b`.
472                self.check_ptr_access_signed(b, dist, CheckInAllocMsg::Dereferenceable)
473                    .map_err_kind(|_| {
474                        // This could mean they point to different allocations, or they point to the same allocation
475                        // but not the entire range between the pointers is in-bounds.
476                        if let Ok((a_alloc_id, ..)) = self.ptr_try_get_alloc_id(a, 0)
477                            && let Ok((b_alloc_id, ..)) = self.ptr_try_get_alloc_id(b, 0)
478                            && a_alloc_id == b_alloc_id
479                        {
480                            {
    let (name,) = (intrinsic_name,);
    ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                msg: ||
                    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$name}` called on two different pointers where the memory range between them is not in-bounds of an allocation")),
                add_args: Box::new(move |mut set_arg|
                        {
                            set_arg("name".into(),
                                rustc_errors::IntoDiagArg::into_diag_arg(name, &mut None));
                        }),
            }))
}err_ub_custom!(
481                                msg!("`{$name}` called on two different pointers where the memory range between them is not in-bounds of an allocation"),
482                                name = intrinsic_name,
483                            )
484                        } else {
485                            {
    let (name,) = (intrinsic_name,);
    ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                msg: ||
                    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$name}` called on two different pointers that are not both derived from the same allocation")),
                add_args: Box::new(move |mut set_arg|
                        {
                            set_arg("name".into(),
                                rustc_errors::IntoDiagArg::into_diag_arg(name, &mut None));
                        }),
            }))
}err_ub_custom!(
486                                msg!("`{$name}` called on two different pointers that are not both derived from the same allocation"),
487                                name = intrinsic_name,
488                            )
489                        }
490                    })?;
491                // Then check that this is also dereferenceable from `a`. This ensures that they are
492                // derived from the same allocation.
493                self.check_ptr_access_signed(
494                    a,
495                    dist.checked_neg().unwrap(), // i64::MIN is impossible as no allocation can be that large
496                    CheckInAllocMsg::Dereferenceable,
497                )
498                .map_err_kind(|_| {
499                    // Make the error more specific.
500                    {
    let (name,) = (intrinsic_name,);
    ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                msg: ||
                    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$name}` called on two different pointers that are not both derived from the same allocation")),
                add_args: Box::new(move |mut set_arg|
                        {
                            set_arg("name".into(),
                                rustc_errors::IntoDiagArg::into_diag_arg(name, &mut None));
                        }),
            }))
}err_ub_custom!(
501                        msg!("`{$name}` called on two different pointers that are not both derived from the same allocation"),
502                        name = intrinsic_name,
503                    )
504                })?;
505
506                // Perform division by size to compute return value.
507                let ret_layout = if intrinsic_name == sym::ptr_offset_from_unsigned {
508                    if !(0 <= dist && dist <= self.target_isize_max()) {
    ::core::panicking::panic("assertion failed: 0 <= dist && dist <= self.target_isize_max()")
};assert!(0 <= dist && dist <= self.target_isize_max());
509                    usize_layout
510                } else {
511                    if !(self.target_isize_min() <= dist && dist <= self.target_isize_max()) {
    ::core::panicking::panic("assertion failed: self.target_isize_min() <= dist && dist <= self.target_isize_max()")
};assert!(self.target_isize_min() <= dist && dist <= self.target_isize_max());
512                    isize_layout
513                };
514                let pointee_layout = self.layout_of(instance_args.type_at(0))?;
515                // If ret_layout is unsigned, we checked that so is the distance, so we are good.
516                let val = ImmTy::from_int(dist, ret_layout);
517                let size = ImmTy::from_int(pointee_layout.size.bytes(), ret_layout);
518                self.exact_div(&val, &size, dest)?;
519            }
520
521            sym::black_box => {
522                // These just return their argument
523                self.copy_op(&args[0], dest)?;
524            }
525            sym::raw_eq => {
526                let result = self.raw_eq_intrinsic(&args[0], &args[1])?;
527                self.write_scalar(result, dest)?;
528            }
529            sym::typed_swap_nonoverlapping => {
530                self.typed_swap_nonoverlapping_intrinsic(&args[0], &args[1])?;
531            }
532
533            sym::vtable_size => {
534                let ptr = self.read_pointer(&args[0])?;
535                // `None` because we don't know which trait to expect here; any vtable is okay.
536                let (size, _align) = self.get_vtable_size_and_align(ptr, None)?;
537                self.write_scalar(Scalar::from_target_usize(size.bytes(), self), dest)?;
538            }
539            sym::vtable_align => {
540                let ptr = self.read_pointer(&args[0])?;
541                // `None` because we don't know which trait to expect here; any vtable is okay.
542                let (_size, align) = self.get_vtable_size_and_align(ptr, None)?;
543                self.write_scalar(Scalar::from_target_usize(align.bytes(), self), dest)?;
544            }
545
546            sym::minnumf16 => {
547                self.float_minmax_intrinsic::<Half>(args, MinMax::MinimumNumber, dest)?
548            }
549            sym::minnumf32 => {
550                self.float_minmax_intrinsic::<Single>(args, MinMax::MinimumNumber, dest)?
551            }
552            sym::minnumf64 => {
553                self.float_minmax_intrinsic::<Double>(args, MinMax::MinimumNumber, dest)?
554            }
555            sym::minnumf128 => {
556                self.float_minmax_intrinsic::<Quad>(args, MinMax::MinimumNumber, dest)?
557            }
558
559            sym::minimumf16 => self.float_minmax_intrinsic::<Half>(args, MinMax::Minimum, dest)?,
560            sym::minimumf32 => {
561                self.float_minmax_intrinsic::<Single>(args, MinMax::Minimum, dest)?
562            }
563            sym::minimumf64 => {
564                self.float_minmax_intrinsic::<Double>(args, MinMax::Minimum, dest)?
565            }
566            sym::minimumf128 => self.float_minmax_intrinsic::<Quad>(args, MinMax::Minimum, dest)?,
567
568            sym::maxnumf16 => {
569                self.float_minmax_intrinsic::<Half>(args, MinMax::MaximumNumber, dest)?
570            }
571            sym::maxnumf32 => {
572                self.float_minmax_intrinsic::<Single>(args, MinMax::MaximumNumber, dest)?
573            }
574            sym::maxnumf64 => {
575                self.float_minmax_intrinsic::<Double>(args, MinMax::MaximumNumber, dest)?
576            }
577            sym::maxnumf128 => {
578                self.float_minmax_intrinsic::<Quad>(args, MinMax::MaximumNumber, dest)?
579            }
580
581            sym::maximumf16 => self.float_minmax_intrinsic::<Half>(args, MinMax::Maximum, dest)?,
582            sym::maximumf32 => {
583                self.float_minmax_intrinsic::<Single>(args, MinMax::Maximum, dest)?
584            }
585            sym::maximumf64 => {
586                self.float_minmax_intrinsic::<Double>(args, MinMax::Maximum, dest)?
587            }
588            sym::maximumf128 => self.float_minmax_intrinsic::<Quad>(args, MinMax::Maximum, dest)?,
589
590            sym::copysignf16 => self.float_copysign_intrinsic::<Half>(args, dest)?,
591            sym::copysignf32 => self.float_copysign_intrinsic::<Single>(args, dest)?,
592            sym::copysignf64 => self.float_copysign_intrinsic::<Double>(args, dest)?,
593            sym::copysignf128 => self.float_copysign_intrinsic::<Quad>(args, dest)?,
594
595            sym::fabsf16 => self.float_abs_intrinsic::<Half>(args, dest)?,
596            sym::fabsf32 => self.float_abs_intrinsic::<Single>(args, dest)?,
597            sym::fabsf64 => self.float_abs_intrinsic::<Double>(args, dest)?,
598            sym::fabsf128 => self.float_abs_intrinsic::<Quad>(args, dest)?,
599
600            sym::floorf16 => self.float_round_intrinsic::<Half>(
601                args,
602                dest,
603                rustc_apfloat::Round::TowardNegative,
604            )?,
605            sym::floorf32 => self.float_round_intrinsic::<Single>(
606                args,
607                dest,
608                rustc_apfloat::Round::TowardNegative,
609            )?,
610            sym::floorf64 => self.float_round_intrinsic::<Double>(
611                args,
612                dest,
613                rustc_apfloat::Round::TowardNegative,
614            )?,
615            sym::floorf128 => self.float_round_intrinsic::<Quad>(
616                args,
617                dest,
618                rustc_apfloat::Round::TowardNegative,
619            )?,
620
621            sym::ceilf16 => self.float_round_intrinsic::<Half>(
622                args,
623                dest,
624                rustc_apfloat::Round::TowardPositive,
625            )?,
626            sym::ceilf32 => self.float_round_intrinsic::<Single>(
627                args,
628                dest,
629                rustc_apfloat::Round::TowardPositive,
630            )?,
631            sym::ceilf64 => self.float_round_intrinsic::<Double>(
632                args,
633                dest,
634                rustc_apfloat::Round::TowardPositive,
635            )?,
636            sym::ceilf128 => self.float_round_intrinsic::<Quad>(
637                args,
638                dest,
639                rustc_apfloat::Round::TowardPositive,
640            )?,
641
642            sym::truncf16 => {
643                self.float_round_intrinsic::<Half>(args, dest, rustc_apfloat::Round::TowardZero)?
644            }
645            sym::truncf32 => {
646                self.float_round_intrinsic::<Single>(args, dest, rustc_apfloat::Round::TowardZero)?
647            }
648            sym::truncf64 => {
649                self.float_round_intrinsic::<Double>(args, dest, rustc_apfloat::Round::TowardZero)?
650            }
651            sym::truncf128 => {
652                self.float_round_intrinsic::<Quad>(args, dest, rustc_apfloat::Round::TowardZero)?
653            }
654
655            sym::roundf16 => self.float_round_intrinsic::<Half>(
656                args,
657                dest,
658                rustc_apfloat::Round::NearestTiesToAway,
659            )?,
660            sym::roundf32 => self.float_round_intrinsic::<Single>(
661                args,
662                dest,
663                rustc_apfloat::Round::NearestTiesToAway,
664            )?,
665            sym::roundf64 => self.float_round_intrinsic::<Double>(
666                args,
667                dest,
668                rustc_apfloat::Round::NearestTiesToAway,
669            )?,
670            sym::roundf128 => self.float_round_intrinsic::<Quad>(
671                args,
672                dest,
673                rustc_apfloat::Round::NearestTiesToAway,
674            )?,
675
676            sym::round_ties_even_f16 => self.float_round_intrinsic::<Half>(
677                args,
678                dest,
679                rustc_apfloat::Round::NearestTiesToEven,
680            )?,
681            sym::round_ties_even_f32 => self.float_round_intrinsic::<Single>(
682                args,
683                dest,
684                rustc_apfloat::Round::NearestTiesToEven,
685            )?,
686            sym::round_ties_even_f64 => self.float_round_intrinsic::<Double>(
687                args,
688                dest,
689                rustc_apfloat::Round::NearestTiesToEven,
690            )?,
691            sym::round_ties_even_f128 => self.float_round_intrinsic::<Quad>(
692                args,
693                dest,
694                rustc_apfloat::Round::NearestTiesToEven,
695            )?,
696            sym::fmaf16 => self.float_muladd_intrinsic::<Half>(args, dest, MulAddType::Fused)?,
697            sym::fmaf32 => self.float_muladd_intrinsic::<Single>(args, dest, MulAddType::Fused)?,
698            sym::fmaf64 => self.float_muladd_intrinsic::<Double>(args, dest, MulAddType::Fused)?,
699            sym::fmaf128 => self.float_muladd_intrinsic::<Quad>(args, dest, MulAddType::Fused)?,
700            sym::fmuladdf16 => {
701                self.float_muladd_intrinsic::<Half>(args, dest, MulAddType::Nondeterministic)?
702            }
703            sym::fmuladdf32 => {
704                self.float_muladd_intrinsic::<Single>(args, dest, MulAddType::Nondeterministic)?
705            }
706            sym::fmuladdf64 => {
707                self.float_muladd_intrinsic::<Double>(args, dest, MulAddType::Nondeterministic)?
708            }
709            sym::fmuladdf128 => {
710                self.float_muladd_intrinsic::<Quad>(args, dest, MulAddType::Nondeterministic)?
711            }
712
713            sym::va_copy => {
714                let va_list = self.deref_pointer(&args[0])?;
715                let key_mplace = self.va_list_key_field(&va_list)?;
716                let key = self.read_pointer(&key_mplace)?;
717
718                let varargs = self.get_ptr_va_list(key)?;
719                let copy_key = self.va_list_ptr(varargs.clone());
720
721                let copy_key_mplace = self.va_list_key_field(dest)?;
722                self.write_pointer(copy_key, &copy_key_mplace)?;
723            }
724
725            sym::va_end => {
726                let va_list = self.deref_pointer(&args[0])?;
727                let key_mplace = self.va_list_key_field(&va_list)?;
728                let key = self.read_pointer(&key_mplace)?;
729
730                self.deallocate_va_list(key)?;
731            }
732
733            sym::va_arg => {
734                let va_list = self.deref_pointer(&args[0])?;
735                let key_mplace = self.va_list_key_field(&va_list)?;
736                let key = self.read_pointer(&key_mplace)?;
737
738                // Invalidate the old list and get its content. We'll recreate the
739                // new list (one element shorter) below.
740                let mut varargs = self.deallocate_va_list(key)?;
741
742                let Some(arg_mplace) = varargs.pop_front() else {
743                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::VaArgOutOfBounds);throw_ub!(VaArgOutOfBounds);
744                };
745
746                // NOTE: In C some type conversions are allowed (e.g. casting between signed and
747                // unsigned integers). For now we require c-variadic arguments to be read with the
748                // exact type they were passed as.
749                if arg_mplace.layout.ty != dest.layout.ty {
750                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("va_arg type mismatch: requested `{0}`, but next argument is `{1}`",
                            dest.layout.ty, arg_mplace.layout.ty))
                })));throw_unsup_format!(
751                        "va_arg type mismatch: requested `{}`, but next argument is `{}`",
752                        dest.layout.ty,
753                        arg_mplace.layout.ty
754                    );
755                }
756                // Copy the argument.
757                self.copy_op(&arg_mplace, dest)?;
758
759                // Update the VaList pointer.
760                let new_key = self.va_list_ptr(varargs);
761                self.write_pointer(new_key, &key_mplace)?;
762            }
763
764            // Unsupported intrinsic: skip the return_to_block below.
765            _ => return interp_ok(false),
766        }
767
768        {
    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/interpret/intrinsics.rs:768",
                        "rustc_const_eval::interpret::intrinsics",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/intrinsics.rs"),
                        ::tracing_core::__macro_support::Option::Some(768u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::intrinsics"),
                        ::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:?}",
                                                    self.dump_place(&dest.clone().into())) as &dyn Value))])
            });
    } else { ; }
};trace!("{:?}", self.dump_place(&dest.clone().into()));
769        self.return_to_block(ret)?;
770        interp_ok(true)
771    }
772
773    pub(super) fn eval_nondiverging_intrinsic(
774        &mut self,
775        intrinsic: &NonDivergingIntrinsic<'tcx>,
776    ) -> InterpResult<'tcx> {
777        match intrinsic {
778            NonDivergingIntrinsic::Assume(op) => {
779                let op = self.eval_operand(op, None)?;
780                let cond = self.read_scalar(&op)?.to_bool()?;
781                if !cond {
782                    do yeet {
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                    msg: ||
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`assume` called with `false`")),
                    add_args: Box::new(move |mut set_arg| {}),
                }))
    };throw_ub_custom!(msg!("`assume` called with `false`"));
783                }
784                interp_ok(())
785            }
786            NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
787                count,
788                src,
789                dst,
790            }) => {
791                let src = self.eval_operand(src, None)?;
792                let dst = self.eval_operand(dst, None)?;
793                let count = self.eval_operand(count, None)?;
794                self.copy_intrinsic(&src, &dst, &count, /* nonoverlapping */ true)
795            }
796        }
797    }
798
799    pub fn numeric_intrinsic(
800        &self,
801        name: Symbol,
802        val: Scalar<M::Provenance>,
803        layout: TyAndLayout<'tcx>,
804        ret_layout: TyAndLayout<'tcx>,
805    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
806        if !layout.ty.is_integral() {
    {
        ::core::panicking::panic_fmt(format_args!("invalid type for numeric intrinsic: {0}",
                layout.ty));
    }
};assert!(layout.ty.is_integral(), "invalid type for numeric intrinsic: {}", layout.ty);
807        let bits = val.to_bits(layout.size)?; // these operations all ignore the sign
808        let extra = 128 - u128::from(layout.size.bits());
809        let bits_out = match name {
810            sym::ctpop => u128::from(bits.count_ones()),
811            sym::ctlz_nonzero | sym::cttz_nonzero if bits == 0 => {
812                do yeet {
        let (name,) = (name,);
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                    msg: ||
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$name}` called on 0")),
                    add_args: Box::new(move |mut set_arg|
                            {
                                set_arg("name".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(name, &mut None));
                            }),
                }))
    };throw_ub_custom!(msg!("`{$name}` called on 0"), name = name,);
813            }
814            sym::ctlz | sym::ctlz_nonzero => u128::from(bits.leading_zeros()) - extra,
815            sym::cttz | sym::cttz_nonzero => u128::from((bits << extra).trailing_zeros()) - extra,
816            sym::bswap => {
817                match (&layout, &ret_layout) {
    (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!(layout, ret_layout);
818                (bits << extra).swap_bytes()
819            }
820            sym::bitreverse => {
821                match (&layout, &ret_layout) {
    (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!(layout, ret_layout);
822                (bits << extra).reverse_bits()
823            }
824            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("not a numeric intrinsic: {0}",
        name))bug!("not a numeric intrinsic: {}", name),
825        };
826        interp_ok(Scalar::from_uint(bits_out, ret_layout.size))
827    }
828
829    pub fn exact_div(
830        &mut self,
831        a: &ImmTy<'tcx, M::Provenance>,
832        b: &ImmTy<'tcx, M::Provenance>,
833        dest: &PlaceTy<'tcx, M::Provenance>,
834    ) -> InterpResult<'tcx> {
835        match (&a.layout.ty, &b.layout.ty) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(a.layout.ty, b.layout.ty);
836        match a.layout.ty.kind() {
    ty::Int(..) | ty::Uint(..) => {}
    ref left_val => {
        ::core::panicking::assert_matches_failed(left_val,
            "ty::Int(..) | ty::Uint(..)", ::core::option::Option::None);
    }
};assert_matches!(a.layout.ty.kind(), ty::Int(..) | ty::Uint(..));
837
838        // Performs an exact division, resulting in undefined behavior where
839        // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
840        // First, check x % y != 0 (or if that computation overflows).
841        let rem = self.binary_op(BinOp::Rem, a, b)?;
842        // sign does not matter for 0 test, so `to_bits` is fine
843        if rem.to_scalar().to_bits(a.layout.size)? != 0 {
844            do yeet {
        let (a, b) =
            (::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("{0}", a))
                    }),
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("{0}", b))
                    }));
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                    msg: ||
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("exact_div: {$a} cannot be divided by {$b} without remainder")),
                    add_args: Box::new(move |mut set_arg|
                            {
                                set_arg("a".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(a, &mut None));
                                set_arg("b".into(),
                                    rustc_errors::IntoDiagArg::into_diag_arg(b, &mut None));
                            }),
                }))
    }throw_ub_custom!(
845                msg!("exact_div: {$a} cannot be divided by {$b} without remainder"),
846                a = format!("{a}"),
847                b = format!("{b}")
848            )
849        }
850        // `Rem` says this is all right, so we can let `Div` do its job.
851        let res = self.binary_op(BinOp::Div, a, b)?;
852        self.write_immediate(*res, dest)
853    }
854
855    pub fn saturating_arith(
856        &self,
857        mir_op: BinOp,
858        l: &ImmTy<'tcx, M::Provenance>,
859        r: &ImmTy<'tcx, M::Provenance>,
860    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
861        match (&l.layout.ty, &r.layout.ty) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(l.layout.ty, r.layout.ty);
862        match l.layout.ty.kind() {
    ty::Int(..) | ty::Uint(..) => {}
    ref left_val => {
        ::core::panicking::assert_matches_failed(left_val,
            "ty::Int(..) | ty::Uint(..)", ::core::option::Option::None);
    }
};assert_matches!(l.layout.ty.kind(), ty::Int(..) | ty::Uint(..));
863        match mir_op {
    BinOp::Add | BinOp::Sub => {}
    ref left_val => {
        ::core::panicking::assert_matches_failed(left_val,
            "BinOp::Add | BinOp::Sub", ::core::option::Option::None);
    }
};assert_matches!(mir_op, BinOp::Add | BinOp::Sub);
864
865        let (val, overflowed) =
866            self.binary_op(mir_op.wrapping_to_overflowing().unwrap(), l, r)?.to_scalar_pair();
867        interp_ok(if overflowed.to_bool()? {
868            let size = l.layout.size;
869            if l.layout.backend_repr.is_signed() {
870                // For signed ints the saturated value depends on the sign of the first
871                // term since the sign of the second term can be inferred from this and
872                // the fact that the operation has overflowed (if either is 0 no
873                // overflow can occur)
874                let first_term: i128 = l.to_scalar().to_int(l.layout.size)?;
875                if first_term >= 0 {
876                    // Negative overflow not possible since the positive first term
877                    // can only increase an (in range) negative term for addition
878                    // or corresponding negated positive term for subtraction.
879                    Scalar::from_int(size.signed_int_max(), size)
880                } else {
881                    // Positive overflow not possible for similar reason.
882                    Scalar::from_int(size.signed_int_min(), size)
883                }
884            } else {
885                // unsigned
886                if mir_op == BinOp::Add {
887                    // max unsigned
888                    Scalar::from_uint(size.unsigned_int_max(), size)
889                } else {
890                    // underflow to 0
891                    Scalar::from_uint(0u128, size)
892                }
893            }
894        } else {
895            val
896        })
897    }
898
899    /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
900    /// allocation.
901    pub fn ptr_offset_inbounds(
902        &self,
903        ptr: Pointer<Option<M::Provenance>>,
904        offset_bytes: i64,
905    ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
906        // The offset must be in bounds starting from `ptr`.
907        self.check_ptr_access_signed(
908            ptr,
909            offset_bytes,
910            CheckInAllocMsg::InboundsPointerArithmetic,
911        )?;
912        // This also implies that there is no overflow, so we are done.
913        interp_ok(ptr.wrapping_signed_offset(offset_bytes, self))
914    }
915
916    /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.
917    pub(crate) fn copy_intrinsic(
918        &mut self,
919        src: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
920        dst: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
921        count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
922        nonoverlapping: bool,
923    ) -> InterpResult<'tcx> {
924        let count = self.read_target_usize(count)?;
925        let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap())?;
926        let (size, align) = (layout.size, layout.align.abi);
927
928        let size = self.compute_size_in_bytes(size, count).ok_or_else(|| {
929            {
    let (name,) =
        (if nonoverlapping { "copy_nonoverlapping" } else { "copy" },);
    ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                msg: ||
                    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("overflow computing total size of `{$name}`")),
                add_args: Box::new(move |mut set_arg|
                        {
                            set_arg("name".into(),
                                rustc_errors::IntoDiagArg::into_diag_arg(name, &mut None));
                        }),
            }))
}err_ub_custom!(
930                msg!("overflow computing total size of `{$name}`"),
931                name = if nonoverlapping { "copy_nonoverlapping" } else { "copy" }
932            )
933        })?;
934
935        let src = self.read_pointer(src)?;
936        let dst = self.read_pointer(dst)?;
937
938        self.check_ptr_align(src, align)?;
939        self.check_ptr_align(dst, align)?;
940
941        self.mem_copy(src, dst, size, nonoverlapping)
942    }
943
944    /// Does a *typed* swap of `*left` and `*right`.
945    fn typed_swap_nonoverlapping_intrinsic(
946        &mut self,
947        left: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
948        right: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
949    ) -> InterpResult<'tcx> {
950        let left = self.deref_pointer(left)?;
951        let right = self.deref_pointer(right)?;
952        match (&left.layout, &right.layout) {
    (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!(left.layout, right.layout);
953        if !left.layout.is_sized() {
    ::core::panicking::panic("assertion failed: left.layout.is_sized()")
};assert!(left.layout.is_sized());
954        let kind = MemoryKind::Stack;
955        let temp = self.allocate(left.layout, kind)?;
956        self.copy_op(&left, &temp)?; // checks alignment of `left`
957
958        // We want to always enforce non-overlapping, even if this is a scalar type.
959        // Therefore we directly use the underlying `mem_copy` here.
960        self.mem_copy(right.ptr(), left.ptr(), left.layout.size, /*nonoverlapping*/ true)?;
961        // This means we also need to do the validation of the value that used to be in `right`
962        // ourselves. This value is now in `left.` The one that started out in `left` already got
963        // validated by the copy above.
964        if M::enforce_validity(self, left.layout) {
965            self.validate_operand(
966                &left.clone().into(),
967                M::enforce_validity_recursively(self, left.layout),
968                /*reset_provenance_and_padding*/ true,
969            )?;
970        }
971
972        self.copy_op(&temp, &right)?; // checks alignment of `right`
973
974        self.deallocate_ptr(temp.ptr(), None, kind)?;
975        interp_ok(())
976    }
977
978    pub fn write_bytes_intrinsic(
979        &mut self,
980        dst: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
981        byte: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
982        count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
983        name: &'static str,
984    ) -> InterpResult<'tcx> {
985        let layout = self.layout_of(dst.layout.ty.builtin_deref(true).unwrap())?;
986
987        let dst = self.read_pointer(dst)?;
988        let byte = self.read_scalar(byte)?.to_u8()?;
989        let count = self.read_target_usize(count)?;
990
991        // `checked_mul` enforces a too small bound (the correct one would probably be target_isize_max),
992        // but no actual allocation can be big enough for the difference to be noticeable.
993        let len = self.compute_size_in_bytes(layout.size, count).ok_or_else(|| {
994            {
    let (name,) = (name,);
    ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                msg: ||
                    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("overflow computing total size of `{$name}`")),
                add_args: Box::new(move |mut set_arg|
                        {
                            set_arg("name".into(),
                                rustc_errors::IntoDiagArg::into_diag_arg(name, &mut None));
                        }),
            }))
}err_ub_custom!(msg!("overflow computing total size of `{$name}`"), name = name)
995        })?;
996
997        let bytes = std::iter::repeat_n(byte, len.bytes_usize());
998        self.write_bytes_ptr(dst, bytes)
999    }
1000
1001    pub(crate) fn compare_bytes_intrinsic(
1002        &mut self,
1003        left: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1004        right: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1005        byte_count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1006    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
1007        let left = self.read_pointer(left)?;
1008        let right = self.read_pointer(right)?;
1009        let n = Size::from_bytes(self.read_target_usize(byte_count)?);
1010
1011        let left_bytes = self.read_bytes_ptr_strip_provenance(left, n)?;
1012        let right_bytes = self.read_bytes_ptr_strip_provenance(right, n)?;
1013
1014        // `Ordering`'s discriminants are -1/0/+1, so casting does the right thing.
1015        let result = Ord::cmp(left_bytes, right_bytes) as i32;
1016        interp_ok(Scalar::from_i32(result))
1017    }
1018
1019    pub(crate) fn raw_eq_intrinsic(
1020        &mut self,
1021        lhs: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1022        rhs: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1023    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
1024        let layout = self.layout_of(lhs.layout.ty.builtin_deref(true).unwrap())?;
1025        if !layout.is_sized() {
    ::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
1026
1027        let get_bytes = |this: &InterpCx<'tcx, M>,
1028                         op: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>|
1029         -> InterpResult<'tcx, &[u8]> {
1030            let ptr = this.read_pointer(op)?;
1031            this.check_ptr_align(ptr, layout.align.abi)?;
1032            let Some(alloc_ref) = self.get_ptr_alloc(ptr, layout.size)? else {
1033                // zero-sized access
1034                return interp_ok(&[]);
1035            };
1036            alloc_ref.get_bytes_strip_provenance()
1037        };
1038
1039        let lhs_bytes = get_bytes(self, lhs)?;
1040        let rhs_bytes = get_bytes(self, rhs)?;
1041        interp_ok(Scalar::from_bool(lhs_bytes == rhs_bytes))
1042    }
1043
1044    fn float_minmax<F>(
1045        &self,
1046        a: Scalar<M::Provenance>,
1047        b: Scalar<M::Provenance>,
1048        op: MinMax,
1049    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1050    where
1051        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1052    {
1053        let a: F = a.to_float()?;
1054        let b: F = b.to_float()?;
1055        let res = if #[allow(non_exhaustive_omitted_patterns)] match op {
    MinMax::MinimumNumber | MinMax::MaximumNumber => true,
    _ => false,
}matches!(op, MinMax::MinimumNumber | MinMax::MaximumNumber) && a == b {
1056            // They are definitely not NaN (those are never equal), but they could be `+0` and `-0`.
1057            // Let the machine decide which one to return.
1058            M::equal_float_min_max(self, a, b)
1059        } else {
1060            let result = match op {
1061                MinMax::Minimum => a.minimum(b),
1062                MinMax::MinimumNumber => a.min(b),
1063                MinMax::Maximum => a.maximum(b),
1064                MinMax::MaximumNumber => a.max(b),
1065            };
1066            self.adjust_nan(result, &[a, b])
1067        };
1068
1069        interp_ok(res.into())
1070    }
1071
1072    fn float_minmax_intrinsic<F>(
1073        &mut self,
1074        args: &[OpTy<'tcx, M::Provenance>],
1075        op: MinMax,
1076        dest: &PlaceTy<'tcx, M::Provenance>,
1077    ) -> InterpResult<'tcx, ()>
1078    where
1079        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1080    {
1081        let res =
1082            self.float_minmax::<F>(self.read_scalar(&args[0])?, self.read_scalar(&args[1])?, op)?;
1083        self.write_scalar(res, dest)?;
1084        interp_ok(())
1085    }
1086
1087    fn float_copysign_intrinsic<F>(
1088        &mut self,
1089        args: &[OpTy<'tcx, M::Provenance>],
1090        dest: &PlaceTy<'tcx, M::Provenance>,
1091    ) -> InterpResult<'tcx, ()>
1092    where
1093        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1094    {
1095        let a: F = self.read_scalar(&args[0])?.to_float()?;
1096        let b: F = self.read_scalar(&args[1])?.to_float()?;
1097        // bitwise, no NaN adjustments
1098        self.write_scalar(a.copy_sign(b), dest)?;
1099        interp_ok(())
1100    }
1101
1102    fn float_abs_intrinsic<F>(
1103        &mut self,
1104        args: &[OpTy<'tcx, M::Provenance>],
1105        dest: &PlaceTy<'tcx, M::Provenance>,
1106    ) -> InterpResult<'tcx, ()>
1107    where
1108        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1109    {
1110        let x: F = self.read_scalar(&args[0])?.to_float()?;
1111        // bitwise, no NaN adjustments
1112        self.write_scalar(x.abs(), dest)?;
1113        interp_ok(())
1114    }
1115
1116    fn float_round<F>(
1117        &mut self,
1118        x: Scalar<M::Provenance>,
1119        mode: rustc_apfloat::Round,
1120    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1121    where
1122        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1123    {
1124        let x: F = x.to_float()?;
1125        let res = x.round_to_integral(mode).value;
1126        let res = self.adjust_nan(res, &[x]);
1127        interp_ok(res.into())
1128    }
1129
1130    fn float_round_intrinsic<F>(
1131        &mut self,
1132        args: &[OpTy<'tcx, M::Provenance>],
1133        dest: &PlaceTy<'tcx, M::Provenance>,
1134        mode: rustc_apfloat::Round,
1135    ) -> InterpResult<'tcx, ()>
1136    where
1137        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1138    {
1139        let res = self.float_round::<F>(self.read_scalar(&args[0])?, mode)?;
1140        self.write_scalar(res, dest)?;
1141        interp_ok(())
1142    }
1143
1144    fn float_muladd<F>(
1145        &self,
1146        a: Scalar<M::Provenance>,
1147        b: Scalar<M::Provenance>,
1148        c: Scalar<M::Provenance>,
1149        typ: MulAddType,
1150    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1151    where
1152        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1153    {
1154        let a: F = a.to_float()?;
1155        let b: F = b.to_float()?;
1156        let c: F = c.to_float()?;
1157
1158        let fuse = typ == MulAddType::Fused || M::float_fuse_mul_add(self);
1159
1160        let res = if fuse { a.mul_add(b, c).value } else { ((a * b).value + c).value };
1161        let res = self.adjust_nan(res, &[a, b, c]);
1162        interp_ok(res.into())
1163    }
1164
1165    fn float_muladd_intrinsic<F>(
1166        &mut self,
1167        args: &[OpTy<'tcx, M::Provenance>],
1168        dest: &PlaceTy<'tcx, M::Provenance>,
1169        typ: MulAddType,
1170    ) -> InterpResult<'tcx, ()>
1171    where
1172        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1173    {
1174        let a = self.read_scalar(&args[0])?;
1175        let b = self.read_scalar(&args[1])?;
1176        let c = self.read_scalar(&args[2])?;
1177
1178        let res = self.float_muladd::<F>(a, b, c, typ)?;
1179        self.write_scalar(res, dest)?;
1180        interp_ok(())
1181    }
1182
1183    /// Converts `src` from floating point to integer type `dest_ty`
1184    /// after rounding with mode `round`.
1185    /// Returns `None` if `f` is NaN or out of range.
1186    pub fn float_to_int_checked(
1187        &self,
1188        src: &ImmTy<'tcx, M::Provenance>,
1189        cast_to: TyAndLayout<'tcx>,
1190        round: rustc_apfloat::Round,
1191    ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::Provenance>>> {
1192        fn float_to_int_inner<'tcx, F: rustc_apfloat::Float, M: Machine<'tcx>>(
1193            ecx: &InterpCx<'tcx, M>,
1194            src: F,
1195            cast_to: TyAndLayout<'tcx>,
1196            round: rustc_apfloat::Round,
1197        ) -> (Scalar<M::Provenance>, rustc_apfloat::Status) {
1198            let int_size = cast_to.layout.size;
1199            match cast_to.ty.kind() {
1200                // Unsigned
1201                ty::Uint(_) => {
1202                    let res = src.to_u128_r(int_size.bits_usize(), round, &mut false);
1203                    (Scalar::from_uint(res.value, int_size), res.status)
1204                }
1205                // Signed
1206                ty::Int(_) => {
1207                    let res = src.to_i128_r(int_size.bits_usize(), round, &mut false);
1208                    (Scalar::from_int(res.value, int_size), res.status)
1209                }
1210                // Nothing else
1211                _ => ::rustc_middle::util::bug::span_bug_fmt(ecx.cur_span(),
    format_args!("attempted float-to-int conversion with non-int output type {0}",
        cast_to.ty))span_bug!(
1212                    ecx.cur_span(),
1213                    "attempted float-to-int conversion with non-int output type {}",
1214                    cast_to.ty,
1215                ),
1216            }
1217        }
1218
1219        let ty::Float(fty) = src.layout.ty.kind() else {
1220            ::rustc_middle::util::bug::bug_fmt(format_args!("float_to_int_checked: non-float input type {0}",
        src.layout.ty))bug!("float_to_int_checked: non-float input type {}", src.layout.ty)
1221        };
1222
1223        let (val, status) = match fty {
1224            FloatTy::F16 => float_to_int_inner(self, src.to_scalar().to_f16()?, cast_to, round),
1225            FloatTy::F32 => float_to_int_inner(self, src.to_scalar().to_f32()?, cast_to, round),
1226            FloatTy::F64 => float_to_int_inner(self, src.to_scalar().to_f64()?, cast_to, round),
1227            FloatTy::F128 => float_to_int_inner(self, src.to_scalar().to_f128()?, cast_to, round),
1228        };
1229
1230        if status.intersects(
1231            rustc_apfloat::Status::INVALID_OP
1232                | rustc_apfloat::Status::OVERFLOW
1233                | rustc_apfloat::Status::UNDERFLOW,
1234        ) {
1235            // Floating point value is NaN (flagged with INVALID_OP) or outside the range
1236            // of values of the integer type (flagged with OVERFLOW or UNDERFLOW).
1237            interp_ok(None)
1238        } else {
1239            // Floating point value can be represented by the integer type after rounding.
1240            // The INEXACT flag is ignored on purpose to allow rounding.
1241            interp_ok(Some(ImmTy::from_scalar(val, cast_to)))
1242        }
1243    }
1244
1245    /// Get the MPlace of the key from the place storing the VaList.
1246    pub(super) fn va_list_key_field<P: Projectable<'tcx, M::Provenance>>(
1247        &self,
1248        va_list: &P,
1249    ) -> InterpResult<'tcx, P> {
1250        // The struct wrapped by VaList.
1251        let va_list_inner = self.project_field(va_list, FieldIdx::ZERO)?;
1252
1253        // Find the first pointer field in this struct. The exact index is target-specific.
1254        let ty::Adt(adt, substs) = va_list_inner.layout().ty.kind() else {
1255            ::rustc_middle::util::bug::bug_fmt(format_args!("invalid VaListImpl layout"));bug!("invalid VaListImpl layout");
1256        };
1257
1258        for (i, field) in adt.non_enum_variant().fields.iter().enumerate() {
1259            if field.ty(*self.tcx, substs).is_raw_ptr() {
1260                return self.project_field(&va_list_inner, FieldIdx::from_usize(i));
1261            }
1262        }
1263
1264        ::rustc_middle::util::bug::bug_fmt(format_args!("no VaListImpl field is a pointer"));bug!("no VaListImpl field is a pointer");
1265    }
1266}