Skip to main content

rustc_const_eval/interpret/
intrinsics.rs

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