]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/intrinsics.rs
Rollup merge of #105882 - compiler-errors:issue-105832, r=jackh726
[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_scalar(&args[1])?.to_machine_isize(self)?;
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_scalar(&args[1])?.to_machine_isize(self)?;
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 | sym::assert_zero_valid | sym::assert_uninit_valid => {
432                 let ty = instance.substs.type_at(0);
433                 let layout = self.layout_of(ty)?;
434
435                 // For *all* intrinsics we first check `is_uninhabited` to give a more specific
436                 // error message.
437                 if layout.abi.is_uninhabited() {
438                     // The run-time intrinsic panics just to get a good backtrace; here we abort
439                     // since there is no problem showing a backtrace even for aborts.
440                     M::abort(
441                         self,
442                         format!(
443                             "aborted execution: attempted to instantiate uninhabited type `{}`",
444                             ty
445                         ),
446                     )?;
447                 }
448
449                 if intrinsic_name == sym::assert_zero_valid {
450                     let should_panic = !self.tcx.permits_zero_init(layout);
451
452                     if should_panic {
453                         M::abort(
454                             self,
455                             format!(
456                                 "aborted execution: attempted to zero-initialize type `{}`, which is invalid",
457                                 ty
458                             ),
459                         )?;
460                     }
461                 }
462
463                 if intrinsic_name == sym::assert_uninit_valid {
464                     let should_panic = !self.tcx.permits_uninit_init(layout);
465
466                     if should_panic {
467                         M::abort(
468                             self,
469                             format!(
470                                 "aborted execution: attempted to leave type `{}` uninitialized, which is invalid",
471                                 ty
472                             ),
473                         )?;
474                     }
475                 }
476             }
477             sym::simd_insert => {
478                 let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
479                 let elem = &args[2];
480                 let (input, input_len) = self.operand_to_simd(&args[0])?;
481                 let (dest, dest_len) = self.place_to_simd(dest)?;
482                 assert_eq!(input_len, dest_len, "Return vector length must match input length");
483                 assert!(
484                     index < dest_len,
485                     "Index `{}` must be in bounds of vector with length {}`",
486                     index,
487                     dest_len
488                 );
489
490                 for i in 0..dest_len {
491                     let place = self.mplace_index(&dest, i)?;
492                     let value = if i == index {
493                         elem.clone()
494                     } else {
495                         self.mplace_index(&input, i)?.into()
496                     };
497                     self.copy_op(&value, &place.into(), /*allow_transmute*/ false)?;
498                 }
499             }
500             sym::simd_extract => {
501                 let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
502                 let (input, input_len) = self.operand_to_simd(&args[0])?;
503                 assert!(
504                     index < input_len,
505                     "index `{}` must be in bounds of vector with length `{}`",
506                     index,
507                     input_len
508                 );
509                 self.copy_op(
510                     &self.mplace_index(&input, index)?.into(),
511                     dest,
512                     /*allow_transmute*/ false,
513                 )?;
514             }
515             sym::likely | sym::unlikely | sym::black_box => {
516                 // These just return their argument
517                 self.copy_op(&args[0], dest, /*allow_transmute*/ false)?;
518             }
519             sym::raw_eq => {
520                 let result = self.raw_eq_intrinsic(&args[0], &args[1])?;
521                 self.write_scalar(result, dest)?;
522             }
523
524             sym::vtable_size => {
525                 let ptr = self.read_pointer(&args[0])?;
526                 let (size, _align) = self.get_vtable_size_and_align(ptr)?;
527                 self.write_scalar(Scalar::from_machine_usize(size.bytes(), self), dest)?;
528             }
529             sym::vtable_align => {
530                 let ptr = self.read_pointer(&args[0])?;
531                 let (_size, align) = self.get_vtable_size_and_align(ptr)?;
532                 self.write_scalar(Scalar::from_machine_usize(align.bytes(), self), dest)?;
533             }
534
535             _ => return Ok(false),
536         }
537
538         trace!("{:?}", self.dump_place(**dest));
539         self.go_to_block(ret);
540         Ok(true)
541     }
542
543     pub(super) fn emulate_nondiverging_intrinsic(
544         &mut self,
545         intrinsic: &NonDivergingIntrinsic<'tcx>,
546     ) -> InterpResult<'tcx> {
547         match intrinsic {
548             NonDivergingIntrinsic::Assume(op) => {
549                 let op = self.eval_operand(op, None)?;
550                 let cond = self.read_scalar(&op)?.to_bool()?;
551                 if !cond {
552                     throw_ub_format!("`assume` called with `false`");
553                 }
554                 Ok(())
555             }
556             NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
557                 count,
558                 src,
559                 dst,
560             }) => {
561                 let src = self.eval_operand(src, None)?;
562                 let dst = self.eval_operand(dst, None)?;
563                 let count = self.eval_operand(count, None)?;
564                 self.copy_intrinsic(&src, &dst, &count, /* nonoverlapping */ true)
565             }
566         }
567     }
568
569     pub fn exact_div(
570         &mut self,
571         a: &ImmTy<'tcx, M::Provenance>,
572         b: &ImmTy<'tcx, M::Provenance>,
573         dest: &PlaceTy<'tcx, M::Provenance>,
574     ) -> InterpResult<'tcx> {
575         // Performs an exact division, resulting in undefined behavior where
576         // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
577         // First, check x % y != 0 (or if that computation overflows).
578         let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, &a, &b)?;
579         assert!(!overflow); // All overflow is UB, so this should never return on overflow.
580         if res.assert_bits(a.layout.size) != 0 {
581             throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b)
582         }
583         // `Rem` says this is all right, so we can let `Div` do its job.
584         self.binop_ignore_overflow(BinOp::Div, &a, &b, dest)
585     }
586
587     pub fn saturating_arith(
588         &self,
589         mir_op: BinOp,
590         l: &ImmTy<'tcx, M::Provenance>,
591         r: &ImmTy<'tcx, M::Provenance>,
592     ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
593         assert!(matches!(mir_op, BinOp::Add | BinOp::Sub));
594         let (val, overflowed, _ty) = self.overflowing_binary_op(mir_op, l, r)?;
595         Ok(if overflowed {
596             let size = l.layout.size;
597             let num_bits = size.bits();
598             if l.layout.abi.is_signed() {
599                 // For signed ints the saturated value depends on the sign of the first
600                 // term since the sign of the second term can be inferred from this and
601                 // the fact that the operation has overflowed (if either is 0 no
602                 // overflow can occur)
603                 let first_term: u128 = l.to_scalar().to_bits(l.layout.size)?;
604                 let first_term_positive = first_term & (1 << (num_bits - 1)) == 0;
605                 if first_term_positive {
606                     // Negative overflow not possible since the positive first term
607                     // can only increase an (in range) negative term for addition
608                     // or corresponding negated positive term for subtraction
609                     Scalar::from_int(size.signed_int_max(), size)
610                 } else {
611                     // Positive overflow not possible for similar reason
612                     // max negative
613                     Scalar::from_int(size.signed_int_min(), size)
614                 }
615             } else {
616                 // unsigned
617                 if matches!(mir_op, BinOp::Add) {
618                     // max unsigned
619                     Scalar::from_uint(size.unsigned_int_max(), size)
620                 } else {
621                     // underflow to 0
622                     Scalar::from_uint(0u128, size)
623                 }
624             }
625         } else {
626             val
627         })
628     }
629
630     /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
631     /// allocation. For integer pointers, we consider each of them their own tiny allocation of size
632     /// 0, so offset-by-0 (and only 0) is okay -- except that null cannot be offset by _any_ value.
633     pub fn ptr_offset_inbounds(
634         &self,
635         ptr: Pointer<Option<M::Provenance>>,
636         pointee_ty: Ty<'tcx>,
637         offset_count: i64,
638     ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
639         // We cannot overflow i64 as a type's size must be <= isize::MAX.
640         let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
641         // The computed offset, in bytes, must not overflow an isize.
642         // `checked_mul` enforces a too small bound, but no actual allocation can be big enough for
643         // the difference to be noticeable.
644         let offset_bytes =
645             offset_count.checked_mul(pointee_size).ok_or(err_ub!(PointerArithOverflow))?;
646         // The offset being in bounds cannot rely on "wrapping around" the address space.
647         // So, first rule out overflows in the pointer arithmetic.
648         let offset_ptr = ptr.signed_offset(offset_bytes, self)?;
649         // ptr and offset_ptr must be in bounds of the same allocated object. This means all of the
650         // memory between these pointers must be accessible. Note that we do not require the
651         // pointers to be properly aligned (unlike a read/write operation).
652         let min_ptr = if offset_bytes >= 0 { ptr } else { offset_ptr };
653         // This call handles checking for integer/null pointers.
654         self.check_ptr_access_align(
655             min_ptr,
656             Size::from_bytes(offset_bytes.unsigned_abs()),
657             Align::ONE,
658             CheckInAllocMsg::PointerArithmeticTest,
659         )?;
660         Ok(offset_ptr)
661     }
662
663     /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.
664     pub(crate) fn copy_intrinsic(
665         &mut self,
666         src: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
667         dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
668         count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
669         nonoverlapping: bool,
670     ) -> InterpResult<'tcx> {
671         let count = self.read_scalar(&count)?.to_machine_usize(self)?;
672         let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap().ty)?;
673         let (size, align) = (layout.size, layout.align.abi);
674         // `checked_mul` enforces a too small bound (the correct one would probably be machine_isize_max),
675         // but no actual allocation can be big enough for the difference to be noticeable.
676         let size = size.checked_mul(count, self).ok_or_else(|| {
677             err_ub_format!(
678                 "overflow computing total size of `{}`",
679                 if nonoverlapping { "copy_nonoverlapping" } else { "copy" }
680             )
681         })?;
682
683         let src = self.read_pointer(&src)?;
684         let dst = self.read_pointer(&dst)?;
685
686         self.mem_copy(src, align, dst, align, size, nonoverlapping)
687     }
688
689     pub(crate) fn write_bytes_intrinsic(
690         &mut self,
691         dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
692         byte: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
693         count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
694     ) -> InterpResult<'tcx> {
695         let layout = self.layout_of(dst.layout.ty.builtin_deref(true).unwrap().ty)?;
696
697         let dst = self.read_pointer(&dst)?;
698         let byte = self.read_scalar(&byte)?.to_u8()?;
699         let count = self.read_scalar(&count)?.to_machine_usize(self)?;
700
701         // `checked_mul` enforces a too small bound (the correct one would probably be machine_isize_max),
702         // but no actual allocation can be big enough for the difference to be noticeable.
703         let len = layout
704             .size
705             .checked_mul(count, self)
706             .ok_or_else(|| err_ub_format!("overflow computing total size of `write_bytes`"))?;
707
708         let bytes = std::iter::repeat(byte).take(len.bytes_usize());
709         self.write_bytes_ptr(dst, bytes)
710     }
711
712     pub(crate) fn raw_eq_intrinsic(
713         &mut self,
714         lhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
715         rhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
716     ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
717         let layout = self.layout_of(lhs.layout.ty.builtin_deref(true).unwrap().ty)?;
718         assert!(layout.is_sized());
719
720         let get_bytes = |this: &InterpCx<'mir, 'tcx, M>,
721                          op: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
722                          size|
723          -> InterpResult<'tcx, &[u8]> {
724             let ptr = this.read_pointer(op)?;
725             let Some(alloc_ref) = self.get_ptr_alloc(ptr, size, Align::ONE)? else {
726                 // zero-sized access
727                 return Ok(&[]);
728             };
729             if alloc_ref.has_provenance() {
730                 throw_ub_format!("`raw_eq` on bytes with provenance");
731             }
732             alloc_ref.get_bytes_strip_provenance()
733         };
734
735         let lhs_bytes = get_bytes(self, lhs, layout.size)?;
736         let rhs_bytes = get_bytes(self, rhs, layout.size)?;
737         Ok(Scalar::from_bool(lhs_bytes == rhs_bytes))
738     }
739 }