rustc_const_eval/interpret/
intrinsics.rs

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