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