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