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
5use std::assert_matches::assert_matches;
6
7use rustc_abi::Size;
8use rustc_apfloat::ieee::{Double, Half, Quad, Single};
9use rustc_hir::def_id::DefId;
10use rustc_middle::mir::{self, BinOp, ConstValue, NonDivergingIntrinsic};
11use rustc_middle::ty::layout::{LayoutOf as _, TyAndLayout, ValidityRequirement};
12use rustc_middle::ty::{GenericArgsRef, Ty, TyCtxt};
13use rustc_middle::{bug, ty};
14use rustc_span::{Symbol, sym};
15use tracing::trace;
16
17use super::memory::MemoryKind;
18use super::util::ensure_monomorphic_enough;
19use super::{
20    Allocation, CheckInAllocMsg, ConstAllocation, GlobalId, ImmTy, InterpCx, InterpResult,
21    MPlaceTy, Machine, OpTy, Pointer, PointerArithmetic, Provenance, Scalar, err_inval,
22    err_ub_custom, err_unsup_format, interp_ok, throw_inval, throw_ub_custom, throw_ub_format,
23};
24use crate::fluent_generated as fluent;
25
26/// Directly returns an `Allocation` containing an absolute path representation of the given type.
27pub(crate) fn alloc_type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ConstAllocation<'tcx> {
28    let path = crate::util::type_name(tcx, ty);
29    let alloc = Allocation::from_bytes_byte_aligned_immutable(path.into_bytes());
30    tcx.mk_const_alloc(alloc)
31}
32
33/// The logic for all nullary intrinsics is implemented here. These intrinsics don't get evaluated
34/// inside an `InterpCx` and instead have their value computed directly from rustc internal info.
35pub(crate) fn eval_nullary_intrinsic<'tcx>(
36    tcx: TyCtxt<'tcx>,
37    typing_env: ty::TypingEnv<'tcx>,
38    def_id: DefId,
39    args: GenericArgsRef<'tcx>,
40) -> InterpResult<'tcx, ConstValue<'tcx>> {
41    let tp_ty = args.type_at(0);
42    let name = tcx.item_name(def_id);
43    interp_ok(match name {
44        sym::type_name => {
45            ensure_monomorphic_enough(tcx, tp_ty)?;
46            let alloc = alloc_type_name(tcx, tp_ty);
47            ConstValue::Slice { data: alloc, meta: alloc.inner().size().bytes() }
48        }
49        sym::needs_drop => {
50            ensure_monomorphic_enough(tcx, tp_ty)?;
51            ConstValue::from_bool(tp_ty.needs_drop(tcx, typing_env))
52        }
53        sym::pref_align_of => {
54            // Correctly handles non-monomorphic calls, so there is no need for ensure_monomorphic_enough.
55            let layout = tcx
56                .layout_of(typing_env.as_query_input(tp_ty))
57                .map_err(|e| err_inval!(Layout(*e)))?;
58            ConstValue::from_target_usize(layout.align.pref.bytes(), &tcx)
59        }
60        sym::type_id => {
61            ensure_monomorphic_enough(tcx, tp_ty)?;
62            ConstValue::from_u128(tcx.type_id_hash(tp_ty).as_u128())
63        }
64        sym::variant_count => match tp_ty.kind() {
65            // Correctly handles non-monomorphic calls, so there is no need for ensure_monomorphic_enough.
66            ty::Adt(adt, _) => ConstValue::from_target_usize(adt.variants().len() as u64, &tcx),
67            ty::Alias(..) | ty::Param(_) | ty::Placeholder(_) | ty::Infer(_) => {
68                throw_inval!(TooGeneric)
69            }
70            ty::Pat(_, pat) => match **pat {
71                ty::PatternKind::Range { .. } => ConstValue::from_target_usize(0u64, &tcx),
72                // Future pattern kinds may have more variants
73            },
74            ty::Bound(_, _) => bug!("bound ty during ctfe"),
75            ty::Bool
76            | ty::Char
77            | ty::Int(_)
78            | ty::Uint(_)
79            | ty::Float(_)
80            | ty::Foreign(_)
81            | ty::Str
82            | ty::Array(_, _)
83            | ty::Slice(_)
84            | ty::RawPtr(_, _)
85            | ty::Ref(_, _, _)
86            | ty::FnDef(_, _)
87            | ty::FnPtr(..)
88            | ty::Dynamic(_, _, _)
89            | ty::Closure(_, _)
90            | ty::CoroutineClosure(_, _)
91            | ty::Coroutine(_, _)
92            | ty::CoroutineWitness(..)
93            | ty::UnsafeBinder(_)
94            | ty::Never
95            | ty::Tuple(_)
96            | ty::Error(_) => ConstValue::from_target_usize(0u64, &tcx),
97        },
98        other => bug!("`{}` is not a zero arg intrinsic", other),
99    })
100}
101
102impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
103    /// Returns `true` if emulation happened.
104    /// Here we implement the intrinsics that are common to all Miri instances; individual machines can add their own
105    /// intrinsic handling.
106    pub fn eval_intrinsic(
107        &mut self,
108        instance: ty::Instance<'tcx>,
109        args: &[OpTy<'tcx, M::Provenance>],
110        dest: &MPlaceTy<'tcx, M::Provenance>,
111        ret: Option<mir::BasicBlock>,
112    ) -> InterpResult<'tcx, bool> {
113        let instance_args = instance.args;
114        let intrinsic_name = self.tcx.item_name(instance.def_id());
115
116        match intrinsic_name {
117            sym::caller_location => {
118                let span = self.find_closest_untracked_caller_location();
119                let val = self.tcx.span_as_caller_location(span);
120                let val =
121                    self.const_val_to_op(val, self.tcx.caller_location_ty(), Some(dest.layout))?;
122                self.copy_op(&val, dest)?;
123            }
124
125            sym::min_align_of_val | sym::size_of_val => {
126                // Avoid `deref_pointer` -- this is not a deref, the ptr does not have to be
127                // dereferenceable!
128                let place = self.ref_to_mplace(&self.read_immediate(&args[0])?)?;
129                let (size, align) = self
130                    .size_and_align_of_mplace(&place)?
131                    .ok_or_else(|| err_unsup_format!("`extern type` does not have known layout"))?;
132
133                let result = match intrinsic_name {
134                    sym::min_align_of_val => align.bytes(),
135                    sym::size_of_val => size.bytes(),
136                    _ => bug!(),
137                };
138
139                self.write_scalar(Scalar::from_target_usize(result, self), dest)?;
140            }
141
142            sym::pref_align_of
143            | sym::needs_drop
144            | sym::type_id
145            | sym::type_name
146            | sym::variant_count => {
147                let gid = GlobalId { instance, promoted: None };
148                let ty = match intrinsic_name {
149                    sym::pref_align_of | sym::variant_count => self.tcx.types.usize,
150                    sym::needs_drop => self.tcx.types.bool,
151                    sym::type_id => self.tcx.types.u128,
152                    sym::type_name => Ty::new_static_str(self.tcx.tcx),
153                    _ => bug!(),
154                };
155                let val = self
156                    .ctfe_query(|tcx| tcx.const_eval_global_id(self.typing_env, gid, tcx.span))?;
157                let val = self.const_val_to_op(val, ty, Some(dest.layout))?;
158                self.copy_op(&val, dest)?;
159            }
160
161            sym::ctpop
162            | sym::cttz
163            | sym::cttz_nonzero
164            | sym::ctlz
165            | sym::ctlz_nonzero
166            | sym::bswap
167            | sym::bitreverse => {
168                let ty = instance_args.type_at(0);
169                let layout = self.layout_of(ty)?;
170                let val = self.read_scalar(&args[0])?;
171
172                let out_val = self.numeric_intrinsic(intrinsic_name, val, layout, dest.layout)?;
173                self.write_scalar(out_val, dest)?;
174            }
175            sym::saturating_add | sym::saturating_sub => {
176                let l = self.read_immediate(&args[0])?;
177                let r = self.read_immediate(&args[1])?;
178                let val = self.saturating_arith(
179                    if intrinsic_name == sym::saturating_add { BinOp::Add } else { BinOp::Sub },
180                    &l,
181                    &r,
182                )?;
183                self.write_scalar(val, dest)?;
184            }
185            sym::discriminant_value => {
186                let place = self.deref_pointer(&args[0])?;
187                let variant = self.read_discriminant(&place)?;
188                let discr = self.discriminant_for_variant(place.layout.ty, variant)?;
189                self.write_immediate(*discr, dest)?;
190            }
191            sym::exact_div => {
192                let l = self.read_immediate(&args[0])?;
193                let r = self.read_immediate(&args[1])?;
194                self.exact_div(&l, &r, dest)?;
195            }
196            sym::rotate_left | sym::rotate_right => {
197                // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
198                // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
199                let layout_val = self.layout_of(instance_args.type_at(0))?;
200                let val = self.read_scalar(&args[0])?;
201                let val_bits = val.to_bits(layout_val.size)?; // sign is ignored here
202
203                let layout_raw_shift = self.layout_of(self.tcx.types.u32)?;
204                let raw_shift = self.read_scalar(&args[1])?;
205                let raw_shift_bits = raw_shift.to_bits(layout_raw_shift.size)?;
206
207                let width_bits = u128::from(layout_val.size.bits());
208                let shift_bits = raw_shift_bits % width_bits;
209                let inv_shift_bits = (width_bits - shift_bits) % width_bits;
210                let result_bits = if intrinsic_name == sym::rotate_left {
211                    (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
212                } else {
213                    (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
214                };
215                let truncated_bits = layout_val.size.truncate(result_bits);
216                let result = Scalar::from_uint(truncated_bits, layout_val.size);
217                self.write_scalar(result, dest)?;
218            }
219            sym::copy => {
220                self.copy_intrinsic(&args[0], &args[1], &args[2], /*nonoverlapping*/ false)?;
221            }
222            sym::write_bytes => {
223                self.write_bytes_intrinsic(&args[0], &args[1], &args[2], "write_bytes")?;
224            }
225            sym::compare_bytes => {
226                let result = self.compare_bytes_intrinsic(&args[0], &args[1], &args[2])?;
227                self.write_scalar(result, dest)?;
228            }
229            sym::arith_offset => {
230                let ptr = self.read_pointer(&args[0])?;
231                let offset_count = self.read_target_isize(&args[1])?;
232                let pointee_ty = instance_args.type_at(0);
233
234                let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
235                let offset_bytes = offset_count.wrapping_mul(pointee_size);
236                let offset_ptr = ptr.wrapping_signed_offset(offset_bytes, self);
237                self.write_pointer(offset_ptr, dest)?;
238            }
239            sym::ptr_offset_from | sym::ptr_offset_from_unsigned => {
240                let a = self.read_pointer(&args[0])?;
241                let b = self.read_pointer(&args[1])?;
242
243                let usize_layout = self.layout_of(self.tcx.types.usize)?;
244                let isize_layout = self.layout_of(self.tcx.types.isize)?;
245
246                // Get offsets for both that are at least relative to the same base.
247                // With `OFFSET_IS_ADDR` this is trivial; without it we need either
248                // two integers or two pointers into the same allocation.
249                let (a_offset, b_offset, is_addr) = if M::Provenance::OFFSET_IS_ADDR {
250                    (a.addr().bytes(), b.addr().bytes(), /*is_addr*/ true)
251                } else {
252                    match (self.ptr_try_get_alloc_id(a, 0), self.ptr_try_get_alloc_id(b, 0)) {
253                        (Err(a), Err(b)) => {
254                            // Neither pointer points to an allocation, so they are both absolute.
255                            (a, b, /*is_addr*/ true)
256                        }
257                        (Ok((a_alloc_id, a_offset, _)), Ok((b_alloc_id, b_offset, _)))
258                            if a_alloc_id == b_alloc_id =>
259                        {
260                            // Found allocation for both, and it's the same.
261                            // Use these offsets for distance calculation.
262                            (a_offset.bytes(), b_offset.bytes(), /*is_addr*/ false)
263                        }
264                        _ => {
265                            // Not into the same allocation -- this is UB.
266                            throw_ub_custom!(
267                                fluent::const_eval_offset_from_different_allocations,
268                                name = intrinsic_name,
269                            );
270                        }
271                    }
272                };
273
274                // Compute distance: a - b.
275                let dist = {
276                    // Addresses are unsigned, so this is a `usize` computation. We have to do the
277                    // overflow check separately anyway.
278                    let (val, overflowed) = {
279                        let a_offset = ImmTy::from_uint(a_offset, usize_layout);
280                        let b_offset = ImmTy::from_uint(b_offset, usize_layout);
281                        self.binary_op(BinOp::SubWithOverflow, &a_offset, &b_offset)?
282                            .to_scalar_pair()
283                    };
284                    if overflowed.to_bool()? {
285                        // a < b
286                        if intrinsic_name == sym::ptr_offset_from_unsigned {
287                            throw_ub_custom!(
288                                fluent::const_eval_offset_from_unsigned_overflow,
289                                a_offset = a_offset,
290                                b_offset = b_offset,
291                                is_addr = is_addr,
292                            );
293                        }
294                        // The signed form of the intrinsic allows this. If we interpret the
295                        // difference as isize, we'll get the proper signed difference. If that
296                        // seems *positive* or equal to isize::MIN, they were more than isize::MAX apart.
297                        let dist = val.to_target_isize(self)?;
298                        if dist >= 0 || i128::from(dist) == self.pointer_size().signed_int_min() {
299                            throw_ub_custom!(
300                                fluent::const_eval_offset_from_underflow,
301                                name = intrinsic_name,
302                            );
303                        }
304                        dist
305                    } else {
306                        // b >= a
307                        let dist = val.to_target_isize(self)?;
308                        // If converting to isize produced a *negative* result, we had an overflow
309                        // because they were more than isize::MAX apart.
310                        if dist < 0 {
311                            throw_ub_custom!(
312                                fluent::const_eval_offset_from_overflow,
313                                name = intrinsic_name,
314                            );
315                        }
316                        dist
317                    }
318                };
319
320                // Check that the memory between them is dereferenceable at all, starting from the
321                // origin pointer: `dist` is `a - b`, so it is based on `b`.
322                self.check_ptr_access_signed(b, dist, CheckInAllocMsg::OffsetFromTest)
323                    .map_err_kind(|_| {
324                        // This could mean they point to different allocations, or they point to the same allocation
325                        // but not the entire range between the pointers is in-bounds.
326                        if let Ok((a_alloc_id, ..)) = self.ptr_try_get_alloc_id(a, 0)
327                            && let Ok((b_alloc_id, ..)) = self.ptr_try_get_alloc_id(b, 0)
328                            && a_alloc_id == b_alloc_id
329                        {
330                            err_ub_custom!(
331                                fluent::const_eval_offset_from_out_of_bounds,
332                                name = intrinsic_name,
333                            )
334                        } else {
335                            err_ub_custom!(
336                                fluent::const_eval_offset_from_different_allocations,
337                                name = intrinsic_name,
338                            )
339                        }
340                    })?;
341                // Then check that this is also dereferenceable from `a`. This ensures that they are
342                // derived from the same allocation.
343                self.check_ptr_access_signed(
344                    a,
345                    dist.checked_neg().unwrap(), // i64::MIN is impossible as no allocation can be that large
346                    CheckInAllocMsg::OffsetFromTest,
347                )
348                .map_err_kind(|_| {
349                    // Make the error more specific.
350                    err_ub_custom!(
351                        fluent::const_eval_offset_from_different_allocations,
352                        name = intrinsic_name,
353                    )
354                })?;
355
356                // Perform division by size to compute return value.
357                let ret_layout = if intrinsic_name == sym::ptr_offset_from_unsigned {
358                    assert!(0 <= dist && dist <= self.target_isize_max());
359                    usize_layout
360                } else {
361                    assert!(self.target_isize_min() <= dist && dist <= self.target_isize_max());
362                    isize_layout
363                };
364                let pointee_layout = self.layout_of(instance_args.type_at(0))?;
365                // If ret_layout is unsigned, we checked that so is the distance, so we are good.
366                let val = ImmTy::from_int(dist, ret_layout);
367                let size = ImmTy::from_int(pointee_layout.size.bytes(), ret_layout);
368                self.exact_div(&val, &size, dest)?;
369            }
370
371            sym::assert_inhabited
372            | sym::assert_zero_valid
373            | sym::assert_mem_uninitialized_valid => {
374                let ty = instance.args.type_at(0);
375                let requirement = ValidityRequirement::from_intrinsic(intrinsic_name).unwrap();
376
377                let should_panic = !self
378                    .tcx
379                    .check_validity_requirement((requirement, self.typing_env.as_query_input(ty)))
380                    .map_err(|_| err_inval!(TooGeneric))?;
381
382                if should_panic {
383                    let layout = self.layout_of(ty)?;
384
385                    let msg = match requirement {
386                        // For *all* intrinsics we first check `is_uninhabited` to give a more specific
387                        // error message.
388                        _ if layout.is_uninhabited() => format!(
389                            "aborted execution: attempted to instantiate uninhabited type `{ty}`"
390                        ),
391                        ValidityRequirement::Inhabited => bug!("handled earlier"),
392                        ValidityRequirement::Zero => format!(
393                            "aborted execution: attempted to zero-initialize type `{ty}`, which is invalid"
394                        ),
395                        ValidityRequirement::UninitMitigated0x01Fill => format!(
396                            "aborted execution: attempted to leave type `{ty}` uninitialized, which is invalid"
397                        ),
398                        ValidityRequirement::Uninit => bug!("assert_uninit_valid doesn't exist"),
399                    };
400
401                    M::panic_nounwind(self, &msg)?;
402                    // Skip the `return_to_block` at the end (we panicked, we do not return).
403                    return interp_ok(true);
404                }
405            }
406            sym::simd_insert => {
407                let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
408                let elem = &args[2];
409                let (input, input_len) = self.project_to_simd(&args[0])?;
410                let (dest, dest_len) = self.project_to_simd(dest)?;
411                assert_eq!(input_len, dest_len, "Return vector length must match input length");
412                // Bounds are not checked by typeck so we have to do it ourselves.
413                if index >= input_len {
414                    throw_ub_format!(
415                        "`simd_insert` index {index} is out-of-bounds of vector with length {input_len}"
416                    );
417                }
418
419                for i in 0..dest_len {
420                    let place = self.project_index(&dest, i)?;
421                    let value =
422                        if i == index { elem.clone() } else { self.project_index(&input, i)? };
423                    self.copy_op(&value, &place)?;
424                }
425            }
426            sym::simd_extract => {
427                let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
428                let (input, input_len) = self.project_to_simd(&args[0])?;
429                // Bounds are not checked by typeck so we have to do it ourselves.
430                if index >= input_len {
431                    throw_ub_format!(
432                        "`simd_extract` index {index} is out-of-bounds of vector with length {input_len}"
433                    );
434                }
435                self.copy_op(&self.project_index(&input, index)?, dest)?;
436            }
437            sym::black_box => {
438                // These just return their argument
439                self.copy_op(&args[0], dest)?;
440            }
441            sym::raw_eq => {
442                let result = self.raw_eq_intrinsic(&args[0], &args[1])?;
443                self.write_scalar(result, dest)?;
444            }
445            sym::typed_swap_nonoverlapping => {
446                self.typed_swap_nonoverlapping_intrinsic(&args[0], &args[1])?;
447            }
448
449            sym::vtable_size => {
450                let ptr = self.read_pointer(&args[0])?;
451                // `None` because we don't know which trait to expect here; any vtable is okay.
452                let (size, _align) = self.get_vtable_size_and_align(ptr, None)?;
453                self.write_scalar(Scalar::from_target_usize(size.bytes(), self), dest)?;
454            }
455            sym::vtable_align => {
456                let ptr = self.read_pointer(&args[0])?;
457                // `None` because we don't know which trait to expect here; any vtable is okay.
458                let (_size, align) = self.get_vtable_size_and_align(ptr, None)?;
459                self.write_scalar(Scalar::from_target_usize(align.bytes(), self), dest)?;
460            }
461
462            sym::minnumf16 => self.float_min_intrinsic::<Half>(args, dest)?,
463            sym::minnumf32 => self.float_min_intrinsic::<Single>(args, dest)?,
464            sym::minnumf64 => self.float_min_intrinsic::<Double>(args, dest)?,
465            sym::minnumf128 => self.float_min_intrinsic::<Quad>(args, dest)?,
466
467            sym::maxnumf16 => self.float_max_intrinsic::<Half>(args, dest)?,
468            sym::maxnumf32 => self.float_max_intrinsic::<Single>(args, dest)?,
469            sym::maxnumf64 => self.float_max_intrinsic::<Double>(args, dest)?,
470            sym::maxnumf128 => self.float_max_intrinsic::<Quad>(args, dest)?,
471
472            sym::copysignf16 => self.float_copysign_intrinsic::<Half>(args, dest)?,
473            sym::copysignf32 => self.float_copysign_intrinsic::<Single>(args, dest)?,
474            sym::copysignf64 => self.float_copysign_intrinsic::<Double>(args, dest)?,
475            sym::copysignf128 => self.float_copysign_intrinsic::<Quad>(args, dest)?,
476
477            sym::fabsf16 => self.float_abs_intrinsic::<Half>(args, dest)?,
478            sym::fabsf32 => self.float_abs_intrinsic::<Single>(args, dest)?,
479            sym::fabsf64 => self.float_abs_intrinsic::<Double>(args, dest)?,
480            sym::fabsf128 => self.float_abs_intrinsic::<Quad>(args, dest)?,
481
482            // Unsupported intrinsic: skip the return_to_block below.
483            _ => return interp_ok(false),
484        }
485
486        trace!("{:?}", self.dump_place(&dest.clone().into()));
487        self.return_to_block(ret)?;
488        interp_ok(true)
489    }
490
491    pub(super) fn eval_nondiverging_intrinsic(
492        &mut self,
493        intrinsic: &NonDivergingIntrinsic<'tcx>,
494    ) -> InterpResult<'tcx> {
495        match intrinsic {
496            NonDivergingIntrinsic::Assume(op) => {
497                let op = self.eval_operand(op, None)?;
498                let cond = self.read_scalar(&op)?.to_bool()?;
499                if !cond {
500                    throw_ub_custom!(fluent::const_eval_assume_false);
501                }
502                interp_ok(())
503            }
504            NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
505                count,
506                src,
507                dst,
508            }) => {
509                let src = self.eval_operand(src, None)?;
510                let dst = self.eval_operand(dst, None)?;
511                let count = self.eval_operand(count, None)?;
512                self.copy_intrinsic(&src, &dst, &count, /* nonoverlapping */ true)
513            }
514        }
515    }
516
517    pub fn numeric_intrinsic(
518        &self,
519        name: Symbol,
520        val: Scalar<M::Provenance>,
521        layout: TyAndLayout<'tcx>,
522        ret_layout: TyAndLayout<'tcx>,
523    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
524        assert!(layout.ty.is_integral(), "invalid type for numeric intrinsic: {}", layout.ty);
525        let bits = val.to_bits(layout.size)?; // these operations all ignore the sign
526        let extra = 128 - u128::from(layout.size.bits());
527        let bits_out = match name {
528            sym::ctpop => u128::from(bits.count_ones()),
529            sym::ctlz_nonzero | sym::cttz_nonzero if bits == 0 => {
530                throw_ub_custom!(fluent::const_eval_call_nonzero_intrinsic, name = name,);
531            }
532            sym::ctlz | sym::ctlz_nonzero => u128::from(bits.leading_zeros()) - extra,
533            sym::cttz | sym::cttz_nonzero => u128::from((bits << extra).trailing_zeros()) - extra,
534            sym::bswap => {
535                assert_eq!(layout, ret_layout);
536                (bits << extra).swap_bytes()
537            }
538            sym::bitreverse => {
539                assert_eq!(layout, ret_layout);
540                (bits << extra).reverse_bits()
541            }
542            _ => bug!("not a numeric intrinsic: {}", name),
543        };
544        interp_ok(Scalar::from_uint(bits_out, ret_layout.size))
545    }
546
547    pub fn exact_div(
548        &mut self,
549        a: &ImmTy<'tcx, M::Provenance>,
550        b: &ImmTy<'tcx, M::Provenance>,
551        dest: &MPlaceTy<'tcx, M::Provenance>,
552    ) -> InterpResult<'tcx> {
553        assert_eq!(a.layout.ty, b.layout.ty);
554        assert_matches!(a.layout.ty.kind(), ty::Int(..) | ty::Uint(..));
555
556        // Performs an exact division, resulting in undefined behavior where
557        // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
558        // First, check x % y != 0 (or if that computation overflows).
559        let rem = self.binary_op(BinOp::Rem, a, b)?;
560        // sign does not matter for 0 test, so `to_bits` is fine
561        if rem.to_scalar().to_bits(a.layout.size)? != 0 {
562            throw_ub_custom!(
563                fluent::const_eval_exact_div_has_remainder,
564                a = format!("{a}"),
565                b = format!("{b}")
566            )
567        }
568        // `Rem` says this is all right, so we can let `Div` do its job.
569        let res = self.binary_op(BinOp::Div, a, b)?;
570        self.write_immediate(*res, dest)
571    }
572
573    pub fn saturating_arith(
574        &self,
575        mir_op: BinOp,
576        l: &ImmTy<'tcx, M::Provenance>,
577        r: &ImmTy<'tcx, M::Provenance>,
578    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
579        assert_eq!(l.layout.ty, r.layout.ty);
580        assert_matches!(l.layout.ty.kind(), ty::Int(..) | ty::Uint(..));
581        assert_matches!(mir_op, BinOp::Add | BinOp::Sub);
582
583        let (val, overflowed) =
584            self.binary_op(mir_op.wrapping_to_overflowing().unwrap(), l, r)?.to_scalar_pair();
585        interp_ok(if overflowed.to_bool()? {
586            let size = l.layout.size;
587            if l.layout.backend_repr.is_signed() {
588                // For signed ints the saturated value depends on the sign of the first
589                // term since the sign of the second term can be inferred from this and
590                // the fact that the operation has overflowed (if either is 0 no
591                // overflow can occur)
592                let first_term: i128 = l.to_scalar().to_int(l.layout.size)?;
593                if first_term >= 0 {
594                    // Negative overflow not possible since the positive first term
595                    // can only increase an (in range) negative term for addition
596                    // or corresponding negated positive term for subtraction.
597                    Scalar::from_int(size.signed_int_max(), size)
598                } else {
599                    // Positive overflow not possible for similar reason.
600                    Scalar::from_int(size.signed_int_min(), size)
601                }
602            } else {
603                // unsigned
604                if matches!(mir_op, BinOp::Add) {
605                    // max unsigned
606                    Scalar::from_uint(size.unsigned_int_max(), size)
607                } else {
608                    // underflow to 0
609                    Scalar::from_uint(0u128, size)
610                }
611            }
612        } else {
613            val
614        })
615    }
616
617    /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
618    /// allocation.
619    pub fn ptr_offset_inbounds(
620        &self,
621        ptr: Pointer<Option<M::Provenance>>,
622        offset_bytes: i64,
623    ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
624        // The offset must be in bounds starting from `ptr`.
625        self.check_ptr_access_signed(ptr, offset_bytes, CheckInAllocMsg::PointerArithmeticTest)?;
626        // This also implies that there is no overflow, so we are done.
627        interp_ok(ptr.wrapping_signed_offset(offset_bytes, self))
628    }
629
630    /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.
631    pub(crate) fn copy_intrinsic(
632        &mut self,
633        src: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
634        dst: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
635        count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
636        nonoverlapping: bool,
637    ) -> InterpResult<'tcx> {
638        let count = self.read_target_usize(count)?;
639        let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap())?;
640        let (size, align) = (layout.size, layout.align.abi);
641
642        let size = self.compute_size_in_bytes(size, count).ok_or_else(|| {
643            err_ub_custom!(
644                fluent::const_eval_size_overflow,
645                name = if nonoverlapping { "copy_nonoverlapping" } else { "copy" }
646            )
647        })?;
648
649        let src = self.read_pointer(src)?;
650        let dst = self.read_pointer(dst)?;
651
652        self.check_ptr_align(src, align)?;
653        self.check_ptr_align(dst, align)?;
654
655        self.mem_copy(src, dst, size, nonoverlapping)
656    }
657
658    /// Does a *typed* swap of `*left` and `*right`.
659    fn typed_swap_nonoverlapping_intrinsic(
660        &mut self,
661        left: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
662        right: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
663    ) -> InterpResult<'tcx> {
664        let left = self.deref_pointer(left)?;
665        let right = self.deref_pointer(right)?;
666        assert_eq!(left.layout, right.layout);
667        assert!(left.layout.is_sized());
668        let kind = MemoryKind::Stack;
669        let temp = self.allocate(left.layout, kind)?;
670        self.copy_op(&left, &temp)?; // checks alignment of `left`
671
672        // We want to always enforce non-overlapping, even if this is a scalar type.
673        // Therefore we directly use the underlying `mem_copy` here.
674        self.mem_copy(right.ptr(), left.ptr(), left.layout.size, /*nonoverlapping*/ true)?;
675        // This means we also need to do the validation of the value that used to be in `right`
676        // ourselves. This value is now in `left.` The one that started out in `left` already got
677        // validated by the copy above.
678        if M::enforce_validity(self, left.layout) {
679            self.validate_operand(
680                &left.clone().into(),
681                M::enforce_validity_recursively(self, left.layout),
682                /*reset_provenance_and_padding*/ true,
683            )?;
684        }
685
686        self.copy_op(&temp, &right)?; // checks alignment of `right`
687
688        self.deallocate_ptr(temp.ptr(), None, kind)?;
689        interp_ok(())
690    }
691
692    pub fn write_bytes_intrinsic(
693        &mut self,
694        dst: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
695        byte: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
696        count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
697        name: &'static str,
698    ) -> InterpResult<'tcx> {
699        let layout = self.layout_of(dst.layout.ty.builtin_deref(true).unwrap())?;
700
701        let dst = self.read_pointer(dst)?;
702        let byte = self.read_scalar(byte)?.to_u8()?;
703        let count = self.read_target_usize(count)?;
704
705        // `checked_mul` enforces a too small bound (the correct one would probably be target_isize_max),
706        // but no actual allocation can be big enough for the difference to be noticeable.
707        let len = self
708            .compute_size_in_bytes(layout.size, count)
709            .ok_or_else(|| err_ub_custom!(fluent::const_eval_size_overflow, name = name))?;
710
711        let bytes = std::iter::repeat(byte).take(len.bytes_usize());
712        self.write_bytes_ptr(dst, bytes)
713    }
714
715    pub(crate) fn compare_bytes_intrinsic(
716        &mut self,
717        left: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
718        right: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
719        byte_count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
720    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
721        let left = self.read_pointer(left)?;
722        let right = self.read_pointer(right)?;
723        let n = Size::from_bytes(self.read_target_usize(byte_count)?);
724
725        let left_bytes = self.read_bytes_ptr_strip_provenance(left, n)?;
726        let right_bytes = self.read_bytes_ptr_strip_provenance(right, n)?;
727
728        // `Ordering`'s discriminants are -1/0/+1, so casting does the right thing.
729        let result = Ord::cmp(left_bytes, right_bytes) as i32;
730        interp_ok(Scalar::from_i32(result))
731    }
732
733    pub(crate) fn raw_eq_intrinsic(
734        &mut self,
735        lhs: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
736        rhs: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
737    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
738        let layout = self.layout_of(lhs.layout.ty.builtin_deref(true).unwrap())?;
739        assert!(layout.is_sized());
740
741        let get_bytes = |this: &InterpCx<'tcx, M>,
742                         op: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>|
743         -> InterpResult<'tcx, &[u8]> {
744            let ptr = this.read_pointer(op)?;
745            this.check_ptr_align(ptr, layout.align.abi)?;
746            let Some(alloc_ref) = self.get_ptr_alloc(ptr, layout.size)? else {
747                // zero-sized access
748                return interp_ok(&[]);
749            };
750            alloc_ref.get_bytes_strip_provenance()
751        };
752
753        let lhs_bytes = get_bytes(self, lhs)?;
754        let rhs_bytes = get_bytes(self, rhs)?;
755        interp_ok(Scalar::from_bool(lhs_bytes == rhs_bytes))
756    }
757
758    fn float_min_intrinsic<F>(
759        &mut self,
760        args: &[OpTy<'tcx, M::Provenance>],
761        dest: &MPlaceTy<'tcx, M::Provenance>,
762    ) -> InterpResult<'tcx, ()>
763    where
764        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
765    {
766        let a: F = self.read_scalar(&args[0])?.to_float()?;
767        let b: F = self.read_scalar(&args[1])?.to_float()?;
768        let res = if a == b {
769            // They are definitely not NaN (those are never equal), but they could be `+0` and `-0`.
770            // Let the machine decide which one to return.
771            M::equal_float_min_max(self, a, b)
772        } else {
773            self.adjust_nan(a.min(b), &[a, b])
774        };
775        self.write_scalar(res, dest)?;
776        interp_ok(())
777    }
778
779    fn float_max_intrinsic<F>(
780        &mut self,
781        args: &[OpTy<'tcx, M::Provenance>],
782        dest: &MPlaceTy<'tcx, M::Provenance>,
783    ) -> InterpResult<'tcx, ()>
784    where
785        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
786    {
787        let a: F = self.read_scalar(&args[0])?.to_float()?;
788        let b: F = self.read_scalar(&args[1])?.to_float()?;
789        let res = if a == b {
790            // They are definitely not NaN (those are never equal), but they could be `+0` and `-0`.
791            // Let the machine decide which one to return.
792            M::equal_float_min_max(self, a, b)
793        } else {
794            self.adjust_nan(a.max(b), &[a, b])
795        };
796        self.write_scalar(res, dest)?;
797        interp_ok(())
798    }
799
800    fn float_copysign_intrinsic<F>(
801        &mut self,
802        args: &[OpTy<'tcx, M::Provenance>],
803        dest: &MPlaceTy<'tcx, M::Provenance>,
804    ) -> InterpResult<'tcx, ()>
805    where
806        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
807    {
808        let a: F = self.read_scalar(&args[0])?.to_float()?;
809        let b: F = self.read_scalar(&args[1])?.to_float()?;
810        // bitwise, no NaN adjustments
811        self.write_scalar(a.copy_sign(b), dest)?;
812        interp_ok(())
813    }
814
815    fn float_abs_intrinsic<F>(
816        &mut self,
817        args: &[OpTy<'tcx, M::Provenance>],
818        dest: &MPlaceTy<'tcx, M::Provenance>,
819    ) -> InterpResult<'tcx, ()>
820    where
821        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
822    {
823        let x: F = self.read_scalar(&args[0])?.to_float()?;
824        // bitwise, no NaN adjustments
825        self.write_scalar(x.abs(), dest)?;
826        interp_ok(())
827    }
828}