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