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