]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/intrinsics.rs
Auto merge of #103954 - matthiaskrgr:rollup-tskpxnj, r=matthiaskrgr
[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 =
181                     self.tcx.const_eval_global_id(self.param_env, gid, Some(self.tcx.span))?;
182                 let val = self.const_val_to_op(val, ty, Some(dest.layout))?;
183                 self.copy_op(&val, dest, /*allow_transmute*/ false)?;
184             }
185
186             sym::ctpop
187             | sym::cttz
188             | sym::cttz_nonzero
189             | sym::ctlz
190             | sym::ctlz_nonzero
191             | sym::bswap
192             | sym::bitreverse => {
193                 let ty = substs.type_at(0);
194                 let layout_of = self.layout_of(ty)?;
195                 let val = self.read_scalar(&args[0])?;
196                 let bits = val.to_bits(layout_of.size)?;
197                 let kind = match layout_of.abi {
198                     Abi::Scalar(scalar) => scalar.primitive(),
199                     _ => span_bug!(
200                         self.cur_span(),
201                         "{} called on invalid type {:?}",
202                         intrinsic_name,
203                         ty
204                     ),
205                 };
206                 let (nonzero, intrinsic_name) = match intrinsic_name {
207                     sym::cttz_nonzero => (true, sym::cttz),
208                     sym::ctlz_nonzero => (true, sym::ctlz),
209                     other => (false, other),
210                 };
211                 if nonzero && bits == 0 {
212                     throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
213                 }
214                 let out_val = numeric_intrinsic(intrinsic_name, bits, kind);
215                 self.write_scalar(out_val, dest)?;
216             }
217             sym::add_with_overflow | sym::sub_with_overflow | sym::mul_with_overflow => {
218                 let lhs = self.read_immediate(&args[0])?;
219                 let rhs = self.read_immediate(&args[1])?;
220                 let bin_op = match intrinsic_name {
221                     sym::add_with_overflow => BinOp::Add,
222                     sym::sub_with_overflow => BinOp::Sub,
223                     sym::mul_with_overflow => BinOp::Mul,
224                     _ => bug!(),
225                 };
226                 self.binop_with_overflow(
227                     bin_op, /*force_overflow_checks*/ true, &lhs, &rhs, dest,
228                 )?;
229             }
230             sym::saturating_add | sym::saturating_sub => {
231                 let l = self.read_immediate(&args[0])?;
232                 let r = self.read_immediate(&args[1])?;
233                 let val = self.saturating_arith(
234                     if intrinsic_name == sym::saturating_add { BinOp::Add } else { BinOp::Sub },
235                     &l,
236                     &r,
237                 )?;
238                 self.write_scalar(val, dest)?;
239             }
240             sym::discriminant_value => {
241                 let place = self.deref_operand(&args[0])?;
242                 let discr_val = self.read_discriminant(&place.into())?.0;
243                 self.write_scalar(discr_val, dest)?;
244             }
245             sym::unchecked_shl
246             | sym::unchecked_shr
247             | sym::unchecked_add
248             | sym::unchecked_sub
249             | sym::unchecked_mul
250             | sym::unchecked_div
251             | sym::unchecked_rem => {
252                 let l = self.read_immediate(&args[0])?;
253                 let r = self.read_immediate(&args[1])?;
254                 let bin_op = match intrinsic_name {
255                     sym::unchecked_shl => BinOp::Shl,
256                     sym::unchecked_shr => BinOp::Shr,
257                     sym::unchecked_add => BinOp::Add,
258                     sym::unchecked_sub => BinOp::Sub,
259                     sym::unchecked_mul => BinOp::Mul,
260                     sym::unchecked_div => BinOp::Div,
261                     sym::unchecked_rem => BinOp::Rem,
262                     _ => bug!(),
263                 };
264                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, &l, &r)?;
265                 if overflowed {
266                     let layout = self.layout_of(substs.type_at(0))?;
267                     let r_val = r.to_scalar().to_bits(layout.size)?;
268                     if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
269                         throw_ub_format!("overflowing shift by {} in `{}`", r_val, intrinsic_name);
270                     } else {
271                         throw_ub_format!("overflow executing `{}`", intrinsic_name);
272                     }
273                 }
274                 self.write_scalar(val, dest)?;
275             }
276             sym::rotate_left | sym::rotate_right => {
277                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
278                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
279                 let layout = self.layout_of(substs.type_at(0))?;
280                 let val = self.read_scalar(&args[0])?;
281                 let val_bits = val.to_bits(layout.size)?;
282                 let raw_shift = self.read_scalar(&args[1])?;
283                 let raw_shift_bits = raw_shift.to_bits(layout.size)?;
284                 let width_bits = u128::from(layout.size.bits());
285                 let shift_bits = raw_shift_bits % width_bits;
286                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
287                 let result_bits = if intrinsic_name == sym::rotate_left {
288                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
289                 } else {
290                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
291                 };
292                 let truncated_bits = self.truncate(result_bits, layout);
293                 let result = Scalar::from_uint(truncated_bits, layout.size);
294                 self.write_scalar(result, dest)?;
295             }
296             sym::copy => {
297                 self.copy_intrinsic(&args[0], &args[1], &args[2], /*nonoverlapping*/ false)?;
298             }
299             sym::write_bytes => {
300                 self.write_bytes_intrinsic(&args[0], &args[1], &args[2])?;
301             }
302             sym::offset => {
303                 let ptr = self.read_pointer(&args[0])?;
304                 let offset_count = self.read_scalar(&args[1])?.to_machine_isize(self)?;
305                 let pointee_ty = substs.type_at(0);
306
307                 let offset_ptr = self.ptr_offset_inbounds(ptr, pointee_ty, offset_count)?;
308                 self.write_pointer(offset_ptr, dest)?;
309             }
310             sym::arith_offset => {
311                 let ptr = self.read_pointer(&args[0])?;
312                 let offset_count = self.read_scalar(&args[1])?.to_machine_isize(self)?;
313                 let pointee_ty = substs.type_at(0);
314
315                 let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
316                 let offset_bytes = offset_count.wrapping_mul(pointee_size);
317                 let offset_ptr = ptr.wrapping_signed_offset(offset_bytes, self);
318                 self.write_pointer(offset_ptr, dest)?;
319             }
320             sym::ptr_offset_from | sym::ptr_offset_from_unsigned => {
321                 let a = self.read_pointer(&args[0])?;
322                 let b = self.read_pointer(&args[1])?;
323
324                 let usize_layout = self.layout_of(self.tcx.types.usize)?;
325                 let isize_layout = self.layout_of(self.tcx.types.isize)?;
326
327                 // Get offsets for both that are at least relative to the same base.
328                 let (a_offset, b_offset) =
329                     match (self.ptr_try_get_alloc_id(a), self.ptr_try_get_alloc_id(b)) {
330                         (Err(a), Err(b)) => {
331                             // Neither pointer points to an allocation.
332                             // If these are inequal or null, this *will* fail the deref check below.
333                             (a, b)
334                         }
335                         (Err(_), _) | (_, Err(_)) => {
336                             // We managed to find a valid allocation for one pointer, but not the other.
337                             // That means they are definitely not pointing to the same allocation.
338                             throw_ub_format!(
339                                 "`{}` called on pointers into different allocations",
340                                 intrinsic_name
341                             );
342                         }
343                         (Ok((a_alloc_id, a_offset, _)), Ok((b_alloc_id, b_offset, _))) => {
344                             // Found allocation for both. They must be into the same allocation.
345                             if a_alloc_id != b_alloc_id {
346                                 throw_ub_format!(
347                                     "`{}` called on pointers into different allocations",
348                                     intrinsic_name
349                                 );
350                             }
351                             // Use these offsets for distance calculation.
352                             (a_offset.bytes(), b_offset.bytes())
353                         }
354                     };
355
356                 // Compute distance.
357                 let dist = {
358                     // Addresses are unsigned, so this is a `usize` computation. We have to do the
359                     // overflow check separately anyway.
360                     let (val, overflowed, _ty) = {
361                         let a_offset = ImmTy::from_uint(a_offset, usize_layout);
362                         let b_offset = ImmTy::from_uint(b_offset, usize_layout);
363                         self.overflowing_binary_op(BinOp::Sub, &a_offset, &b_offset)?
364                     };
365                     if overflowed {
366                         // a < b
367                         if intrinsic_name == sym::ptr_offset_from_unsigned {
368                             throw_ub_format!(
369                                 "`{}` called when first pointer has smaller offset than second: {} < {}",
370                                 intrinsic_name,
371                                 a_offset,
372                                 b_offset,
373                             );
374                         }
375                         // The signed form of the intrinsic allows this. If we interpret the
376                         // difference as isize, we'll get the proper signed difference. If that
377                         // seems *positive*, they were more than isize::MAX apart.
378                         let dist = val.to_machine_isize(self)?;
379                         if dist >= 0 {
380                             throw_ub_format!(
381                                 "`{}` called when first pointer is too far before second",
382                                 intrinsic_name
383                             );
384                         }
385                         dist
386                     } else {
387                         // b >= a
388                         let dist = val.to_machine_isize(self)?;
389                         // If converting to isize produced a *negative* result, we had an overflow
390                         // because they were more than isize::MAX apart.
391                         if dist < 0 {
392                             throw_ub_format!(
393                                 "`{}` called when first pointer is too far ahead of second",
394                                 intrinsic_name
395                             );
396                         }
397                         dist
398                     }
399                 };
400
401                 // Check that the range between them is dereferenceable ("in-bounds or one past the
402                 // end of the same allocation"). This is like the check in ptr_offset_inbounds.
403                 let min_ptr = if dist >= 0 { b } else { a };
404                 self.check_ptr_access_align(
405                     min_ptr,
406                     Size::from_bytes(dist.unsigned_abs()),
407                     Align::ONE,
408                     CheckInAllocMsg::OffsetFromTest,
409                 )?;
410
411                 // Perform division by size to compute return value.
412                 let ret_layout = if intrinsic_name == sym::ptr_offset_from_unsigned {
413                     assert!(0 <= dist && dist <= self.machine_isize_max());
414                     usize_layout
415                 } else {
416                     assert!(self.machine_isize_min() <= dist && dist <= self.machine_isize_max());
417                     isize_layout
418                 };
419                 let pointee_layout = self.layout_of(substs.type_at(0))?;
420                 // If ret_layout is unsigned, we checked that so is the distance, so we are good.
421                 let val = ImmTy::from_int(dist, ret_layout);
422                 let size = ImmTy::from_int(pointee_layout.size.bytes(), ret_layout);
423                 self.exact_div(&val, &size, dest)?;
424             }
425
426             sym::transmute => {
427                 self.copy_op(&args[0], dest, /*allow_transmute*/ true)?;
428             }
429             sym::assert_inhabited | sym::assert_zero_valid | sym::assert_uninit_valid => {
430                 let ty = instance.substs.type_at(0);
431                 let layout = self.layout_of(ty)?;
432
433                 // For *all* intrinsics we first check `is_uninhabited` to give a more specific
434                 // error message.
435                 if layout.abi.is_uninhabited() {
436                     // The run-time intrinsic panics just to get a good backtrace; here we abort
437                     // since there is no problem showing a backtrace even for aborts.
438                     M::abort(
439                         self,
440                         format!(
441                             "aborted execution: attempted to instantiate uninhabited type `{}`",
442                             ty
443                         ),
444                     )?;
445                 }
446
447                 if intrinsic_name == sym::assert_zero_valid {
448                     let should_panic = !self.tcx.permits_zero_init(layout);
449
450                     if should_panic {
451                         M::abort(
452                             self,
453                             format!(
454                                 "aborted execution: attempted to zero-initialize type `{}`, which is invalid",
455                                 ty
456                             ),
457                         )?;
458                     }
459                 }
460
461                 if intrinsic_name == sym::assert_uninit_valid {
462                     let should_panic = !self.tcx.permits_uninit_init(layout);
463
464                     if should_panic {
465                         M::abort(
466                             self,
467                             format!(
468                                 "aborted execution: attempted to leave type `{}` uninitialized, which is invalid",
469                                 ty
470                             ),
471                         )?;
472                     }
473                 }
474             }
475             sym::simd_insert => {
476                 let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
477                 let elem = &args[2];
478                 let (input, input_len) = self.operand_to_simd(&args[0])?;
479                 let (dest, dest_len) = self.place_to_simd(dest)?;
480                 assert_eq!(input_len, dest_len, "Return vector length must match input length");
481                 assert!(
482                     index < dest_len,
483                     "Index `{}` must be in bounds of vector with length {}`",
484                     index,
485                     dest_len
486                 );
487
488                 for i in 0..dest_len {
489                     let place = self.mplace_index(&dest, i)?;
490                     let value = if i == index {
491                         elem.clone()
492                     } else {
493                         self.mplace_index(&input, i)?.into()
494                     };
495                     self.copy_op(&value, &place.into(), /*allow_transmute*/ false)?;
496                 }
497             }
498             sym::simd_extract => {
499                 let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
500                 let (input, input_len) = self.operand_to_simd(&args[0])?;
501                 assert!(
502                     index < input_len,
503                     "index `{}` must be in bounds of vector with length `{}`",
504                     index,
505                     input_len
506                 );
507                 self.copy_op(
508                     &self.mplace_index(&input, index)?.into(),
509                     dest,
510                     /*allow_transmute*/ false,
511                 )?;
512             }
513             sym::likely | sym::unlikely | sym::black_box => {
514                 // These just return their argument
515                 self.copy_op(&args[0], dest, /*allow_transmute*/ false)?;
516             }
517             sym::raw_eq => {
518                 let result = self.raw_eq_intrinsic(&args[0], &args[1])?;
519                 self.write_scalar(result, dest)?;
520             }
521
522             sym::vtable_size => {
523                 let ptr = self.read_pointer(&args[0])?;
524                 let (size, _align) = self.get_vtable_size_and_align(ptr)?;
525                 self.write_scalar(Scalar::from_machine_usize(size.bytes(), self), dest)?;
526             }
527             sym::vtable_align => {
528                 let ptr = self.read_pointer(&args[0])?;
529                 let (_size, align) = self.get_vtable_size_and_align(ptr)?;
530                 self.write_scalar(Scalar::from_machine_usize(align.bytes(), self), dest)?;
531             }
532
533             _ => return Ok(false),
534         }
535
536         trace!("{:?}", self.dump_place(**dest));
537         self.go_to_block(ret);
538         Ok(true)
539     }
540
541     pub(super) fn emulate_nondiverging_intrinsic(
542         &mut self,
543         intrinsic: &NonDivergingIntrinsic<'tcx>,
544     ) -> InterpResult<'tcx> {
545         match intrinsic {
546             NonDivergingIntrinsic::Assume(op) => {
547                 let op = self.eval_operand(op, None)?;
548                 let cond = self.read_scalar(&op)?.to_bool()?;
549                 if !cond {
550                     throw_ub_format!("`assume` called with `false`");
551                 }
552                 Ok(())
553             }
554             NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
555                 count,
556                 src,
557                 dst,
558             }) => {
559                 let src = self.eval_operand(src, None)?;
560                 let dst = self.eval_operand(dst, None)?;
561                 let count = self.eval_operand(count, None)?;
562                 self.copy_intrinsic(&src, &dst, &count, /* nonoverlapping */ true)
563             }
564         }
565     }
566
567     pub fn exact_div(
568         &mut self,
569         a: &ImmTy<'tcx, M::Provenance>,
570         b: &ImmTy<'tcx, M::Provenance>,
571         dest: &PlaceTy<'tcx, M::Provenance>,
572     ) -> InterpResult<'tcx> {
573         // Performs an exact division, resulting in undefined behavior where
574         // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
575         // First, check x % y != 0 (or if that computation overflows).
576         let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, &a, &b)?;
577         assert!(!overflow); // All overflow is UB, so this should never return on overflow.
578         if res.assert_bits(a.layout.size) != 0 {
579             throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b)
580         }
581         // `Rem` says this is all right, so we can let `Div` do its job.
582         self.binop_ignore_overflow(BinOp::Div, &a, &b, dest)
583     }
584
585     pub fn saturating_arith(
586         &self,
587         mir_op: BinOp,
588         l: &ImmTy<'tcx, M::Provenance>,
589         r: &ImmTy<'tcx, M::Provenance>,
590     ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
591         assert!(matches!(mir_op, BinOp::Add | BinOp::Sub));
592         let (val, overflowed, _ty) = self.overflowing_binary_op(mir_op, l, r)?;
593         Ok(if overflowed {
594             let size = l.layout.size;
595             let num_bits = size.bits();
596             if l.layout.abi.is_signed() {
597                 // For signed ints the saturated value depends on the sign of the first
598                 // term since the sign of the second term can be inferred from this and
599                 // the fact that the operation has overflowed (if either is 0 no
600                 // overflow can occur)
601                 let first_term: u128 = l.to_scalar().to_bits(l.layout.size)?;
602                 let first_term_positive = first_term & (1 << (num_bits - 1)) == 0;
603                 if first_term_positive {
604                     // Negative overflow not possible since the positive first term
605                     // can only increase an (in range) negative term for addition
606                     // or corresponding negated positive term for subtraction
607                     Scalar::from_int(size.signed_int_max(), size)
608                 } else {
609                     // Positive overflow not possible for similar reason
610                     // max negative
611                     Scalar::from_int(size.signed_int_min(), size)
612                 }
613             } else {
614                 // unsigned
615                 if matches!(mir_op, BinOp::Add) {
616                     // max unsigned
617                     Scalar::from_uint(size.unsigned_int_max(), size)
618                 } else {
619                     // underflow to 0
620                     Scalar::from_uint(0u128, size)
621                 }
622             }
623         } else {
624             val
625         })
626     }
627
628     /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
629     /// allocation. For integer pointers, we consider each of them their own tiny allocation of size
630     /// 0, so offset-by-0 (and only 0) is okay -- except that null cannot be offset by _any_ value.
631     pub fn ptr_offset_inbounds(
632         &self,
633         ptr: Pointer<Option<M::Provenance>>,
634         pointee_ty: Ty<'tcx>,
635         offset_count: i64,
636     ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
637         // We cannot overflow i64 as a type's size must be <= isize::MAX.
638         let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
639         // The computed offset, in bytes, must not overflow an isize.
640         // `checked_mul` enforces a too small bound, but no actual allocation can be big enough for
641         // the difference to be noticeable.
642         let offset_bytes =
643             offset_count.checked_mul(pointee_size).ok_or(err_ub!(PointerArithOverflow))?;
644         // The offset being in bounds cannot rely on "wrapping around" the address space.
645         // So, first rule out overflows in the pointer arithmetic.
646         let offset_ptr = ptr.signed_offset(offset_bytes, self)?;
647         // ptr and offset_ptr must be in bounds of the same allocated object. This means all of the
648         // memory between these pointers must be accessible. Note that we do not require the
649         // pointers to be properly aligned (unlike a read/write operation).
650         let min_ptr = if offset_bytes >= 0 { ptr } else { offset_ptr };
651         // This call handles checking for integer/null pointers.
652         self.check_ptr_access_align(
653             min_ptr,
654             Size::from_bytes(offset_bytes.unsigned_abs()),
655             Align::ONE,
656             CheckInAllocMsg::PointerArithmeticTest,
657         )?;
658         Ok(offset_ptr)
659     }
660
661     /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.
662     pub(crate) fn copy_intrinsic(
663         &mut self,
664         src: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
665         dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
666         count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
667         nonoverlapping: bool,
668     ) -> InterpResult<'tcx> {
669         let count = self.read_scalar(&count)?.to_machine_usize(self)?;
670         let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap().ty)?;
671         let (size, align) = (layout.size, layout.align.abi);
672         // `checked_mul` enforces a too small bound (the correct one would probably be machine_isize_max),
673         // but no actual allocation can be big enough for the difference to be noticeable.
674         let size = size.checked_mul(count, self).ok_or_else(|| {
675             err_ub_format!(
676                 "overflow computing total size of `{}`",
677                 if nonoverlapping { "copy_nonoverlapping" } else { "copy" }
678             )
679         })?;
680
681         let src = self.read_pointer(&src)?;
682         let dst = self.read_pointer(&dst)?;
683
684         self.mem_copy(src, align, dst, align, size, nonoverlapping)
685     }
686
687     pub(crate) fn write_bytes_intrinsic(
688         &mut self,
689         dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
690         byte: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
691         count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
692     ) -> InterpResult<'tcx> {
693         let layout = self.layout_of(dst.layout.ty.builtin_deref(true).unwrap().ty)?;
694
695         let dst = self.read_pointer(&dst)?;
696         let byte = self.read_scalar(&byte)?.to_u8()?;
697         let count = self.read_scalar(&count)?.to_machine_usize(self)?;
698
699         // `checked_mul` enforces a too small bound (the correct one would probably be machine_isize_max),
700         // but no actual allocation can be big enough for the difference to be noticeable.
701         let len = layout
702             .size
703             .checked_mul(count, self)
704             .ok_or_else(|| err_ub_format!("overflow computing total size of `write_bytes`"))?;
705
706         let bytes = std::iter::repeat(byte).take(len.bytes_usize());
707         self.write_bytes_ptr(dst, bytes)
708     }
709
710     pub(crate) fn raw_eq_intrinsic(
711         &mut self,
712         lhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
713         rhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
714     ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
715         let layout = self.layout_of(lhs.layout.ty.builtin_deref(true).unwrap().ty)?;
716         assert!(!layout.is_unsized());
717
718         let get_bytes = |this: &InterpCx<'mir, 'tcx, M>,
719                          op: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
720                          size|
721          -> InterpResult<'tcx, &[u8]> {
722             let ptr = this.read_pointer(op)?;
723             let Some(alloc_ref) = self.get_ptr_alloc(ptr, size, Align::ONE)? else {
724                 // zero-sized access
725                 return Ok(&[]);
726             };
727             if alloc_ref.has_provenance() {
728                 throw_ub_format!("`raw_eq` on bytes with provenance");
729             }
730             alloc_ref.get_bytes_strip_provenance()
731         };
732
733         let lhs_bytes = get_bytes(self, lhs, layout.size)?;
734         let rhs_bytes = get_bytes(self, rhs, layout.size)?;
735         Ok(Scalar::from_bool(lhs_bytes == rhs_bytes))
736     }
737 }