]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/intrinsics.rs
Auto merge of #105605 - inquisitivecrystal:attr-validation, r=cjgillot
[rust.git] / compiler / rustc_const_eval / src / interpret / intrinsics.rs
1 //! Intrinsics and other functions that the miri engine executes without
2 //! looking at their MIR. Intrinsics/functions supported here are shared by CTFE
3 //! and miri.
4
5 use rustc_hir::def_id::DefId;
6 use rustc_middle::mir::{
7     self,
8     interpret::{
9         Allocation, ConstAllocation, ConstValue, GlobalId, InterpResult, PointerArithmetic, Scalar,
10     },
11     BinOp, NonDivergingIntrinsic,
12 };
13 use rustc_middle::ty;
14 use rustc_middle::ty::layout::LayoutOf as _;
15 use rustc_middle::ty::subst::SubstsRef;
16 use rustc_middle::ty::{Ty, TyCtxt};
17 use rustc_span::symbol::{sym, Symbol};
18 use rustc_target::abi::{Abi, Align, Primitive, Size};
19
20 use super::{
21     util::ensure_monomorphic_enough, CheckInAllocMsg, ImmTy, InterpCx, Machine, OpTy, PlaceTy,
22     Pointer,
23 };
24
25 mod caller_location;
26
27 fn numeric_intrinsic<Prov>(name: Symbol, bits: u128, kind: Primitive) -> Scalar<Prov> {
28     let size = match kind {
29         Primitive::Int(integer, _) => integer.size(),
30         _ => bug!("invalid `{}` argument: {:?}", name, bits),
31     };
32     let extra = 128 - u128::from(size.bits());
33     let bits_out = match name {
34         sym::ctpop => u128::from(bits.count_ones()),
35         sym::ctlz => u128::from(bits.leading_zeros()) - extra,
36         sym::cttz => u128::from((bits << extra).trailing_zeros()) - extra,
37         sym::bswap => (bits << extra).swap_bytes(),
38         sym::bitreverse => (bits << extra).reverse_bits(),
39         _ => bug!("not a numeric intrinsic: {}", name),
40     };
41     Scalar::from_uint(bits_out, size)
42 }
43
44 /// Directly returns an `Allocation` containing an absolute path representation of the given type.
45 pub(crate) fn alloc_type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ConstAllocation<'tcx> {
46     let path = crate::util::type_name(tcx, ty);
47     let alloc = Allocation::from_bytes_byte_aligned_immutable(path.into_bytes());
48     tcx.intern_const_alloc(alloc)
49 }
50
51 /// The logic for all nullary intrinsics is implemented here. These intrinsics don't get evaluated
52 /// inside an `InterpCx` and instead have their value computed directly from rustc internal info.
53 pub(crate) fn eval_nullary_intrinsic<'tcx>(
54     tcx: TyCtxt<'tcx>,
55     param_env: ty::ParamEnv<'tcx>,
56     def_id: DefId,
57     substs: SubstsRef<'tcx>,
58 ) -> InterpResult<'tcx, ConstValue<'tcx>> {
59     let tp_ty = substs.type_at(0);
60     let name = tcx.item_name(def_id);
61     Ok(match name {
62         sym::type_name => {
63             ensure_monomorphic_enough(tcx, tp_ty)?;
64             let alloc = alloc_type_name(tcx, tp_ty);
65             ConstValue::Slice { data: alloc, start: 0, end: alloc.inner().len() }
66         }
67         sym::needs_drop => {
68             ensure_monomorphic_enough(tcx, tp_ty)?;
69             ConstValue::from_bool(tp_ty.needs_drop(tcx, param_env))
70         }
71         sym::pref_align_of => {
72             // Correctly handles non-monomorphic calls, so there is no need for ensure_monomorphic_enough.
73             let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
74             ConstValue::from_machine_usize(layout.align.pref.bytes(), &tcx)
75         }
76         sym::type_id => {
77             ensure_monomorphic_enough(tcx, tp_ty)?;
78             ConstValue::from_u64(tcx.type_id_hash(tp_ty))
79         }
80         sym::variant_count => match tp_ty.kind() {
81             // Correctly handles non-monomorphic calls, so there is no need for ensure_monomorphic_enough.
82             ty::Adt(ref adt, _) => {
83                 ConstValue::from_machine_usize(adt.variants().len() as u64, &tcx)
84             }
85             ty::Alias(..) | ty::Param(_) | ty::Placeholder(_) | ty::Infer(_) => {
86                 throw_inval!(TooGeneric)
87             }
88             ty::Bound(_, _) => bug!("bound ty during ctfe"),
89             ty::Bool
90             | ty::Char
91             | ty::Int(_)
92             | ty::Uint(_)
93             | ty::Float(_)
94             | ty::Foreign(_)
95             | ty::Str
96             | ty::Array(_, _)
97             | ty::Slice(_)
98             | ty::RawPtr(_)
99             | ty::Ref(_, _, _)
100             | ty::FnDef(_, _)
101             | ty::FnPtr(_)
102             | ty::Dynamic(_, _, _)
103             | ty::Closure(_, _)
104             | ty::Generator(_, _, _)
105             | ty::GeneratorWitness(_)
106             | ty::Never
107             | ty::Tuple(_)
108             | ty::Error(_) => ConstValue::from_machine_usize(0u64, &tcx),
109         },
110         other => bug!("`{}` is not a zero arg intrinsic", other),
111     })
112 }
113
114 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
115     /// Returns `true` if emulation happened.
116     /// Here we implement the intrinsics that are common to all Miri instances; individual machines can add their own
117     /// intrinsic handling.
118     pub fn emulate_intrinsic(
119         &mut self,
120         instance: ty::Instance<'tcx>,
121         args: &[OpTy<'tcx, M::Provenance>],
122         dest: &PlaceTy<'tcx, M::Provenance>,
123         ret: Option<mir::BasicBlock>,
124     ) -> InterpResult<'tcx, bool> {
125         let substs = instance.substs;
126         let intrinsic_name = self.tcx.item_name(instance.def_id());
127
128         // First handle intrinsics without return place.
129         let ret = match ret {
130             None => match intrinsic_name {
131                 sym::transmute => throw_ub_format!("transmuting to uninhabited type"),
132                 sym::abort => M::abort(self, "the program aborted execution".to_owned())?,
133                 // Unsupported diverging intrinsic.
134                 _ => return Ok(false),
135             },
136             Some(p) => p,
137         };
138
139         match intrinsic_name {
140             sym::caller_location => {
141                 let span = self.find_closest_untracked_caller_location();
142                 let location = self.alloc_caller_location_for_span(span);
143                 self.write_immediate(location.to_ref(self), dest)?;
144             }
145
146             sym::min_align_of_val | sym::size_of_val => {
147                 // Avoid `deref_operand` -- this is not a deref, the ptr does not have to be
148                 // dereferenceable!
149                 let place = self.ref_to_mplace(&self.read_immediate(&args[0])?)?;
150                 let (size, align) = self
151                     .size_and_align_of_mplace(&place)?
152                     .ok_or_else(|| err_unsup_format!("`extern type` does not have known layout"))?;
153
154                 let result = match intrinsic_name {
155                     sym::min_align_of_val => align.bytes(),
156                     sym::size_of_val => size.bytes(),
157                     _ => bug!(),
158                 };
159
160                 self.write_scalar(Scalar::from_machine_usize(result, self), dest)?;
161             }
162
163             sym::pref_align_of
164             | sym::needs_drop
165             | sym::type_id
166             | sym::type_name
167             | sym::variant_count => {
168                 let gid = GlobalId { instance, promoted: None };
169                 let ty = match intrinsic_name {
170                     sym::pref_align_of | sym::variant_count => self.tcx.types.usize,
171                     sym::needs_drop => self.tcx.types.bool,
172                     sym::type_id => self.tcx.types.u64,
173                     sym::type_name => self.tcx.mk_static_str(),
174                     _ => bug!(),
175                 };
176                 let val = self.ctfe_query(None, |tcx| {
177                     tcx.const_eval_global_id(self.param_env, gid, Some(tcx.span))
178                 })?;
179                 let val = self.const_val_to_op(val, ty, Some(dest.layout))?;
180                 self.copy_op(&val, dest, /*allow_transmute*/ false)?;
181             }
182
183             sym::ctpop
184             | sym::cttz
185             | sym::cttz_nonzero
186             | sym::ctlz
187             | sym::ctlz_nonzero
188             | sym::bswap
189             | sym::bitreverse => {
190                 let ty = substs.type_at(0);
191                 let layout_of = self.layout_of(ty)?;
192                 let val = self.read_scalar(&args[0])?;
193                 let bits = val.to_bits(layout_of.size)?;
194                 let kind = match layout_of.abi {
195                     Abi::Scalar(scalar) => scalar.primitive(),
196                     _ => span_bug!(
197                         self.cur_span(),
198                         "{} called on invalid type {:?}",
199                         intrinsic_name,
200                         ty
201                     ),
202                 };
203                 let (nonzero, intrinsic_name) = match intrinsic_name {
204                     sym::cttz_nonzero => (true, sym::cttz),
205                     sym::ctlz_nonzero => (true, sym::ctlz),
206                     other => (false, other),
207                 };
208                 if nonzero && bits == 0 {
209                     throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
210                 }
211                 let out_val = numeric_intrinsic(intrinsic_name, bits, kind);
212                 self.write_scalar(out_val, dest)?;
213             }
214             sym::add_with_overflow | sym::sub_with_overflow | sym::mul_with_overflow => {
215                 let lhs = self.read_immediate(&args[0])?;
216                 let rhs = self.read_immediate(&args[1])?;
217                 let bin_op = match intrinsic_name {
218                     sym::add_with_overflow => BinOp::Add,
219                     sym::sub_with_overflow => BinOp::Sub,
220                     sym::mul_with_overflow => BinOp::Mul,
221                     _ => bug!(),
222                 };
223                 self.binop_with_overflow(
224                     bin_op, /*force_overflow_checks*/ true, &lhs, &rhs, dest,
225                 )?;
226             }
227             sym::saturating_add | sym::saturating_sub => {
228                 let l = self.read_immediate(&args[0])?;
229                 let r = self.read_immediate(&args[1])?;
230                 let val = self.saturating_arith(
231                     if intrinsic_name == sym::saturating_add { BinOp::Add } else { BinOp::Sub },
232                     &l,
233                     &r,
234                 )?;
235                 self.write_scalar(val, dest)?;
236             }
237             sym::discriminant_value => {
238                 let place = self.deref_operand(&args[0])?;
239                 let discr_val = self.read_discriminant(&place.into())?.0;
240                 self.write_scalar(discr_val, dest)?;
241             }
242             sym::exact_div => {
243                 let l = self.read_immediate(&args[0])?;
244                 let r = self.read_immediate(&args[1])?;
245                 self.exact_div(&l, &r, dest)?;
246             }
247             sym::unchecked_shl
248             | sym::unchecked_shr
249             | sym::unchecked_add
250             | sym::unchecked_sub
251             | sym::unchecked_mul
252             | sym::unchecked_div
253             | sym::unchecked_rem => {
254                 let l = self.read_immediate(&args[0])?;
255                 let r = self.read_immediate(&args[1])?;
256                 let bin_op = match intrinsic_name {
257                     sym::unchecked_shl => BinOp::Shl,
258                     sym::unchecked_shr => BinOp::Shr,
259                     sym::unchecked_add => BinOp::Add,
260                     sym::unchecked_sub => BinOp::Sub,
261                     sym::unchecked_mul => BinOp::Mul,
262                     sym::unchecked_div => BinOp::Div,
263                     sym::unchecked_rem => BinOp::Rem,
264                     _ => bug!(),
265                 };
266                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, &l, &r)?;
267                 if overflowed {
268                     let layout = self.layout_of(substs.type_at(0))?;
269                     let r_val = r.to_scalar().to_bits(layout.size)?;
270                     if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
271                         throw_ub_format!("overflowing shift by {} in `{}`", r_val, intrinsic_name);
272                     } else {
273                         throw_ub_format!("overflow executing `{}`", intrinsic_name);
274                     }
275                 }
276                 self.write_scalar(val, dest)?;
277             }
278             sym::rotate_left | sym::rotate_right => {
279                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
280                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
281                 let layout = self.layout_of(substs.type_at(0))?;
282                 let val = self.read_scalar(&args[0])?;
283                 let val_bits = val.to_bits(layout.size)?;
284                 let raw_shift = self.read_scalar(&args[1])?;
285                 let raw_shift_bits = raw_shift.to_bits(layout.size)?;
286                 let width_bits = u128::from(layout.size.bits());
287                 let shift_bits = raw_shift_bits % width_bits;
288                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
289                 let result_bits = if intrinsic_name == sym::rotate_left {
290                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
291                 } else {
292                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
293                 };
294                 let truncated_bits = self.truncate(result_bits, layout);
295                 let result = Scalar::from_uint(truncated_bits, layout.size);
296                 self.write_scalar(result, dest)?;
297             }
298             sym::copy => {
299                 self.copy_intrinsic(&args[0], &args[1], &args[2], /*nonoverlapping*/ false)?;
300             }
301             sym::write_bytes => {
302                 self.write_bytes_intrinsic(&args[0], &args[1], &args[2])?;
303             }
304             sym::offset => {
305                 let ptr = self.read_pointer(&args[0])?;
306                 let offset_count = self.read_machine_isize(&args[1])?;
307                 let pointee_ty = substs.type_at(0);
308
309                 let offset_ptr = self.ptr_offset_inbounds(ptr, pointee_ty, offset_count)?;
310                 self.write_pointer(offset_ptr, dest)?;
311             }
312             sym::arith_offset => {
313                 let ptr = self.read_pointer(&args[0])?;
314                 let offset_count = self.read_machine_isize(&args[1])?;
315                 let pointee_ty = substs.type_at(0);
316
317                 let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
318                 let offset_bytes = offset_count.wrapping_mul(pointee_size);
319                 let offset_ptr = ptr.wrapping_signed_offset(offset_bytes, self);
320                 self.write_pointer(offset_ptr, dest)?;
321             }
322             sym::ptr_offset_from | sym::ptr_offset_from_unsigned => {
323                 let a = self.read_pointer(&args[0])?;
324                 let b = self.read_pointer(&args[1])?;
325
326                 let usize_layout = self.layout_of(self.tcx.types.usize)?;
327                 let isize_layout = self.layout_of(self.tcx.types.isize)?;
328
329                 // Get offsets for both that are at least relative to the same base.
330                 let (a_offset, b_offset) =
331                     match (self.ptr_try_get_alloc_id(a), self.ptr_try_get_alloc_id(b)) {
332                         (Err(a), Err(b)) => {
333                             // Neither pointer points to an allocation.
334                             // If these are inequal or null, this *will* fail the deref check below.
335                             (a, b)
336                         }
337                         (Err(_), _) | (_, Err(_)) => {
338                             // We managed to find a valid allocation for one pointer, but not the other.
339                             // That means they are definitely not pointing to the same allocation.
340                             throw_ub_format!(
341                                 "`{}` called on pointers into different allocations",
342                                 intrinsic_name
343                             );
344                         }
345                         (Ok((a_alloc_id, a_offset, _)), Ok((b_alloc_id, b_offset, _))) => {
346                             // Found allocation for both. They must be into the same allocation.
347                             if a_alloc_id != b_alloc_id {
348                                 throw_ub_format!(
349                                     "`{}` called on pointers into different allocations",
350                                     intrinsic_name
351                                 );
352                             }
353                             // Use these offsets for distance calculation.
354                             (a_offset.bytes(), b_offset.bytes())
355                         }
356                     };
357
358                 // Compute distance.
359                 let dist = {
360                     // Addresses are unsigned, so this is a `usize` computation. We have to do the
361                     // overflow check separately anyway.
362                     let (val, overflowed, _ty) = {
363                         let a_offset = ImmTy::from_uint(a_offset, usize_layout);
364                         let b_offset = ImmTy::from_uint(b_offset, usize_layout);
365                         self.overflowing_binary_op(BinOp::Sub, &a_offset, &b_offset)?
366                     };
367                     if overflowed {
368                         // a < b
369                         if intrinsic_name == sym::ptr_offset_from_unsigned {
370                             throw_ub_format!(
371                                 "`{}` called when first pointer has smaller offset than second: {} < {}",
372                                 intrinsic_name,
373                                 a_offset,
374                                 b_offset,
375                             );
376                         }
377                         // The signed form of the intrinsic allows this. If we interpret the
378                         // difference as isize, we'll get the proper signed difference. If that
379                         // seems *positive*, they were more than isize::MAX apart.
380                         let dist = val.to_machine_isize(self)?;
381                         if dist >= 0 {
382                             throw_ub_format!(
383                                 "`{}` called when first pointer is too far before second",
384                                 intrinsic_name
385                             );
386                         }
387                         dist
388                     } else {
389                         // b >= a
390                         let dist = val.to_machine_isize(self)?;
391                         // If converting to isize produced a *negative* result, we had an overflow
392                         // because they were more than isize::MAX apart.
393                         if dist < 0 {
394                             throw_ub_format!(
395                                 "`{}` called when first pointer is too far ahead of second",
396                                 intrinsic_name
397                             );
398                         }
399                         dist
400                     }
401                 };
402
403                 // Check that the range between them is dereferenceable ("in-bounds or one past the
404                 // end of the same allocation"). This is like the check in ptr_offset_inbounds.
405                 let min_ptr = if dist >= 0 { b } else { a };
406                 self.check_ptr_access_align(
407                     min_ptr,
408                     Size::from_bytes(dist.unsigned_abs()),
409                     Align::ONE,
410                     CheckInAllocMsg::OffsetFromTest,
411                 )?;
412
413                 // Perform division by size to compute return value.
414                 let ret_layout = if intrinsic_name == sym::ptr_offset_from_unsigned {
415                     assert!(0 <= dist && dist <= self.machine_isize_max());
416                     usize_layout
417                 } else {
418                     assert!(self.machine_isize_min() <= dist && dist <= self.machine_isize_max());
419                     isize_layout
420                 };
421                 let pointee_layout = self.layout_of(substs.type_at(0))?;
422                 // If ret_layout is unsigned, we checked that so is the distance, so we are good.
423                 let val = ImmTy::from_int(dist, ret_layout);
424                 let size = ImmTy::from_int(pointee_layout.size.bytes(), ret_layout);
425                 self.exact_div(&val, &size, dest)?;
426             }
427
428             sym::transmute => {
429                 self.copy_op(&args[0], dest, /*allow_transmute*/ true)?;
430             }
431             sym::assert_inhabited
432             | sym::assert_zero_valid
433             | sym::assert_mem_uninitialized_valid => {
434                 let ty = instance.substs.type_at(0);
435                 let layout = self.layout_of(ty)?;
436
437                 // For *all* intrinsics we first check `is_uninhabited` to give a more specific
438                 // error message.
439                 if layout.abi.is_uninhabited() {
440                     // The run-time intrinsic panics just to get a good backtrace; here we abort
441                     // since there is no problem showing a backtrace even for aborts.
442                     M::abort(
443                         self,
444                         format!(
445                             "aborted execution: attempted to instantiate uninhabited type `{}`",
446                             ty
447                         ),
448                     )?;
449                 }
450
451                 if intrinsic_name == sym::assert_zero_valid {
452                     let should_panic = !self.tcx.permits_zero_init(layout);
453
454                     if should_panic {
455                         M::abort(
456                             self,
457                             format!(
458                                 "aborted execution: attempted to zero-initialize type `{}`, which is invalid",
459                                 ty
460                             ),
461                         )?;
462                     }
463                 }
464
465                 if intrinsic_name == sym::assert_mem_uninitialized_valid {
466                     let should_panic = !self.tcx.permits_uninit_init(layout);
467
468                     if should_panic {
469                         M::abort(
470                             self,
471                             format!(
472                                 "aborted execution: attempted to leave type `{}` uninitialized, which is invalid",
473                                 ty
474                             ),
475                         )?;
476                     }
477                 }
478             }
479             sym::simd_insert => {
480                 let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
481                 let elem = &args[2];
482                 let (input, input_len) = self.operand_to_simd(&args[0])?;
483                 let (dest, dest_len) = self.place_to_simd(dest)?;
484                 assert_eq!(input_len, dest_len, "Return vector length must match input length");
485                 assert!(
486                     index < dest_len,
487                     "Index `{}` must be in bounds of vector with length {}`",
488                     index,
489                     dest_len
490                 );
491
492                 for i in 0..dest_len {
493                     let place = self.mplace_index(&dest, i)?;
494                     let value = if i == index {
495                         elem.clone()
496                     } else {
497                         self.mplace_index(&input, i)?.into()
498                     };
499                     self.copy_op(&value, &place.into(), /*allow_transmute*/ false)?;
500                 }
501             }
502             sym::simd_extract => {
503                 let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
504                 let (input, input_len) = self.operand_to_simd(&args[0])?;
505                 assert!(
506                     index < input_len,
507                     "index `{}` must be in bounds of vector with length `{}`",
508                     index,
509                     input_len
510                 );
511                 self.copy_op(
512                     &self.mplace_index(&input, index)?.into(),
513                     dest,
514                     /*allow_transmute*/ false,
515                 )?;
516             }
517             sym::likely | sym::unlikely | sym::black_box => {
518                 // These just return their argument
519                 self.copy_op(&args[0], dest, /*allow_transmute*/ false)?;
520             }
521             sym::raw_eq => {
522                 let result = self.raw_eq_intrinsic(&args[0], &args[1])?;
523                 self.write_scalar(result, dest)?;
524             }
525
526             sym::vtable_size => {
527                 let ptr = self.read_pointer(&args[0])?;
528                 let (size, _align) = self.get_vtable_size_and_align(ptr)?;
529                 self.write_scalar(Scalar::from_machine_usize(size.bytes(), self), dest)?;
530             }
531             sym::vtable_align => {
532                 let ptr = self.read_pointer(&args[0])?;
533                 let (_size, align) = self.get_vtable_size_and_align(ptr)?;
534                 self.write_scalar(Scalar::from_machine_usize(align.bytes(), self), dest)?;
535             }
536
537             _ => return Ok(false),
538         }
539
540         trace!("{:?}", self.dump_place(**dest));
541         self.go_to_block(ret);
542         Ok(true)
543     }
544
545     pub(super) fn emulate_nondiverging_intrinsic(
546         &mut self,
547         intrinsic: &NonDivergingIntrinsic<'tcx>,
548     ) -> InterpResult<'tcx> {
549         match intrinsic {
550             NonDivergingIntrinsic::Assume(op) => {
551                 let op = self.eval_operand(op, None)?;
552                 let cond = self.read_scalar(&op)?.to_bool()?;
553                 if !cond {
554                     throw_ub_format!("`assume` called with `false`");
555                 }
556                 Ok(())
557             }
558             NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
559                 count,
560                 src,
561                 dst,
562             }) => {
563                 let src = self.eval_operand(src, None)?;
564                 let dst = self.eval_operand(dst, None)?;
565                 let count = self.eval_operand(count, None)?;
566                 self.copy_intrinsic(&src, &dst, &count, /* nonoverlapping */ true)
567             }
568         }
569     }
570
571     pub fn exact_div(
572         &mut self,
573         a: &ImmTy<'tcx, M::Provenance>,
574         b: &ImmTy<'tcx, M::Provenance>,
575         dest: &PlaceTy<'tcx, M::Provenance>,
576     ) -> InterpResult<'tcx> {
577         // Performs an exact division, resulting in undefined behavior where
578         // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
579         // First, check x % y != 0 (or if that computation overflows).
580         let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, &a, &b)?;
581         assert!(!overflow); // All overflow is UB, so this should never return on overflow.
582         if res.assert_bits(a.layout.size) != 0 {
583             throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b)
584         }
585         // `Rem` says this is all right, so we can let `Div` do its job.
586         self.binop_ignore_overflow(BinOp::Div, &a, &b, dest)
587     }
588
589     pub fn saturating_arith(
590         &self,
591         mir_op: BinOp,
592         l: &ImmTy<'tcx, M::Provenance>,
593         r: &ImmTy<'tcx, M::Provenance>,
594     ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
595         assert!(matches!(mir_op, BinOp::Add | BinOp::Sub));
596         let (val, overflowed, _ty) = self.overflowing_binary_op(mir_op, l, r)?;
597         Ok(if overflowed {
598             let size = l.layout.size;
599             let num_bits = size.bits();
600             if l.layout.abi.is_signed() {
601                 // For signed ints the saturated value depends on the sign of the first
602                 // term since the sign of the second term can be inferred from this and
603                 // the fact that the operation has overflowed (if either is 0 no
604                 // overflow can occur)
605                 let first_term: u128 = l.to_scalar().to_bits(l.layout.size)?;
606                 let first_term_positive = first_term & (1 << (num_bits - 1)) == 0;
607                 if first_term_positive {
608                     // Negative overflow not possible since the positive first term
609                     // can only increase an (in range) negative term for addition
610                     // or corresponding negated positive term for subtraction
611                     Scalar::from_int(size.signed_int_max(), size)
612                 } else {
613                     // Positive overflow not possible for similar reason
614                     // max negative
615                     Scalar::from_int(size.signed_int_min(), size)
616                 }
617             } else {
618                 // unsigned
619                 if matches!(mir_op, BinOp::Add) {
620                     // max unsigned
621                     Scalar::from_uint(size.unsigned_int_max(), size)
622                 } else {
623                     // underflow to 0
624                     Scalar::from_uint(0u128, size)
625                 }
626             }
627         } else {
628             val
629         })
630     }
631
632     /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
633     /// allocation. For integer pointers, we consider each of them their own tiny allocation of size
634     /// 0, so offset-by-0 (and only 0) is okay -- except that null cannot be offset by _any_ value.
635     pub fn ptr_offset_inbounds(
636         &self,
637         ptr: Pointer<Option<M::Provenance>>,
638         pointee_ty: Ty<'tcx>,
639         offset_count: i64,
640     ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
641         // We cannot overflow i64 as a type's size must be <= isize::MAX.
642         let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
643         // The computed offset, in bytes, must not overflow an isize.
644         // `checked_mul` enforces a too small bound, but no actual allocation can be big enough for
645         // the difference to be noticeable.
646         let offset_bytes =
647             offset_count.checked_mul(pointee_size).ok_or(err_ub!(PointerArithOverflow))?;
648         // The offset being in bounds cannot rely on "wrapping around" the address space.
649         // So, first rule out overflows in the pointer arithmetic.
650         let offset_ptr = ptr.signed_offset(offset_bytes, self)?;
651         // ptr and offset_ptr must be in bounds of the same allocated object. This means all of the
652         // memory between these pointers must be accessible. Note that we do not require the
653         // pointers to be properly aligned (unlike a read/write operation).
654         let min_ptr = if offset_bytes >= 0 { ptr } else { offset_ptr };
655         // This call handles checking for integer/null pointers.
656         self.check_ptr_access_align(
657             min_ptr,
658             Size::from_bytes(offset_bytes.unsigned_abs()),
659             Align::ONE,
660             CheckInAllocMsg::PointerArithmeticTest,
661         )?;
662         Ok(offset_ptr)
663     }
664
665     /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.
666     pub(crate) fn copy_intrinsic(
667         &mut self,
668         src: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
669         dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
670         count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
671         nonoverlapping: bool,
672     ) -> InterpResult<'tcx> {
673         let count = self.read_machine_usize(&count)?;
674         let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap().ty)?;
675         let (size, align) = (layout.size, layout.align.abi);
676         // `checked_mul` enforces a too small bound (the correct one would probably be machine_isize_max),
677         // but no actual allocation can be big enough for the difference to be noticeable.
678         let size = size.checked_mul(count, self).ok_or_else(|| {
679             err_ub_format!(
680                 "overflow computing total size of `{}`",
681                 if nonoverlapping { "copy_nonoverlapping" } else { "copy" }
682             )
683         })?;
684
685         let src = self.read_pointer(&src)?;
686         let dst = self.read_pointer(&dst)?;
687
688         self.mem_copy(src, align, dst, align, size, nonoverlapping)
689     }
690
691     pub(crate) fn write_bytes_intrinsic(
692         &mut self,
693         dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
694         byte: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
695         count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
696     ) -> InterpResult<'tcx> {
697         let layout = self.layout_of(dst.layout.ty.builtin_deref(true).unwrap().ty)?;
698
699         let dst = self.read_pointer(&dst)?;
700         let byte = self.read_scalar(&byte)?.to_u8()?;
701         let count = self.read_machine_usize(&count)?;
702
703         // `checked_mul` enforces a too small bound (the correct one would probably be machine_isize_max),
704         // but no actual allocation can be big enough for the difference to be noticeable.
705         let len = layout
706             .size
707             .checked_mul(count, self)
708             .ok_or_else(|| err_ub_format!("overflow computing total size of `write_bytes`"))?;
709
710         let bytes = std::iter::repeat(byte).take(len.bytes_usize());
711         self.write_bytes_ptr(dst, bytes)
712     }
713
714     pub(crate) fn raw_eq_intrinsic(
715         &mut self,
716         lhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
717         rhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
718     ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
719         let layout = self.layout_of(lhs.layout.ty.builtin_deref(true).unwrap().ty)?;
720         assert!(layout.is_sized());
721
722         let get_bytes = |this: &InterpCx<'mir, 'tcx, M>,
723                          op: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
724                          size|
725          -> InterpResult<'tcx, &[u8]> {
726             let ptr = this.read_pointer(op)?;
727             let Some(alloc_ref) = self.get_ptr_alloc(ptr, size, Align::ONE)? else {
728                 // zero-sized access
729                 return Ok(&[]);
730             };
731             if alloc_ref.has_provenance() {
732                 throw_ub_format!("`raw_eq` on bytes with provenance");
733             }
734             alloc_ref.get_bytes_strip_provenance()
735         };
736
737         let lhs_bytes = get_bytes(self, lhs, layout.size)?;
738         let rhs_bytes = get_bytes(self, rhs, layout.size)?;
739         Ok(Scalar::from_bool(lhs_bytes == rhs_bytes))
740     }
741 }