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