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_hir::def_id::CRATE_DEF_ID;
11use rustc_infer::infer::TyCtxtInferExt;
12use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, read_target_uint, write_target_uint};
13use rustc_middle::mir::{self, BinOp, ConstValue, NonDivergingIntrinsic};
14use rustc_middle::ty::layout::TyAndLayout;
15use rustc_middle::ty::{FloatTy, PolyExistentialPredicate, Ty, TyCtxt};
16use rustc_middle::{bug, span_bug, ty};
17use rustc_span::{Symbol, sym};
18use rustc_trait_selection::traits::{Obligation, ObligationCause, ObligationCtxt};
19use tracing::trace;
20
21use super::memory::MemoryKind;
22use super::util::ensure_monomorphic_enough;
23use super::{
24    AllocId, CheckInAllocMsg, ImmTy, InterpCx, InterpResult, Machine, OpTy, PlaceTy, Pointer,
25    PointerArithmetic, Provenance, Scalar, err_ub_custom, err_unsup_format, interp_ok, throw_inval,
26    throw_ub_custom, throw_ub_format,
27};
28use crate::fluent_generated as fluent;
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: ||
                        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!(
441                                fluent::const_eval_offset_from_different_allocations,
442                                name = intrinsic_name,
443                            );
444                        }
445                    }
446                };
447
448                // Compute distance: a - b.
449                let dist = {
450                    // Addresses are unsigned, so this is a `usize` computation. We have to do the
451                    // overflow check separately anyway.
452                    let (val, overflowed) = {
453                        let a_offset = ImmTy::from_uint(a_offset, usize_layout);
454                        let b_offset = ImmTy::from_uint(b_offset, usize_layout);
455                        self.binary_op(BinOp::SubWithOverflow, &a_offset, &b_offset)?
456                            .to_scalar_pair()
457                    };
458                    if overflowed.to_bool()? {
459                        // a < b
460                        if intrinsic_name == sym::ptr_offset_from_unsigned {
461                            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!(
462                                fluent::const_eval_offset_from_unsigned_overflow,
463                                a_offset = a_offset,
464                                b_offset = b_offset,
465                                is_addr = is_addr,
466                            );
467                        }
468                        // The signed form of the intrinsic allows this. If we interpret the
469                        // difference as isize, we'll get the proper signed difference. If that
470                        // seems *positive* or equal to isize::MIN, they were more than isize::MAX apart.
471                        let dist = val.to_target_isize(self)?;
472                        if dist >= 0 || i128::from(dist) == self.pointer_size().signed_int_min() {
473                            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!(
474                                fluent::const_eval_offset_from_underflow,
475                                name = intrinsic_name,
476                            );
477                        }
478                        dist
479                    } else {
480                        // b >= a
481                        let dist = val.to_target_isize(self)?;
482                        // If converting to isize produced a *negative* result, we had an overflow
483                        // because they were more than isize::MAX apart.
484                        if dist < 0 {
485                            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!(
486                                fluent::const_eval_offset_from_overflow,
487                                name = intrinsic_name,
488                            );
489                        }
490                        dist
491                    }
492                };
493
494                // Check that the memory between them is dereferenceable at all, starting from the
495                // origin pointer: `dist` is `a - b`, so it is based on `b`.
496                self.check_ptr_access_signed(b, dist, CheckInAllocMsg::Dereferenceable)
497                    .map_err_kind(|_| {
498                        // This could mean they point to different allocations, or they point to the same allocation
499                        // but not the entire range between the pointers is in-bounds.
500                        if let Ok((a_alloc_id, ..)) = self.ptr_try_get_alloc_id(a, 0)
501                            && let Ok((b_alloc_id, ..)) = self.ptr_try_get_alloc_id(b, 0)
502                            && a_alloc_id == b_alloc_id
503                        {
504                            {
    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!(
505                                fluent::const_eval_offset_from_out_of_bounds,
506                                name = intrinsic_name,
507                            )
508                        } else {
509                            {
    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!(
510                                fluent::const_eval_offset_from_different_allocations,
511                                name = intrinsic_name,
512                            )
513                        }
514                    })?;
515                // Then check that this is also dereferenceable from `a`. This ensures that they are
516                // derived from the same allocation.
517                self.check_ptr_access_signed(
518                    a,
519                    dist.checked_neg().unwrap(), // i64::MIN is impossible as no allocation can be that large
520                    CheckInAllocMsg::Dereferenceable,
521                )
522                .map_err_kind(|_| {
523                    // Make the error more specific.
524                    {
    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!(
525                        fluent::const_eval_offset_from_different_allocations,
526                        name = intrinsic_name,
527                    )
528                })?;
529
530                // Perform division by size to compute return value.
531                let ret_layout = if intrinsic_name == sym::ptr_offset_from_unsigned {
532                    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());
533                    usize_layout
534                } else {
535                    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());
536                    isize_layout
537                };
538                let pointee_layout = self.layout_of(instance_args.type_at(0))?;
539                // If ret_layout is unsigned, we checked that so is the distance, so we are good.
540                let val = ImmTy::from_int(dist, ret_layout);
541                let size = ImmTy::from_int(pointee_layout.size.bytes(), ret_layout);
542                self.exact_div(&val, &size, dest)?;
543            }
544
545            sym::black_box => {
546                // These just return their argument
547                self.copy_op(&args[0], dest)?;
548            }
549            sym::raw_eq => {
550                let result = self.raw_eq_intrinsic(&args[0], &args[1])?;
551                self.write_scalar(result, dest)?;
552            }
553            sym::typed_swap_nonoverlapping => {
554                self.typed_swap_nonoverlapping_intrinsic(&args[0], &args[1])?;
555            }
556
557            sym::vtable_size => {
558                let ptr = self.read_pointer(&args[0])?;
559                // `None` because we don't know which trait to expect here; any vtable is okay.
560                let (size, _align) = self.get_vtable_size_and_align(ptr, None)?;
561                self.write_scalar(Scalar::from_target_usize(size.bytes(), self), dest)?;
562            }
563            sym::vtable_align => {
564                let ptr = self.read_pointer(&args[0])?;
565                // `None` because we don't know which trait to expect here; any vtable is okay.
566                let (_size, align) = self.get_vtable_size_and_align(ptr, None)?;
567                self.write_scalar(Scalar::from_target_usize(align.bytes(), self), dest)?;
568            }
569
570            sym::minnumf16 => {
571                self.float_minmax_intrinsic::<Half>(args, MinMax::MinimumNumber, dest)?
572            }
573            sym::minnumf32 => {
574                self.float_minmax_intrinsic::<Single>(args, MinMax::MinimumNumber, dest)?
575            }
576            sym::minnumf64 => {
577                self.float_minmax_intrinsic::<Double>(args, MinMax::MinimumNumber, dest)?
578            }
579            sym::minnumf128 => {
580                self.float_minmax_intrinsic::<Quad>(args, MinMax::MinimumNumber, dest)?
581            }
582
583            sym::minimumf16 => self.float_minmax_intrinsic::<Half>(args, MinMax::Minimum, dest)?,
584            sym::minimumf32 => {
585                self.float_minmax_intrinsic::<Single>(args, MinMax::Minimum, dest)?
586            }
587            sym::minimumf64 => {
588                self.float_minmax_intrinsic::<Double>(args, MinMax::Minimum, dest)?
589            }
590            sym::minimumf128 => self.float_minmax_intrinsic::<Quad>(args, MinMax::Minimum, dest)?,
591
592            sym::maxnumf16 => {
593                self.float_minmax_intrinsic::<Half>(args, MinMax::MaximumNumber, dest)?
594            }
595            sym::maxnumf32 => {
596                self.float_minmax_intrinsic::<Single>(args, MinMax::MaximumNumber, dest)?
597            }
598            sym::maxnumf64 => {
599                self.float_minmax_intrinsic::<Double>(args, MinMax::MaximumNumber, dest)?
600            }
601            sym::maxnumf128 => {
602                self.float_minmax_intrinsic::<Quad>(args, MinMax::MaximumNumber, dest)?
603            }
604
605            sym::maximumf16 => self.float_minmax_intrinsic::<Half>(args, MinMax::Maximum, dest)?,
606            sym::maximumf32 => {
607                self.float_minmax_intrinsic::<Single>(args, MinMax::Maximum, dest)?
608            }
609            sym::maximumf64 => {
610                self.float_minmax_intrinsic::<Double>(args, MinMax::Maximum, dest)?
611            }
612            sym::maximumf128 => self.float_minmax_intrinsic::<Quad>(args, MinMax::Maximum, dest)?,
613
614            sym::copysignf16 => self.float_copysign_intrinsic::<Half>(args, dest)?,
615            sym::copysignf32 => self.float_copysign_intrinsic::<Single>(args, dest)?,
616            sym::copysignf64 => self.float_copysign_intrinsic::<Double>(args, dest)?,
617            sym::copysignf128 => self.float_copysign_intrinsic::<Quad>(args, dest)?,
618
619            sym::fabsf16 => self.float_abs_intrinsic::<Half>(args, dest)?,
620            sym::fabsf32 => self.float_abs_intrinsic::<Single>(args, dest)?,
621            sym::fabsf64 => self.float_abs_intrinsic::<Double>(args, dest)?,
622            sym::fabsf128 => self.float_abs_intrinsic::<Quad>(args, dest)?,
623
624            sym::floorf16 => self.float_round_intrinsic::<Half>(
625                args,
626                dest,
627                rustc_apfloat::Round::TowardNegative,
628            )?,
629            sym::floorf32 => self.float_round_intrinsic::<Single>(
630                args,
631                dest,
632                rustc_apfloat::Round::TowardNegative,
633            )?,
634            sym::floorf64 => self.float_round_intrinsic::<Double>(
635                args,
636                dest,
637                rustc_apfloat::Round::TowardNegative,
638            )?,
639            sym::floorf128 => self.float_round_intrinsic::<Quad>(
640                args,
641                dest,
642                rustc_apfloat::Round::TowardNegative,
643            )?,
644
645            sym::ceilf16 => self.float_round_intrinsic::<Half>(
646                args,
647                dest,
648                rustc_apfloat::Round::TowardPositive,
649            )?,
650            sym::ceilf32 => self.float_round_intrinsic::<Single>(
651                args,
652                dest,
653                rustc_apfloat::Round::TowardPositive,
654            )?,
655            sym::ceilf64 => self.float_round_intrinsic::<Double>(
656                args,
657                dest,
658                rustc_apfloat::Round::TowardPositive,
659            )?,
660            sym::ceilf128 => self.float_round_intrinsic::<Quad>(
661                args,
662                dest,
663                rustc_apfloat::Round::TowardPositive,
664            )?,
665
666            sym::truncf16 => {
667                self.float_round_intrinsic::<Half>(args, dest, rustc_apfloat::Round::TowardZero)?
668            }
669            sym::truncf32 => {
670                self.float_round_intrinsic::<Single>(args, dest, rustc_apfloat::Round::TowardZero)?
671            }
672            sym::truncf64 => {
673                self.float_round_intrinsic::<Double>(args, dest, rustc_apfloat::Round::TowardZero)?
674            }
675            sym::truncf128 => {
676                self.float_round_intrinsic::<Quad>(args, dest, rustc_apfloat::Round::TowardZero)?
677            }
678
679            sym::roundf16 => self.float_round_intrinsic::<Half>(
680                args,
681                dest,
682                rustc_apfloat::Round::NearestTiesToAway,
683            )?,
684            sym::roundf32 => self.float_round_intrinsic::<Single>(
685                args,
686                dest,
687                rustc_apfloat::Round::NearestTiesToAway,
688            )?,
689            sym::roundf64 => self.float_round_intrinsic::<Double>(
690                args,
691                dest,
692                rustc_apfloat::Round::NearestTiesToAway,
693            )?,
694            sym::roundf128 => self.float_round_intrinsic::<Quad>(
695                args,
696                dest,
697                rustc_apfloat::Round::NearestTiesToAway,
698            )?,
699
700            sym::round_ties_even_f16 => self.float_round_intrinsic::<Half>(
701                args,
702                dest,
703                rustc_apfloat::Round::NearestTiesToEven,
704            )?,
705            sym::round_ties_even_f32 => self.float_round_intrinsic::<Single>(
706                args,
707                dest,
708                rustc_apfloat::Round::NearestTiesToEven,
709            )?,
710            sym::round_ties_even_f64 => self.float_round_intrinsic::<Double>(
711                args,
712                dest,
713                rustc_apfloat::Round::NearestTiesToEven,
714            )?,
715            sym::round_ties_even_f128 => self.float_round_intrinsic::<Quad>(
716                args,
717                dest,
718                rustc_apfloat::Round::NearestTiesToEven,
719            )?,
720            sym::fmaf16 => self.float_muladd_intrinsic::<Half>(args, dest, MulAddType::Fused)?,
721            sym::fmaf32 => self.float_muladd_intrinsic::<Single>(args, dest, MulAddType::Fused)?,
722            sym::fmaf64 => self.float_muladd_intrinsic::<Double>(args, dest, MulAddType::Fused)?,
723            sym::fmaf128 => self.float_muladd_intrinsic::<Quad>(args, dest, MulAddType::Fused)?,
724            sym::fmuladdf16 => {
725                self.float_muladd_intrinsic::<Half>(args, dest, MulAddType::Nondeterministic)?
726            }
727            sym::fmuladdf32 => {
728                self.float_muladd_intrinsic::<Single>(args, dest, MulAddType::Nondeterministic)?
729            }
730            sym::fmuladdf64 => {
731                self.float_muladd_intrinsic::<Double>(args, dest, MulAddType::Nondeterministic)?
732            }
733            sym::fmuladdf128 => {
734                self.float_muladd_intrinsic::<Quad>(args, dest, MulAddType::Nondeterministic)?
735            }
736
737            // Unsupported intrinsic: skip the return_to_block below.
738            _ => return interp_ok(false),
739        }
740
741        {
    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:741",
                        "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(741u32),
                        ::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()));
