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(tcx, 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(tcx, 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(tcx, 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::vtable_size => {
534                let ptr = self.read_pointer(&args[0])?;
535                // `None` because we don't know which trait to expect here; any vtable is okay.
536                let (size, _align) = self.get_vtable_size_and_align(ptr, None)?;
537                self.write_scalar(Scalar::from_target_usize(size.bytes(), self), dest)?;
538            }
539            sym::vtable_align => {
540                let ptr = self.read_pointer(&args[0])?;
541                // `None` because we don't know which trait to expect here; any vtable is okay.
542                let (_size, align) = self.get_vtable_size_and_align(ptr, None)?;
543                self.write_scalar(Scalar::from_target_usize(align.bytes(), self), dest)?;
544            }
545
546            sym::minimum_number_nsz_f16 => {
547                self.float_minmax_intrinsic::<Half>(args, MinMax::MinimumNumberNsz, dest)?
548            }
549            sym::minimum_number_nsz_f32 => {
550                self.float_minmax_intrinsic::<Single>(args, MinMax::MinimumNumberNsz, dest)?
551            }
552            sym::minimum_number_nsz_f64 => {
553                self.float_minmax_intrinsic::<Double>(args, MinMax::MinimumNumberNsz, dest)?
554            }
555            sym::minimum_number_nsz_f128 => {
556                self.float_minmax_intrinsic::<Quad>(args, MinMax::MinimumNumberNsz, dest)?
557            }
558
559            sym::minimumf16 => self.float_minmax_intrinsic::<Half>(args, MinMax::Minimum, dest)?,
560            sym::minimumf32 => {
561                self.float_minmax_intrinsic::<Single>(args, MinMax::Minimum, dest)?
562            }
563            sym::minimumf64 => {
564                self.float_minmax_intrinsic::<Double>(args, MinMax::Minimum, dest)?
565            }
566            sym::minimumf128 => self.float_minmax_intrinsic::<Quad>(args, MinMax::Minimum, dest)?,
567
568            sym::maximum_number_nsz_f16 => {
569                self.float_minmax_intrinsic::<Half>(args, MinMax::MaximumNumberNsz, dest)?
570            }
571            sym::maximum_number_nsz_f32 => {
572                self.float_minmax_intrinsic::<Single>(args, MinMax::MaximumNumberNsz, dest)?
573            }
574            sym::maximum_number_nsz_f64 => {
575                self.float_minmax_intrinsic::<Double>(args, MinMax::MaximumNumberNsz, dest)?
576            }
577            sym::maximum_number_nsz_f128 => {
578                self.float_minmax_intrinsic::<Quad>(args, MinMax::MaximumNumberNsz, dest)?
579            }
580
581            sym::maximumf16 => self.float_minmax_intrinsic::<Half>(args, MinMax::Maximum, dest)?,
582            sym::maximumf32 => {
583                self.float_minmax_intrinsic::<Single>(args, MinMax::Maximum, dest)?
584            }
585            sym::maximumf64 => {
586                self.float_minmax_intrinsic::<Double>(args, MinMax::Maximum, dest)?
587            }
588            sym::maximumf128 => self.float_minmax_intrinsic::<Quad>(args, MinMax::Maximum, dest)?,
589
590            sym::copysignf16 => self.float_copysign_intrinsic::<Half>(args, dest)?,
591            sym::copysignf32 => self.float_copysign_intrinsic::<Single>(args, dest)?,
592            sym::copysignf64 => self.float_copysign_intrinsic::<Double>(args, dest)?,
593            sym::copysignf128 => self.float_copysign_intrinsic::<Quad>(args, dest)?,
594
595            sym::fabs => {
596                let arg = self.read_immediate(&args[0])?;
597                let ty::Float(float_ty) = arg.layout.ty.kind() else {
598                    ::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
    format_args!("non-float type for float intrinsic: {0}", arg.layout.ty));span_bug!(
599                        self.cur_span(),
600                        "non-float type for float intrinsic: {}",
601                        arg.layout.ty,
602                    );
603                };
604                let out_val = match float_ty {
605                    FloatTy::F16 => self.unop_float_intrinsic::<Half>(intrinsic_name, arg)?,
606                    FloatTy::F32 => self.unop_float_intrinsic::<Single>(intrinsic_name, arg)?,
607                    FloatTy::F64 => self.unop_float_intrinsic::<Double>(intrinsic_name, arg)?,
608                    FloatTy::F128 => self.unop_float_intrinsic::<Quad>(intrinsic_name, arg)?,
609                };
610                self.write_scalar(out_val, dest)?;
611            }
612
613            sym::floorf16 => self.float_round_intrinsic::<Half>(
614                args,
615                dest,
616                rustc_apfloat::Round::TowardNegative,
617            )?,
618            sym::floorf32 => self.float_round_intrinsic::<Single>(
619                args,
620                dest,
621                rustc_apfloat::Round::TowardNegative,
622            )?,
623            sym::floorf64 => self.float_round_intrinsic::<Double>(
624                args,
625                dest,
626                rustc_apfloat::Round::TowardNegative,
627            )?,
628            sym::floorf128 => self.float_round_intrinsic::<Quad>(
629                args,
630                dest,
631                rustc_apfloat::Round::TowardNegative,
632            )?,
633
634            sym::ceilf16 => self.float_round_intrinsic::<Half>(
635                args,
636                dest,
637                rustc_apfloat::Round::TowardPositive,
638            )?,
639            sym::ceilf32 => self.float_round_intrinsic::<Single>(
640                args,
641                dest,
642                rustc_apfloat::Round::TowardPositive,
643            )?,
644            sym::ceilf64 => self.float_round_intrinsic::<Double>(
645                args,
646                dest,
647                rustc_apfloat::Round::TowardPositive,
648            )?,
649            sym::ceilf128 => self.float_round_intrinsic::<Quad>(
650                args,
651                dest,
652                rustc_apfloat::Round::TowardPositive,
653            )?,
654
655            sym::truncf16 => {
656                self.float_round_intrinsic::<Half>(args, dest, rustc_apfloat::Round::TowardZero)?
657            }
658            sym::truncf32 => {
659                self.float_round_intrinsic::<Single>(args, dest, rustc_apfloat::Round::TowardZero)?
660            }
661            sym::truncf64 => {
662                self.float_round_intrinsic::<Double>(args, dest, rustc_apfloat::Round::TowardZero)?
663            }
664            sym::truncf128 => {
665                self.float_round_intrinsic::<Quad>(args, dest, rustc_apfloat::Round::TowardZero)?
666            }
667
668            sym::roundf16 => self.float_round_intrinsic::<Half>(
669                args,
670                dest,
671                rustc_apfloat::Round::NearestTiesToAway,
672            )?,
673            sym::roundf32 => self.float_round_intrinsic::<Single>(
674                args,
675                dest,
676                rustc_apfloat::Round::NearestTiesToAway,
677            )?,
678            sym::roundf64 => self.float_round_intrinsic::<Double>(
679                args,
680                dest,
681                rustc_apfloat::Round::NearestTiesToAway,
682            )?,
683            sym::roundf128 => self.float_round_intrinsic::<Quad>(
684                args,
685                dest,
686                rustc_apfloat::Round::NearestTiesToAway,
687            )?,
688
689            sym::round_ties_even_f16 => self.float_round_intrinsic::<Half>(
690                args,
691                dest,
692                rustc_apfloat::Round::NearestTiesToEven,
693            )?,
694            sym::round_ties_even_f32 => self.float_round_intrinsic::<Single>(
695                args,
696                dest,
697                rustc_apfloat::Round::NearestTiesToEven,
698            )?,
699            sym::round_ties_even_f64 => self.float_round_intrinsic::<Double>(
700                args,
701                dest,
702                rustc_apfloat::Round::NearestTiesToEven,
703            )?,
704            sym::round_ties_even_f128 => self.float_round_intrinsic::<Quad>(
705                args,
706                dest,
707                rustc_apfloat::Round::NearestTiesToEven,
708            )?,
709            sym::fmaf16 => self.float_muladd_intrinsic::<Half>(args, dest, MulAddType::Fused)?,
710            sym::fmaf32 => self.float_muladd_intrinsic::<Single>(args, dest, MulAddType::Fused)?,
711            sym::fmaf64 => self.float_muladd_intrinsic::<Double>(args, dest, MulAddType::Fused)?,
712            sym::fmaf128 => self.float_muladd_intrinsic::<Quad>(args, dest, MulAddType::Fused)?,
713            sym::fmuladdf16 => {
714                self.float_muladd_intrinsic::<Half>(args, dest, MulAddType::Nondeterministic)?
715            }
716            sym::fmuladdf32 => {
717                self.float_muladd_intrinsic::<Single>(args, dest, MulAddType::Nondeterministic)?
718            }
719            sym::fmuladdf64 => {
720                self.float_muladd_intrinsic::<Double>(args, dest, MulAddType::Nondeterministic)?
721            }
722            sym::fmuladdf128 => {
723                self.float_muladd_intrinsic::<Quad>(args, dest, MulAddType::Nondeterministic)?
724            }
725
726            sym::va_copy => {
727                let va_list = self.deref_pointer(&args[0])?;
728
729                let key_mplace = self.va_list_key_field(&va_list)?;
730                let key = self.read_pointer(&key_mplace)?;
731
732                let varargs = self.get_ptr_va_list(key)?;
733                let copy_key = self.va_list_ptr(varargs.clone());
734
735                // Zero the destination VaList, so it is fully initialized.
736                let dest = self.force_allocation(dest)?;
737                let zeros = std::iter::repeat_n(0u8, dest.layout.size.bytes_usize());
738                self.write_bytes_ptr(dest.ptr(), zeros)?;
739
740                let copy_key_mplace = self.va_list_key_field(&dest)?;
741                self.write_pointer(copy_key, &copy_key_mplace)?;
742            }
743
744            sym::va_end => {
745                let va_list = self.deref_pointer(&args[0])?;
746                let key_mplace = self.va_list_key_field(&va_list)?;
747                let key = self.read_pointer(&key_mplace)?;
748
749                self.deallocate_va_list(key)?;
750            }
751
752            sym::va_arg => {
753                let va_list = self.deref_pointer(&args[0])?;
754                let key_mplace = self.va_list_key_field(&va_list)?;
755                let key = self.read_pointer(&key_mplace)?;
756
757                // Invalidate the old list and get its content. We'll recreate the
758                // new list (one element shorter) below.
759                let mut varargs = self.deallocate_va_list(key)?;
760
761                let Some(arg_mplace) = varargs.pop_front() else {
762                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::VaArgOutOfBounds);throw_ub!(VaArgOutOfBounds);
763                };
764
765                // Error when the caller's argument is not c-variadic compatible with the type
766                // requested by the callee.
767                self.validate_c_variadic_argument(&arg_mplace, dest.layout)?;
768
769                // Copy the argument, allowing a transmute and relying on the compatibility check
770                // rejecting conversions between types of different size.
771                self.copy_op_allow_transmute(&arg_mplace, dest)?;
772
773                // Update the VaList pointer.
774                let new_key = self.va_list_ptr(varargs);
775                self.write_pointer(new_key, &key_mplace)?;
776            }
777
778            // Unsupported intrinsic: skip the return_to_block below.
779            _ => return interp_ok(false),
780        }
781
782        {
    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:782",
                        "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(782u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::intrinsics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
                                                    self.dump_place(&dest)) as &dyn Value))])
            });
    } else { ; }
};trace!("{:?}", self.dump_place(&dest));
783        self.return_to_block(ret)?;
784        interp_ok(true)
785    }
786
787    /// Validate whether the value and type passed by the caller are compatible with the type
788    /// requested by the callee. Based on section 7.16.1.1 of the C23 specification.
789    ///
790    /// The callee requesting a value of a type is valid when that type is compatible with the type
791    /// provided by the caller (see `validate_c_variadic_compatible_ty`) and, if both types are
792    /// integers of the same size but different signedness, the passed value must be representable
793    /// in both types.
794    fn validate_c_variadic_argument(
795        &mut self,
796        arg_mplace: &MPlaceTy<'tcx, M::Provenance>,
797        callee_type: TyAndLayout<'tcx>,
798    ) -> InterpResult<'tcx> {
799        let callee_ty = callee_type.ty;
800        let caller_ty = arg_mplace.layout.ty;
801
802        // Identical types are clearly compatible.
803        if caller_ty == callee_ty {
804            return interp_ok(());
805        }
806
807        // Types of different sizes can never be compatible.
808        if arg_mplace.layout.size != callee_type.size {
809            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!(
810                "va_arg type mismatch: requested `{}` is incompatible with next argument of type `{}`",
811                callee_ty,
812                caller_ty,
813            )
814        }
815
816        match self.validate_c_variadic_compatible_ty(arg_mplace.layout.ty, callee_type.ty)? {
817            VarArgCompatible::Compatible => interp_ok(()),
818            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!(
819                "va_arg type mismatch: requested `{}` is incompatible with next argument of type `{}`",
820                callee_ty,
821                caller_ty,
822            ),
823            VarArgCompatible::CastIntTo { source_is_signed } => {
824                // Check that the value can be represented in the target type.
825                let size = arg_mplace.layout.size;
826                let scalar = self.read_scalar(arg_mplace)?;
827                if scalar.to_int(size)? < 0 {
828                    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!(
829                        "va_arg value mismatch: value `{value}_{caller_ty}` cannot be represented by type `{callee_ty}`",
830                        value = if source_is_signed {
831                            scalar.to_int(size)?.to_string()
832                        } else {
833                            scalar.to_uint(size)?.to_string()
834                        }
835                    )
836                }
837
838                interp_ok(())
839            }
840        }
841    }
842
843    /// Check whether the caller and callee type are compatible for c-variadic calls. Further
844    /// validation of the argument value may be needed to detect all UB.
845    ///
846    /// Types `T` and `U` are compatible when:
847    ///
848    /// - `T` and `U` are the same type.
849    /// - `T` and `U` are integer types of the same size.
850    /// - `T` and `U` are both pointers, and their target types are compatible.
851    /// - `T` is a pointer to [`std::ffi::c_void`] and `U` is a pointer to [`i8`] or [`u8`],
852    /// or vice versa.
853    fn validate_c_variadic_compatible_ty(
854        &mut self,
855        caller_type: Ty<'tcx>,
856        callee_type: Ty<'tcx>,
857    ) -> InterpResult<'tcx, VarArgCompatible> {
858        if caller_type == callee_type {
859            return interp_ok(VarArgCompatible::Compatible);
860        }
861
862        if self.layout_of(caller_type)?.size != self.layout_of(callee_type)?.size {
863            return interp_ok(VarArgCompatible::Incompatible);
864        }
865
866        // Any character type (`char`, `unsigned char` and `signed char`) is compatible with
867        // `void*`, so the signedness of `c_char` is irrelevant here.
868        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));
869
870        match (caller_type.kind(), callee_type.kind()) {
871            (ty::RawPtr(caller_target_ty, _), ty::RawPtr(callee_target_ty, _)) => {
872                // In C, types can be qualified by a combination of `const`, `volatile` and
873                // `restrict`. These properties are irrelevant for the ABI, and don't have an
874                // equivalent in rust.
875
876                // Accept the cast if one type is pointer to void, and the other is a pointer to
877                // a character type (`char`, `unsigned char` and `signed char`).
878                if caller_target_ty.is_c_void(self.tcx.tcx) && is_c_char(*callee_target_ty) {
879                    return interp_ok(VarArgCompatible::Compatible);
880                }
881                if callee_target_ty.is_c_void(self.tcx.tcx) && is_c_char(*caller_target_ty) {
882                    return interp_ok(VarArgCompatible::Compatible);
883                }
884
885                // Accept the cast if both types are pointers to compatible types.
886                match self
887                    .validate_c_variadic_compatible_ty(*caller_target_ty, *callee_target_ty)?
888                {
889                    VarArgCompatible::Incompatible => interp_ok(VarArgCompatible::Incompatible),
890                    VarArgCompatible::Compatible => interp_ok(VarArgCompatible::Compatible),
891                    VarArgCompatible::CastIntTo { source_is_signed: _ } => {
892                        // The integer cast check is not needed when the value is behind a pointer.
893                        interp_ok(VarArgCompatible::Compatible)
894                    }
895                }
896            }
897            (ty::Int(_), ty::Uint(_)) => {
898                interp_ok(VarArgCompatible::CastIntTo { source_is_signed: true })
899            }
900            (ty::Uint(_), ty::Int(_)) => {
901                interp_ok(VarArgCompatible::CastIntTo { source_is_signed: false })
902            }
903            (ty::Int(_), ty::Int(_)) | (ty::Uint(_), ty::Uint(_)) => {
904                // E.g. cast between `usize` and `u64` on a 64-bit platform.
905                interp_ok(VarArgCompatible::Compatible)
906            }
907            _ => interp_ok(VarArgCompatible::Incompatible),
908        }
909    }
910
911    pub(super) fn eval_nondiverging_intrinsic(
912        &mut self,
913        intrinsic: &NonDivergingIntrinsic<'tcx>,
914    ) -> InterpResult<'tcx> {
915        match intrinsic {
916            NonDivergingIntrinsic::Assume(op) => {
917                let op = self.eval_operand(op, None)?;
918                let cond = self.read_scalar(&op)?.to_bool()?;
919                if !cond {
920                    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`");
921                }
922                interp_ok(())
923            }
924            NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
925                count,
926                src,
927                dst,
928            }) => {
929                let src = self.eval_operand(src, None)?;
930                let dst = self.eval_operand(dst, None)?;
931                let count = self.eval_operand(count, None)?;
932                self.copy_intrinsic(&src, &dst, &count, /* nonoverlapping */ true)
933            }
934        }
935    }
936
937    pub fn numeric_intrinsic(
938        &self,
939        name: Symbol,
940        val: Scalar<M::Provenance>,
941        layout: TyAndLayout<'tcx>,
942        ret_layout: TyAndLayout<'tcx>,
943    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
944        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);
945        let bits = val.to_bits(layout.size)?; // these operations all ignore the sign
946        let extra = 128 - u128::from(layout.size.bits());
947        let bits_out = match name {
948            sym::ctpop => u128::from(bits.count_ones()),
949            sym::ctlz_nonzero | sym::cttz_nonzero if bits == 0 => {
950                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");
951            }
952            sym::ctlz | sym::ctlz_nonzero => u128::from(bits.leading_zeros()) - extra,
953            sym::cttz | sym::cttz_nonzero => u128::from((bits << extra).trailing_zeros()) - extra,
954            sym::bswap => {
955                {
    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);
956                (bits << extra).swap_bytes()
957            }
958            sym::bitreverse => {
959                {
    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);
960                (bits << extra).reverse_bits()
961            }
962            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("not a numeric intrinsic: {0}",
        name))bug!("not a numeric intrinsic: {}", name),
963        };
964        interp_ok(Scalar::from_uint(bits_out, ret_layout.size))
965    }
966
967    pub fn exact_div(
968        &mut self,
969        a: &ImmTy<'tcx, M::Provenance>,
970        b: &ImmTy<'tcx, M::Provenance>,
971        dest: &PlaceTy<'tcx, M::Provenance>,
972    ) -> InterpResult<'tcx> {
973        {
    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);
974        {
    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(..));
975
976        // Performs an exact division, resulting in undefined behavior where
977        // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
978        // First, check x % y != 0 (or if that computation overflows).
979        let rem = self.binary_op(BinOp::Rem, a, b)?;
980        // sign does not matter for 0 test, so `to_bits` is fine
981        if rem.to_scalar().to_bits(a.layout.size)? != 0 {
982            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")
983        }
984        // `Rem` says this is all right, so we can let `Div` do its job.
985        let res = self.binary_op(BinOp::Div, a, b)?;
986        self.write_immediate(*res, dest)
987    }
988
989    pub fn saturating_arith(
990        &self,
991        mir_op: BinOp,
992        l: &ImmTy<'tcx, M::Provenance>,
993        r: &ImmTy<'tcx, M::Provenance>,
994    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
995        {
    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);
996        {
    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(..));
997        {
    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);
998
999        let (val, overflowed) =
1000            self.binary_op(mir_op.wrapping_to_overflowing().unwrap(), l, r)?.to_scalar_pair();
1001        interp_ok(if overflowed.to_bool()? {
1002            let size = l.layout.size;
1003            if l.layout.backend_repr.is_signed() {
1004                // For signed ints the saturated value depends on the sign of the first
1005                // term since the sign of the second term can be inferred from this and
1006                // the fact that the operation has overflowed (if either is 0 no
1007                // overflow can occur)
1008                let first_term: i128 = l.to_scalar().to_int(l.layout.size)?;
1009                if first_term >= 0 {
1010                    // Negative overflow not possible since the positive first term
1011                    // can only increase an (in range) negative term for addition
1012                    // or corresponding negated positive term for subtraction.
1013                    Scalar::from_int(size.signed_int_max(), size)
1014                } else {
1015                    // Positive overflow not possible for similar reason.
1016                    Scalar::from_int(size.signed_int_min(), size)
1017                }
1018            } else {
1019                // unsigned
1020                if mir_op == BinOp::Add {
1021                    // max unsigned
1022                    Scalar::from_uint(size.unsigned_int_max(), size)
1023                } else {
1024                    // underflow to 0
1025                    Scalar::from_uint(0u128, size)
1026                }
1027            }
1028        } else {
1029            val
1030        })
1031    }
1032
1033    /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
1034    /// allocation.
1035    pub fn ptr_offset_inbounds(
1036        &self,
1037        ptr: Pointer<Option<M::Provenance>>,
1038        offset_bytes: i64,
1039    ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
1040        // The offset must be in bounds starting from `ptr`.
1041        self.check_ptr_access_signed(
1042            ptr,
1043            offset_bytes,
1044            CheckInAllocMsg::InboundsPointerArithmetic,
1045        )?;
1046        // This also implies that there is no overflow, so we are done.
1047        interp_ok(ptr.wrapping_signed_offset(offset_bytes, self))
1048    }
1049
1050    /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.
1051    pub(crate) fn copy_intrinsic(
1052        &mut self,
1053        src: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1054        dst: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1055        count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1056        nonoverlapping: bool,
1057    ) -> InterpResult<'tcx> {
1058        let count = self.read_target_usize(count)?;
1059        let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap())?;
1060        let (size, align) = (layout.size, layout.align.abi);
1061
1062        let size = self.compute_size_in_bytes(size, count).ok_or_else(|| {
1063            ::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!(
1064                "overflow computing total size of `{name}`",
1065                name = if nonoverlapping { "copy_nonoverlapping" } else { "copy" }
1066            )
1067        })?;
1068
1069        let src = self.read_pointer(src)?;
1070        let dst = self.read_pointer(dst)?;
1071
1072        self.check_ptr_align(src, align)?;
1073        self.check_ptr_align(dst, align)?;
1074
1075        self.mem_copy(src, dst, size, nonoverlapping)
1076    }
1077
1078    /// Does a *typed* swap of `*left` and `*right`.
1079    fn typed_swap_nonoverlapping_intrinsic(
1080        &mut self,
1081        left: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1082        right: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1083    ) -> InterpResult<'tcx> {
1084        let left = self.deref_pointer(left)?;
1085        let right = self.deref_pointer(right)?;
1086        {
    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);
1087        if !left.layout.is_sized() {
    ::core::panicking::panic("assertion failed: left.layout.is_sized()")
};assert!(left.layout.is_sized());
1088        let kind = MemoryKind::Stack;
1089        let temp = self.allocate(left.layout, kind)?;
1090        self.copy_op(&left, &temp)?; // checks alignment of `left`
1091
1092        // We want to always enforce non-overlapping, even if this is a scalar type.
1093        // Therefore we directly use the underlying `mem_copy` here.
1094        self.mem_copy(right.ptr(), left.ptr(), left.layout.size, /*nonoverlapping*/ true)?;
1095        // This means we also need to do the validation of the value that used to be in `right`
1096        // ourselves. This value is now in `left.` The one that started out in `left` already got
1097        // validated by the copy above.
1098        if M::enforce_validity(self, left.layout) {
1099            self.validate_operand(
1100                &left.clone().into(),
1101                M::enforce_validity_recursively(self, left.layout),
1102                /*reset_provenance_and_padding*/ true,
1103            )?;
1104        }
1105
1106        self.copy_op(&temp, &right)?; // checks alignment of `right`
1107
1108        self.deallocate_ptr(temp.ptr(), None, kind)?;
1109        interp_ok(())
1110    }
1111
1112    pub fn write_bytes_intrinsic(
1113        &mut self,
1114        dst: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1115        byte: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1116        count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1117        name: &'static str,
1118    ) -> InterpResult<'tcx> {
1119        let layout = self.layout_of(dst.layout.ty.builtin_deref(true).unwrap())?;
1120
1121        let dst = self.read_pointer(dst)?;
1122        let byte = self.read_scalar(byte)?.to_u8()?;
1123        let count = self.read_target_usize(count)?;
1124
1125        // `checked_mul` enforces a too small bound (the correct one would probably be target_isize_max),
1126        // but no actual allocation can be big enough for the difference to be noticeable.
1127        let len = self
1128            .compute_size_in_bytes(layout.size, count)
1129            .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}`"))?;
1130
1131        let bytes = std::iter::repeat_n(byte, len.bytes_usize());
1132        self.write_bytes_ptr(dst, bytes)
1133    }
1134
1135    pub(crate) fn compare_bytes_intrinsic(
1136        &mut self,
1137        left: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1138        right: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1139        byte_count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1140    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
1141        let left = self.read_pointer(left)?;
1142        let right = self.read_pointer(right)?;
1143        let n = Size::from_bytes(self.read_target_usize(byte_count)?);
1144
1145        let left_bytes = self.read_bytes_ptr_strip_provenance(left, n)?;
1146        let right_bytes = self.read_bytes_ptr_strip_provenance(right, n)?;
1147
1148        // `Ordering`'s discriminants are -1/0/+1, so casting does the right thing.
1149        let result = Ord::cmp(left_bytes, right_bytes) as i32;
1150        interp_ok(Scalar::from_i32(result))
1151    }
1152
1153    pub(crate) fn raw_eq_intrinsic(
1154        &mut self,
1155        lhs: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1156        rhs: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1157    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
1158        let layout = self.layout_of(lhs.layout.ty.builtin_deref(true).unwrap())?;
1159        if !layout.is_sized() {
    ::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
1160
1161        let get_bytes = |this: &InterpCx<'tcx, M>,
1162                         op: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>|
1163         -> InterpResult<'tcx, &[u8]> {
1164            let ptr = this.read_pointer(op)?;
1165            this.check_ptr_align(ptr, layout.align.abi)?;
1166            let Some(alloc_ref) = self.get_ptr_alloc(ptr, layout.size)? else {
1167                // zero-sized access
1168                return interp_ok(&[]);
1169            };
1170            alloc_ref.get_bytes_strip_provenance()
1171        };
1172
1173        let lhs_bytes = get_bytes(self, lhs)?;
1174        let rhs_bytes = get_bytes(self, rhs)?;
1175        interp_ok(Scalar::from_bool(lhs_bytes == rhs_bytes))
1176    }
1177
1178    fn unop_float_intrinsic<F>(
1179        &self,
1180        name: Symbol,
1181        arg: ImmTy<'tcx, M::Provenance>,
1182    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1183    where
1184        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1185    {
1186        let x: F = arg.to_scalar().to_float()?;
1187        match name {
1188            // bitwise, no NaN adjustments
1189            sym::fabs => interp_ok(x.abs().into()),
1190            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("not a unary float intrinsic: {0}",
        name))bug!("not a unary float intrinsic: {}", name),
1191        }
1192    }
1193
1194    fn float_minmax<F>(
1195        &self,
1196        a: Scalar<M::Provenance>,
1197        b: Scalar<M::Provenance>,
1198        op: MinMax,
1199    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1200    where
1201        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1202    {
1203        let a: F = a.to_float()?;
1204        let b: F = b.to_float()?;
1205        let res = if #[allow(non_exhaustive_omitted_patterns)] match op {
    MinMax::MinimumNumberNsz | MinMax::MaximumNumberNsz => true,
    _ => false,
}matches!(op, MinMax::MinimumNumberNsz | MinMax::MaximumNumberNsz) && a == b {
1206            // They are definitely not NaN (those are never equal), but they could be `+0` and `-0`.
1207            // Let the machine decide which one to return.
1208            M::equal_float_min_max(self, a, b)
1209        } else {
1210            let result = match op {
1211                MinMax::Minimum => a.minimum(b),
1212                MinMax::MinimumNumberNsz => a.min(b),
1213                MinMax::Maximum => a.maximum(b),
1214                MinMax::MaximumNumberNsz => a.max(b),
1215            };
1216            self.adjust_nan(result, &[a, b])
1217        };
1218
1219        interp_ok(res.into())
1220    }
1221
1222    fn float_minmax_intrinsic<F>(
1223        &mut self,
1224        args: &[OpTy<'tcx, M::Provenance>],
1225        op: MinMax,
1226        dest: &PlaceTy<'tcx, M::Provenance>,
1227    ) -> InterpResult<'tcx, ()>
1228    where
1229        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1230    {
1231        let res =
1232            self.float_minmax::<F>(self.read_scalar(&args[0])?, self.read_scalar(&args[1])?, op)?;
1233        self.write_scalar(res, dest)?;
1234        interp_ok(())
1235    }
1236
1237    fn float_copysign_intrinsic<F>(
1238        &mut self,
1239        args: &[OpTy<'tcx, M::Provenance>],
1240        dest: &PlaceTy<'tcx, M::Provenance>,
1241    ) -> InterpResult<'tcx, ()>
1242    where
1243        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1244    {
1245        let a: F = self.read_scalar(&args[0])?.to_float()?;
1246        let b: F = self.read_scalar(&args[1])?.to_float()?;
1247        // bitwise, no NaN adjustments
1248        self.write_scalar(a.copy_sign(b), dest)?;
1249        interp_ok(())
1250    }
1251
1252    fn float_round<F>(
1253        &mut self,
1254        x: Scalar<M::Provenance>,
1255        mode: rustc_apfloat::Round,
1256    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1257    where
1258        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1259    {
1260        let x: F = x.to_float()?;
1261        let res = x.round_to_integral(mode).value;
1262        let res = self.adjust_nan(res, &[x]);
1263        interp_ok(res.into())
1264    }
1265
1266    fn float_round_intrinsic<F>(
1267        &mut self,
1268        args: &[OpTy<'tcx, M::Provenance>],
1269        dest: &PlaceTy<'tcx, M::Provenance>,
1270        mode: rustc_apfloat::Round,
1271    ) -> InterpResult<'tcx, ()>
1272    where
1273        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1274    {
1275        let res = self.float_round::<F>(self.read_scalar(&args[0])?, mode)?;
1276        self.write_scalar(res, dest)?;
1277        interp_ok(())
1278    }
1279
1280    fn float_muladd<F>(
1281        &self,
1282        a: Scalar<M::Provenance>,
1283        b: Scalar<M::Provenance>,
1284        c: Scalar<M::Provenance>,
1285        typ: MulAddType,
1286    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1287    where
1288        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1289    {
1290        let a: F = a.to_float()?;
1291        let b: F = b.to_float()?;
1292        let c: F = c.to_float()?;
1293
1294        let fuse = typ == MulAddType::Fused || M::float_fuse_mul_add(self);
1295
1296        let res = if fuse { a.mul_add(b, c).value } else { ((a * b).value + c).value };
1297        let res = self.adjust_nan(res, &[a, b, c]);
1298        interp_ok(res.into())
1299    }
1300
1301    fn float_muladd_intrinsic<F>(
1302        &mut self,
1303        args: &[OpTy<'tcx, M::Provenance>],
1304        dest: &PlaceTy<'tcx, M::Provenance>,
1305        typ: MulAddType,
1306    ) -> InterpResult<'tcx, ()>
1307    where
1308        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1309    {
1310        let a = self.read_scalar(&args[0])?;
1311        let b = self.read_scalar(&args[1])?;
1312        let c = self.read_scalar(&args[2])?;
1313
1314        let res = self.float_muladd::<F>(a, b, c, typ)?;
1315        self.write_scalar(res, dest)?;
1316        interp_ok(())
1317    }
1318
1319    /// Converts `src` from floating point to integer type `dest_ty`
1320    /// after rounding with mode `round`.
1321    /// Returns `None` if `f` is NaN or out of range.
1322    pub fn float_to_int_checked(
1323        &self,
1324        src: &ImmTy<'tcx, M::Provenance>,
1325        cast_to: TyAndLayout<'tcx>,
1326        round: rustc_apfloat::Round,
1327    ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::Provenance>>> {
1328        fn float_to_int_inner<'tcx, F: rustc_apfloat::Float, M: Machine<'tcx>>(
1329            ecx: &InterpCx<'tcx, M>,
1330            src: F,
1331            cast_to: TyAndLayout<'tcx>,
1332            round: rustc_apfloat::Round,
1333        ) -> (Scalar<M::Provenance>, rustc_apfloat::Status) {
1334            let int_size = cast_to.layout.size;
1335            match cast_to.ty.kind() {
1336                // Unsigned
1337                ty::Uint(_) => {
1338                    let res = src.to_u128_r(int_size.bits_usize(), round, &mut false);
1339                    (Scalar::from_uint(res.value, int_size), res.status)
1340                }
1341                // Signed
1342                ty::Int(_) => {
1343                    let res = src.to_i128_r(int_size.bits_usize(), round, &mut false);
1344                    (Scalar::from_int(res.value, int_size), res.status)
1345                }
1346                // Nothing else
1347                _ => ::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!(
1348                    ecx.cur_span(),
1349                    "attempted float-to-int conversion with non-int output type {}",
1350                    cast_to.ty,
1351                ),
1352            }
1353        }
1354
1355        let ty::Float(fty) = src.layout.ty.kind() else {
1356            ::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)
1357        };
1358
1359        let (val, status) = match fty {
1360            FloatTy::F16 => float_to_int_inner(self, src.to_scalar().to_f16()?, cast_to, round),
1361            FloatTy::F32 => float_to_int_inner(self, src.to_scalar().to_f32()?, cast_to, round),
1362            FloatTy::F64 => float_to_int_inner(self, src.to_scalar().to_f64()?, cast_to, round),
1363            FloatTy::F128 => float_to_int_inner(self, src.to_scalar().to_f128()?, cast_to, round),
1364        };
1365
1366        if status.intersects(
1367            rustc_apfloat::Status::INVALID_OP
1368                | rustc_apfloat::Status::OVERFLOW
1369                | rustc_apfloat::Status::UNDERFLOW,
1370        ) {
1371            // Floating point value is NaN (flagged with INVALID_OP) or outside the range
1372            // of values of the integer type (flagged with OVERFLOW or UNDERFLOW).
1373            interp_ok(None)
1374        } else {
1375            // Floating point value can be represented by the integer type after rounding.
1376            // The INEXACT flag is ignored on purpose to allow rounding.
1377            interp_ok(Some(ImmTy::from_scalar(val, cast_to)))
1378        }
1379    }
1380
1381    /// Get the MPlace of the key from the place storing the VaList.
1382    pub(super) fn va_list_key_field<P: Projectable<'tcx, M::Provenance>>(
1383        &self,
1384        va_list: &P,
1385    ) -> InterpResult<'tcx, P> {
1386        // The struct wrapped by VaList.
1387        let va_list_inner = self.project_field(va_list, FieldIdx::ZERO)?;
1388
1389        // Find the first pointer field in this struct. The exact index is target-specific.
1390        let ty::Adt(adt, substs) = va_list_inner.layout().ty.kind() else {
1391            ::rustc_middle::util::bug::bug_fmt(format_args!("invalid VaListImpl layout"));bug!("invalid VaListImpl layout");
1392        };
1393
1394        for (i, field) in adt.non_enum_variant().fields.iter().enumerate() {
1395            if field.ty(*self.tcx, substs).skip_norm_wip().is_raw_ptr() {
1396                return self.project_field(&va_list_inner, FieldIdx::from_usize(i));
1397            }
1398        }
1399
1400        ::rustc_middle::util::bug::bug_fmt(format_args!("no VaListImpl field is a pointer"));bug!("no VaListImpl field is a pointer");
1401    }
1402}