2 use rustc::mir::interpret::{InterpResult, Scalar};
5 layout::{LayoutOf, TyLayout},
8 use rustc_apfloat::Float;
9 use rustc_ast::ast::FloatTy;
11 use super::{ImmTy, Immediate, InterpCx, Machine, PlaceTy};
13 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
14 /// Applies the binary operation `op` to the two operands and writes a tuple of the result
15 /// and a boolean signifying the potential overflow to the destination.
16 pub fn binop_with_overflow(
19 left: ImmTy<'tcx, M::PointerTag>,
20 right: ImmTy<'tcx, M::PointerTag>,
21 dest: PlaceTy<'tcx, M::PointerTag>,
22 ) -> InterpResult<'tcx> {
23 let (val, overflowed, ty) = self.overflowing_binary_op(op, left, right)?;
25 self.tcx.intern_tup(&[ty, self.tcx.types.bool]),
27 "type mismatch for result of {:?}",
30 let val = Immediate::ScalarPair(val.into(), Scalar::from_bool(overflowed).into());
31 self.write_immediate(val, dest)
34 /// Applies the binary operation `op` to the arguments and writes the result to the
36 pub fn binop_ignore_overflow(
39 left: ImmTy<'tcx, M::PointerTag>,
40 right: ImmTy<'tcx, M::PointerTag>,
41 dest: PlaceTy<'tcx, M::PointerTag>,
42 ) -> InterpResult<'tcx> {
43 let (val, _overflowed, ty) = self.overflowing_binary_op(op, left, right)?;
44 assert_eq!(ty, dest.layout.ty, "type mismatch for result of {:?}", op);
45 self.write_scalar(val, dest)
49 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
55 ) -> (Scalar<M::PointerTag>, bool, Ty<'tcx>) {
56 use rustc::mir::BinOp::*;
58 let res = match bin_op {
65 _ => bug!("Invalid operation on char: {:?}", bin_op),
67 return (Scalar::from_bool(res), false, self.tcx.types.bool);
75 ) -> (Scalar<M::PointerTag>, bool, Ty<'tcx>) {
76 use rustc::mir::BinOp::*;
78 let res = match bin_op {
88 _ => bug!("Invalid operation on bool: {:?}", bin_op),
90 return (Scalar::from_bool(res), false, self.tcx.types.bool);
93 fn binary_float_op<F: Float + Into<Scalar<M::PointerTag>>>(
99 ) -> (Scalar<M::PointerTag>, bool, Ty<'tcx>) {
100 use rustc::mir::BinOp::*;
102 let (val, ty) = match bin_op {
103 Eq => (Scalar::from_bool(l == r), self.tcx.types.bool),
104 Ne => (Scalar::from_bool(l != r), self.tcx.types.bool),
105 Lt => (Scalar::from_bool(l < r), self.tcx.types.bool),
106 Le => (Scalar::from_bool(l <= r), self.tcx.types.bool),
107 Gt => (Scalar::from_bool(l > r), self.tcx.types.bool),
108 Ge => (Scalar::from_bool(l >= r), self.tcx.types.bool),
109 Add => ((l + r).value.into(), ty),
110 Sub => ((l - r).value.into(), ty),
111 Mul => ((l * r).value.into(), ty),
112 Div => ((l / r).value.into(), ty),
113 Rem => ((l % r).value.into(), ty),
114 _ => bug!("invalid float op: `{:?}`", bin_op),
116 return (val, false, ty);
122 // passing in raw bits
124 left_layout: TyLayout<'tcx>,
126 right_layout: TyLayout<'tcx>,
127 ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, bool, Ty<'tcx>)> {
128 use rustc::mir::BinOp::*;
130 // Shift ops can have an RHS with a different numeric type.
131 if bin_op == Shl || bin_op == Shr {
132 let signed = left_layout.abi.is_signed();
133 let mut oflo = (r as u32 as u128) != r;
134 let mut r = r as u32;
135 let size = left_layout.size;
136 oflo |= r >= size.bits() as u32;
137 r %= size.bits() as u32;
138 let result = if signed {
139 let l = self.sign_extend(l, left_layout) as i128;
140 let result = match bin_op {
143 _ => bug!("it has already been checked that this is a shift op"),
150 _ => bug!("it has already been checked that this is a shift op"),
153 let truncated = self.truncate(result, left_layout);
154 return Ok((Scalar::from_uint(truncated, size), oflo, left_layout.ty));
157 // For the remaining ops, the types must be the same on both sides
158 if left_layout.ty != right_layout.ty {
160 "invalid asymmetric binary op {:?}: {:?} ({:?}), {:?} ({:?})",
169 let size = left_layout.size;
171 // Operations that need special treatment for signed integers
172 if left_layout.abi.is_signed() {
173 let op: Option<fn(&i128, &i128) -> bool> = match bin_op {
174 Lt => Some(i128::lt),
175 Le => Some(i128::le),
176 Gt => Some(i128::gt),
177 Ge => Some(i128::ge),
180 if let Some(op) = op {
181 let l = self.sign_extend(l, left_layout) as i128;
182 let r = self.sign_extend(r, right_layout) as i128;
183 return Ok((Scalar::from_bool(op(&l, &r)), false, self.tcx.types.bool));
185 let op: Option<fn(i128, i128) -> (i128, bool)> = match bin_op {
186 Div if r == 0 => throw_ub!(DivisionByZero),
187 Rem if r == 0 => throw_ub!(RemainderByZero),
188 Div => Some(i128::overflowing_div),
189 Rem => Some(i128::overflowing_rem),
190 Add => Some(i128::overflowing_add),
191 Sub => Some(i128::overflowing_sub),
192 Mul => Some(i128::overflowing_mul),
195 if let Some(op) = op {
196 let l128 = self.sign_extend(l, left_layout) as i128;
197 let r = self.sign_extend(r, right_layout) as i128;
198 // We need a special check for overflowing remainder:
199 // "int_min % -1" overflows and returns 0, but after casting things to a larger int
200 // type it does *not* overflow nor give an unrepresentable result!
203 if r == -1 && l == (1 << (size.bits() - 1)) {
204 return Ok((Scalar::from_int(0, size), true, left_layout.ty));
210 let (result, oflo) = op(l128, r);
211 // This may be out-of-bounds for the result type, so we have to truncate ourselves.
212 // If that truncation loses any information, we have an overflow.
213 let result = result as u128;
214 let truncated = self.truncate(result, left_layout);
216 Scalar::from_uint(truncated, size),
217 oflo || self.sign_extend(truncated, left_layout) != result,
223 let (val, ty) = match bin_op {
224 Eq => (Scalar::from_bool(l == r), self.tcx.types.bool),
225 Ne => (Scalar::from_bool(l != r), self.tcx.types.bool),
227 Lt => (Scalar::from_bool(l < r), self.tcx.types.bool),
228 Le => (Scalar::from_bool(l <= r), self.tcx.types.bool),
229 Gt => (Scalar::from_bool(l > r), self.tcx.types.bool),
230 Ge => (Scalar::from_bool(l >= r), self.tcx.types.bool),
232 BitOr => (Scalar::from_uint(l | r, size), left_layout.ty),
233 BitAnd => (Scalar::from_uint(l & r, size), left_layout.ty),
234 BitXor => (Scalar::from_uint(l ^ r, size), left_layout.ty),
236 Add | Sub | Mul | Rem | Div => {
237 assert!(!left_layout.abi.is_signed());
238 let op: fn(u128, u128) -> (u128, bool) = match bin_op {
239 Add => u128::overflowing_add,
240 Sub => u128::overflowing_sub,
241 Mul => u128::overflowing_mul,
242 Div if r == 0 => throw_ub!(DivisionByZero),
243 Rem if r == 0 => throw_ub!(RemainderByZero),
244 Div => u128::overflowing_div,
245 Rem => u128::overflowing_rem,
248 let (result, oflo) = op(l, r);
249 // Truncate to target type.
250 // If that truncation loses any information, we have an overflow.
251 let truncated = self.truncate(result, left_layout);
253 Scalar::from_uint(truncated, size),
254 oflo || truncated != result,
260 "invalid binary op {:?}: {:?}, {:?} (both {:?})",
271 /// Returns the result of the specified operation, whether it overflowed, and
273 pub fn overflowing_binary_op(
276 left: ImmTy<'tcx, M::PointerTag>,
277 right: ImmTy<'tcx, M::PointerTag>,
278 ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, bool, Ty<'tcx>)> {
280 "Running binary op {:?}: {:?} ({:?}), {:?} ({:?})",
288 match left.layout.ty.kind {
290 assert_eq!(left.layout.ty, right.layout.ty);
291 let left = left.to_scalar()?;
292 let right = right.to_scalar()?;
293 Ok(self.binary_char_op(bin_op, left.to_char()?, right.to_char()?))
296 assert_eq!(left.layout.ty, right.layout.ty);
297 let left = left.to_scalar()?;
298 let right = right.to_scalar()?;
299 Ok(self.binary_bool_op(bin_op, left.to_bool()?, right.to_bool()?))
302 assert_eq!(left.layout.ty, right.layout.ty);
303 let ty = left.layout.ty;
304 let left = left.to_scalar()?;
305 let right = right.to_scalar()?;
308 self.binary_float_op(bin_op, ty, left.to_f32()?, right.to_f32()?)
311 self.binary_float_op(bin_op, ty, left.to_f64()?, right.to_f64()?)
315 _ if left.layout.ty.is_integral() => {
316 // the RHS type can be different, e.g. for shifts -- but it has to be integral, too
318 right.layout.ty.is_integral(),
319 "Unexpected types for BinOp: {:?} {:?} {:?}",
325 let l = self.force_bits(left.to_scalar()?, left.layout.size)?;
326 let r = self.force_bits(right.to_scalar()?, right.layout.size)?;
327 self.binary_int_op(bin_op, l, left.layout, r, right.layout)
329 _ if left.layout.ty.is_any_ptr() => {
330 // The RHS type must be the same *or an integer type* (for `Offset`).
332 right.layout.ty == left.layout.ty || right.layout.ty.is_integral(),
333 "Unexpected types for BinOp: {:?} {:?} {:?}",
339 M::binary_ptr_op(self, bin_op, left, right)
341 _ => bug!("Invalid MIR: bad LHS type for binop: {:?}", left.layout.ty),
345 /// Typed version of `overflowing_binary_op`, returning an `ImmTy`. Also ignores overflows.
350 left: ImmTy<'tcx, M::PointerTag>,
351 right: ImmTy<'tcx, M::PointerTag>,
352 ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
353 let (val, _overflow, ty) = self.overflowing_binary_op(bin_op, left, right)?;
354 Ok(ImmTy::from_scalar(val, self.layout_of(ty)?))
357 /// Returns the result of the specified operation, whether it overflowed, and
359 pub fn overflowing_unary_op(
362 val: ImmTy<'tcx, M::PointerTag>,
363 ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, bool, Ty<'tcx>)> {
364 use rustc::mir::UnOp::*;
366 let layout = val.layout;
367 let val = val.to_scalar()?;
368 trace!("Running unary op {:?}: {:?} ({:?})", un_op, val, layout.ty);
370 match layout.ty.kind {
372 let val = val.to_bool()?;
373 let res = match un_op {
375 _ => bug!("Invalid bool op {:?}", un_op),
377 Ok((Scalar::from_bool(res), false, self.tcx.types.bool))
380 let res = match (un_op, fty) {
381 (Neg, FloatTy::F32) => Scalar::from_f32(-val.to_f32()?),
382 (Neg, FloatTy::F64) => Scalar::from_f64(-val.to_f64()?),
383 _ => bug!("Invalid float op {:?}", un_op),
385 Ok((res, false, layout.ty))
388 assert!(layout.ty.is_integral());
389 let val = self.force_bits(val, layout.size)?;
390 let (res, overflow) = match un_op {
391 Not => (self.truncate(!val, layout), false), // bitwise negation, then truncate
393 // arithmetic negation
394 assert!(layout.abi.is_signed());
395 let val = self.sign_extend(val, layout) as i128;
396 let (res, overflow) = val.overflowing_neg();
397 let res = res as u128;
398 // Truncate to target type.
399 // If that truncation loses any information, we have an overflow.
400 let truncated = self.truncate(res, layout);
401 (truncated, overflow || self.sign_extend(truncated, layout) != res)
404 Ok((Scalar::from_uint(res, layout.size), overflow, layout.ty))
412 val: ImmTy<'tcx, M::PointerTag>,
413 ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
414 let (val, _overflow, ty) = self.overflowing_unary_op(un_op, val)?;
415 Ok(ImmTy::from_scalar(val, self.layout_of(ty)?))