3 use rustc_middle::{mir, ty::Ty};
4 use rustc_target::abi::Size;
8 pub trait EvalContextExt<'tcx> {
12 left: &ImmTy<'tcx, Provenance>,
13 right: &ImmTy<'tcx, Provenance>,
14 ) -> InterpResult<'tcx, (Scalar<Provenance>, bool, Ty<'tcx>)>;
17 impl<'mir, 'tcx> EvalContextExt<'tcx> for super::MiriInterpCx<'mir, 'tcx> {
21 left: &ImmTy<'tcx, Provenance>,
22 right: &ImmTy<'tcx, Provenance>,
23 ) -> InterpResult<'tcx, (Scalar<Provenance>, bool, Ty<'tcx>)> {
24 use rustc_middle::mir::BinOp::*;
26 trace!("ptr_op: {:?} {:?} {:?}", *left, bin_op, *right);
29 Eq | Ne | Lt | Le | Gt | Ge => {
30 assert_eq!(left.layout.abi, right.layout.abi); // types an differ, e.g. fn ptrs with different `for`
31 let size = self.pointer_size();
32 // Just compare the bits. ScalarPairs are compared lexicographically.
33 // We thus always compare pairs and simply fill scalars up with 0.
34 let left = match **left {
35 Immediate::Scalar(l) => (l.to_bits(size)?, 0),
36 Immediate::ScalarPair(l1, l2) => (l1.to_bits(size)?, l2.to_bits(size)?),
37 Immediate::Uninit => panic!("we should never see uninit data here"),
39 let right = match **right {
40 Immediate::Scalar(r) => (r.to_bits(size)?, 0),
41 Immediate::ScalarPair(r1, r2) => (r1.to_bits(size)?, r2.to_bits(size)?),
42 Immediate::Uninit => panic!("we should never see uninit data here"),
44 let res = match bin_op {
53 (Scalar::from_bool(res), false, self.tcx.types.bool)
57 assert!(left.layout.ty.is_unsafe_ptr());
58 let ptr = left.to_scalar().to_pointer(self)?;
59 let offset = right.to_scalar().to_machine_isize(self)?;
62 left.layout.ty.builtin_deref(true).expect("Offset called on non-ptr type").ty;
63 let ptr = self.ptr_offset_inbounds(ptr, pointee_ty, offset)?;
64 (Scalar::from_maybe_pointer(ptr, self), false, left.layout.ty)
67 // Some more operations are possible with atomics.
68 // The return value always has the provenance of the *left* operand.
69 Add | Sub | BitOr | BitAnd | BitXor => {
70 assert!(left.layout.ty.is_unsafe_ptr());
71 assert!(right.layout.ty.is_unsafe_ptr());
72 let ptr = left.to_scalar().to_pointer(self)?;
73 // We do the actual operation with usize-typed scalars.
74 let left = ImmTy::from_uint(ptr.addr().bytes(), self.machine.layouts.usize);
75 let right = ImmTy::from_uint(
76 right.to_scalar().to_machine_usize(self)?,
77 self.machine.layouts.usize,
79 let (result, overflowing, _ty) =
80 self.overflowing_binary_op(bin_op, &left, &right)?;
81 // Construct a new pointer with the provenance of `ptr` (the LHS).
83 Pointer::new(ptr.provenance, Size::from_bytes(result.to_machine_usize(self)?));
84 (Scalar::from_maybe_pointer(result_ptr, self), overflowing, left.layout.ty)
87 _ => span_bug!(self.cur_span(), "Invalid operator on pointers: {:?}", bin_op),