742        self.return_to_block(ret)?;
743        interp_ok(true)
744    }
745
746    pub(super) fn eval_nondiverging_intrinsic(
747        &mut self,
748        intrinsic: &NonDivergingIntrinsic<'tcx>,
749    ) -> InterpResult<'tcx> {
750        match intrinsic {
751            NonDivergingIntrinsic::Assume(op) => {
752                let op = self.eval_operand(op, None)?;
753                let cond = self.read_scalar(&op)?.to_bool()?;
754                if !cond {
755                    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);
756                }
757                interp_ok(())
758            }
759            NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
760                count,
761                src,
762                dst,
763            }) => {
764                let src = self.eval_operand(src, None)?;
765                let dst = self.eval_operand(dst, None)?;
766                let count = self.eval_operand(count, None)?;
767                self.copy_intrinsic(&src, &dst, &count, /* nonoverlapping */ true)
768            }
769        }
770    }
771
772    pub fn numeric_intrinsic(
773        &self,
774        name: Symbol,
775        val: Scalar<M::Provenance>,
776        layout: TyAndLayout<'tcx>,
777        ret_layout: TyAndLayout<'tcx>,
778    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
779        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);
780        let bits = val.to_bits(layout.size)?; // these operations all ignore the sign
781        let extra = 128 - u128::from(layout.size.bits());
782        let bits_out = match name {
783            sym::ctpop => u128::from(bits.count_ones()),
784            sym::ctlz_nonzero | sym::cttz_nonzero if bits == 0 => {
785                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,);
786            }
787            sym::ctlz | sym::ctlz_nonzero => u128::from(bits.leading_zeros()) - extra,
788            sym::cttz | sym::cttz_nonzero => u128::from((bits << extra).trailing_zeros()) - extra,
789            sym::bswap => {
790                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);
791                (bits << extra).swap_bytes()
792            }
793            sym::bitreverse => {
794                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);
795                (bits << extra).reverse_bits()
796            }
797            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("not a numeric intrinsic: {0}",
        name))bug!("not a numeric intrinsic: {}", name),
