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