798        };
799        interp_ok(Scalar::from_uint(bits_out, ret_layout.size))
800    }
801
802    pub fn exact_div(
803        &mut self,
804        a: &ImmTy<'tcx, M::Provenance>,
805        b: &ImmTy<'tcx, M::Provenance>,
806        dest: &PlaceTy<'tcx, M::Provenance>,
807    ) -> InterpResult<'tcx> {
808        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);
809        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(..));
810
811        // Performs an exact division, resulting in undefined behavior where
812        // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
813        // First, check x % y != 0 (or if that computation overflows).
814        let rem = self.binary_op(BinOp::Rem, a, b)?;
815        // sign does not matter for 0 test, so `to_bits` is fine
816        if rem.to_scalar().to_bits(a.layout.size)? != 0 {
817            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!(
818                fluent::const_eval_exact_div_has_remainder,
819                a = format!("{a}"),
820                b = format!("{b}")
821            )
822        }
823        // `Rem` says this is all right, so we can let `Div` do its job.
824        let res = self.binary_op(BinOp::Div, a, b)?;
825        self.write_immediate(*res, dest)
826    }
827
828    pub fn saturating_arith(
829        &self,
830        mir_op: BinOp,
831        l: &ImmTy<'tcx, M::Provenance>,
832        r: &ImmTy<'tcx, M::Provenance>,
833    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
834        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);
835        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(..));
836        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);
837
838        let (val, overflowed) =
839            self.binary_op(mir_op.wrapping_to_overflowing().unwrap(), l, r)?.to_scalar_pair();
840        interp_ok(if overflowed.to_bool()? {
841            let size = l.layout.size;
842            if l.layout.backend_repr.is_signed() {
843                // For signed ints the saturated value depends on the sign of the first
844                // term since the sign of the second term can be inferred from this and
845                // the fact that the operation has overflowed (if either is 0 no
846                // overflow can occur)
847                let first_term: i128 = l.to_scalar().to_int(l.layout.size)?;
848                if first_term >= 0 {
849                    // Negative overflow not possible since the positive first term
850                    // can only increase an (in range) negative term for addition
851                    // or corresponding negated positive term for subtraction.
852                    Scalar::from_int(size.signed_int_max(), size)
853                } else {
854                    // Positive overflow not possible for similar reason.
855                    Scalar::from_int(size.signed_int_min(), size)
856                }
857            } else {
858                // unsigned
859                if mir_op == BinOp::Add {
860                    // max unsigned
861                    Scalar::from_uint(size.unsigned_int_max(), size)
862                } else {
863                    // underflow to 0
864                    Scalar::from_uint(0u128, size)
865                }
866            }
867        } else {
868            val
869        })
870    }
871
872    /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
873    /// allocation.
874    pub fn ptr_offset_inbounds(
875        &self,
876        ptr: Pointer<Option<M::Provenance>>,
877        offset_bytes: i64,
878    ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
879        // The offset must be in bounds starting from `ptr`.
880        self.check_ptr_access_signed(
881            ptr,
882            offset_bytes,
883            CheckInAllocMsg::InboundsPointerArithmetic,
884        )?;
885        // This also implies that there is no overflow, so we are done.
886        interp_ok(ptr.wrapping_signed_offset(offset_bytes, self))
887    }
888
889    /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.
890    pub(crate) fn copy_intrinsic(
891        &mut self,
892        src: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
893        dst: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
894        count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
895        nonoverlapping: bool,
896    ) -> InterpResult<'tcx> {
897        let count = self.read_target_usize(count)?;
898        let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap())?;
899        let (size, align) = (layout.size, layout.align.abi);
900
901        let size = self.compute_size_in_bytes(size, count).ok_or_else(|| {
902            {
    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!(
903                fluent::const_eval_size_overflow,
904                name = if nonoverlapping { "copy_nonoverlapping" } else { "copy" }
905            )
906        })?;
907
908        let src = self.read_pointer(src)?;
909        let dst = self.read_pointer(dst)?;
910
911        self.check_ptr_align(src, align)?;
912        self.check_ptr_align(dst, align)?;
913
914        self.mem_copy(src, dst, size, nonoverlapping)
915    }
916
917    /// Does a *typed* swap of `*left` and `*right`.
918    fn typed_swap_nonoverlapping_intrinsic(
919        &mut self,
920        left: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
921        right: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
922    ) -> InterpResult<'tcx> {
923        let left = self.deref_pointer(left)?;
924        let right = self.deref_pointer(right)?;
925        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);
926        if !left.layout.is_sized() {
    ::core::panicking::panic("assertion failed: left.layout.is_sized()")
};assert!(left.layout.is_sized());
927        let kind = MemoryKind::Stack;
928        let temp = self.allocate(left.layout, kind)?;
929        self.copy_op(&left, &temp)?; // checks alignment of `left`
930
931        // We want to always enforce non-overlapping, even if this is a scalar type.
932        // Therefore we directly use the underlying `mem_copy` here.
933        self.mem_copy(right.ptr(), left.ptr(), left.layout.size, /*nonoverlapping*/ true)?;
934        // This means we also need to do the validation of the value that used to be in `right`
935        // ourselves. This value is now in `left.` The one that started out in `left` already got
936        // validated by the copy above.
937        if M::enforce_validity(self, left.layout) {
938            self.validate_operand(
939                &left.clone().into(),
940                M::enforce_validity_recursively(self, left.layout),
941                /*reset_provenance_and_padding*/ true,
942            )?;
943        }
944
945        self.copy_op(&temp, &right)?; // checks alignment of `right`
946
947        self.deallocate_ptr(temp.ptr(), None, kind)?;
948        interp_ok(())
949    }
950
951    pub fn write_bytes_intrinsic(
952        &mut self,
953        dst: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
954        byte: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
955        count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
956        name: &'static str,
957    ) -> InterpResult<'tcx> {
958        let layout = self.layout_of(dst.layout.ty.builtin_deref(true).unwrap())?;
959
960        let dst = self.read_pointer(dst)?;
961        let byte = self.read_scalar(byte)?.to_u8()?;
962        let count = self.read_target_usize(count)?;
963
964        // `checked_mul` enforces a too small bound (the correct one would probably be target_isize_max),
965        // but no actual allocation can be big enough for the difference to be noticeable.
966        let len = self
967            .compute_size_in_bytes(layout.size, count)
968            .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))?;
969
970        let bytes = std::iter::repeat_n(byte, len.bytes_usize());
971        self.write_bytes_ptr(dst, bytes)
972    }
973
974    pub(crate) fn compare_bytes_intrinsic(
975        &mut self,
976        left: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
977        right: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
978        byte_count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
979    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
980        let left = self.read_pointer(left)?;
981        let right = self.read_pointer(right)?;
982        let n = Size::from_bytes(self.read_target_usize(byte_count)?);
983
984        let left_bytes = self.read_bytes_ptr_strip_provenance(left, n)?;
985        let right_bytes = self.read_bytes_ptr_strip_provenance(right, n)?;
986
987        // `Ordering`'s discriminants are -1/0/+1, so casting does the right thing.
988        let result = Ord::cmp(left_bytes, right_bytes) as i32;
989        interp_ok(Scalar::from_i32(result))
990    }
991
992    pub(crate) fn raw_eq_intrinsic(
993        &mut self,
994        lhs: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
995        rhs: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
996    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
997        let layout = self.layout_of(lhs.layout.ty.builtin_deref(true).unwrap())?;
998        if !layout.is_sized() {
    ::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
999
1000        let get_bytes = |this: &InterpCx<'tcx, M>,
1001                         op: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>|
1002         -> InterpResult<'tcx, &[u8]> {
1003            let ptr = this.read_pointer(op)?;
1004            this.check_ptr_align(ptr, layout.align.abi)?;
1005            let Some(alloc_ref) = self.get_ptr_alloc(ptr, layout.size)? else {
1006                // zero-sized access
1007                return interp_ok(&[]);
1008            };
1009            alloc_ref.get_bytes_strip_provenance()
1010        };
1011
1012        let lhs_bytes = get_bytes(self, lhs)?;
1013        let rhs_bytes = get_bytes(self, rhs)?;
1014        interp_ok(Scalar::from_bool(lhs_bytes == rhs_bytes))
1015    }
1016
1017    fn float_minmax<F>(
1018        &self,
1019        a: Scalar<M::Provenance>,
1020        b: Scalar<M::Provenance>,
1021        op: MinMax,
1022    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1023    where
1024        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1025    {
1026        let a: F = a.to_float()?;
1027        let b: F = b.to_float()?;
1028        let res = if #[allow(non_exhaustive_omitted_patterns)] match op {
    MinMax::MinimumNumber | MinMax::MaximumNumber => true,
    _ => false,
}matches!(op, MinMax::MinimumNumber | MinMax::MaximumNumber) && a == b {
1029            // They are definitely not NaN (those are never equal), but they could be `+0` and `-0`.
1030            // Let the machine decide which one to return.
1031            M::equal_float_min_max(self, a, b)
1032        } else {
1033            let result = match op {
1034                MinMax::Minimum => a.minimum(b),
1035                MinMax::MinimumNumber => a.min(b),
1036                MinMax::Maximum => a.maximum(b),
1037                MinMax::MaximumNumber => a.max(b),
1038            };
1039            self.adjust_nan(result, &[a, b])
1040        };
1041
1042        interp_ok(res.into())
1043    }
1044
1045    fn float_minmax_intrinsic<F>(
1046        &mut self,
1047        args: &[OpTy<'tcx, M::Provenance>],
1048        op: MinMax,
1049        dest: &PlaceTy<'tcx, M::Provenance>,
1050    ) -> InterpResult<'tcx, ()>
1051    where
1052        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1053    {
1054        let res =
1055            self.float_minmax::<F>(self.read_scalar(&args[0])?, self.read_scalar(&args[1])?, op)?;
1056        self.write_scalar(res, dest)?;
1057        interp_ok(())
1058    }
1059
1060    fn float_copysign_intrinsic<F>(
1061        &mut self,
1062        args: &[OpTy<'tcx, M::Provenance>],
1063        dest: &PlaceTy<'tcx, M::Provenance>,
1064    ) -> InterpResult<'tcx, ()>
1065    where
1066        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1067    {
1068        let a: F = self.read_scalar(&args[0])?.to_float()?;
1069        let b: F = self.read_scalar(&args[1])?.to_float()?;
1070        // bitwise, no NaN adjustments
1071        self.write_scalar(a.copy_sign(b), dest)?;
1072        interp_ok(())
1073    }
1074
1075    fn float_abs_intrinsic<F>(
1076        &mut self,
1077        args: &[OpTy<'tcx, M::Provenance>],
1078        dest: &PlaceTy<'tcx, M::Provenance>,
1079    ) -> InterpResult<'tcx, ()>
1080    where
1081        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1082    {
1083        let x: F = self.read_scalar(&args[0])?.to_float()?;
1084        // bitwise, no NaN adjustments
1085        self.write_scalar(x.abs(), dest)?;
1086        interp_ok(())
1087    }
1088
1089    fn float_round<F>(
1090        &mut self,
1091        x: Scalar<M::Provenance>,
1092        mode: rustc_apfloat::Round,
1093    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1094    where
1095        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1096    {
1097        let x: F = x.to_float()?;
1098        let res = x.round_to_integral(mode).value;
1099        let res = self.adjust_nan(res, &[x]);
1100        interp_ok(res.into())
1101    }
1102
1103    fn float_round_intrinsic<F>(
1104        &mut self,
1105        args: &[OpTy<'tcx, M::Provenance>],
1106        dest: &PlaceTy<'tcx, M::Provenance>,
1107        mode: rustc_apfloat::Round,
1108    ) -> InterpResult<'tcx, ()>
1109    where
1110        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1111    {
1112        let res = self.float_round::<F>(self.read_scalar(&args[0])?, mode)?;
1113        self.write_scalar(res, dest)?;
1114        interp_ok(())
1115    }
1116
1117    fn float_muladd<F>(
1118        &self,
1119        a: Scalar<M::Provenance>,
1120        b: Scalar<M::Provenance>,
1121        c: Scalar<M::Provenance>,
1122        typ: MulAddType,
1123    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1124    where
1125        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1126    {
1127        let a: F = a.to_float()?;
1128        let b: F = b.to_float()?;
1129        let c: F = c.to_float()?;
1130
1131        let fuse = typ == MulAddType::Fused || M::float_fuse_mul_add(self);
1132
1133        let res = if fuse { a.mul_add(b, c).value } else { ((a * b).value + c).value };
1134        let res = self.adjust_nan(res, &[a, b, c]);
1135        interp_ok(res.into())
1136    }
1137
1138    fn float_muladd_intrinsic<F>(
1139        &mut self,
1140        args: &[OpTy<'tcx, M::Provenance>],
1141        dest: &PlaceTy<'tcx, M::Provenance>,
1142        typ: MulAddType,
1143    ) -> InterpResult<'tcx, ()>
1144    where
1145        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1146    {
1147        let a = self.read_scalar(&args[0])?;
1148        let b = self.read_scalar(&args[1])?;
1149        let c = self.read_scalar(&args[2])?;
1150
1151        let res = self.float_muladd::<F>(a, b, c, typ)?;
1152        self.write_scalar(res, dest)?;
1153        interp_ok(())
1154    }
1155
1156    /// Converts `src` from floating point to integer type `dest_ty`
1157    /// after rounding with mode `round`.
1158    /// Returns `None` if `f` is NaN or out of range.
1159    pub fn float_to_int_checked(
1160        &self,
1161        src: &ImmTy<'tcx, M::Provenance>,
1162        cast_to: TyAndLayout<'tcx>,
1163        round: rustc_apfloat::Round,
1164    ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::Provenance>>> {
1165        fn float_to_int_inner<'tcx, F: rustc_apfloat::Float, M: Machine<'tcx>>(
1166            ecx: &InterpCx<'tcx, M>,
1167            src: F,
1168            cast_to: TyAndLayout<'tcx>,
1169            round: rustc_apfloat::Round,
1170        ) -> (Scalar<M::Provenance>, rustc_apfloat::Status) {
1171            let int_size = cast_to.layout.size;
1172            match cast_to.ty.kind() {
1173                // Unsigned
1174                ty::Uint(_) => {
1175                    let res = src.to_u128_r(int_size.bits_usize(), round, &mut false);
1176                    (Scalar::from_uint(res.value, int_size), res.status)
1177                }
1178                // Signed
1179                ty::Int(_) => {
1180                    let res = src.to_i128_r(int_size.bits_usize(), round, &mut false);
1181                    (Scalar::from_int(res.value, int_size), res.status)
1182                }
1183                // Nothing else
1184                _ => ::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!(
1185                    ecx.cur_span(),
1186                    "attempted float-to-int conversion with non-int output type {}",
1187                    cast_to.ty,
1188                ),
1189            }
1190        }
1191
1192        let ty::Float(fty) = src.layout.ty.kind() else {
1193            ::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)
1194        };
1195
1196        let (val, status) = match fty {
1197            FloatTy::F16 => float_to_int_inner(self, src.to_scalar().to_f16()?, cast_to, round),
1198            FloatTy::F32 => float_to_int_inner(self, src.to_scalar().to_f32()?, cast_to, round),
1199            FloatTy::F64 => float_to_int_inner(self, src.to_scalar().to_f64()?, cast_to, round),
1200            FloatTy::F128 => float_to_int_inner(self, src.to_scalar().to_f128()?, cast_to, round),
1201        };
1202
1203        if status.intersects(
1204            rustc_apfloat::Status::INVALID_OP
1205                | rustc_apfloat::Status::OVERFLOW
1206                | rustc_apfloat::Status::UNDERFLOW,
1207        ) {
1208            // Floating point value is NaN (flagged with INVALID_OP) or outside the range
1209            // of values of the integer type (flagged with OVERFLOW or UNDERFLOW).
1210            interp_ok(None)
1211        } else {
1212            // Floating point value can be represented by the integer type after rounding.
1213            // The INEXACT flag is ignored on purpose to allow rounding.
1214            interp_ok(Some(ImmTy::from_scalar(val, cast_to)))
1215        }
1216    }
1217}