]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/operator.rs
Auto merge of #68952 - faern:stabilize-assoc-int-consts, r=dtolnay
[rust.git] / src / librustc_mir / interpret / operator.rs
1 use rustc::mir;
2 use rustc::mir::interpret::{InterpResult, Scalar};
3 use rustc::ty::{
4     self,
5     layout::{LayoutOf, TyLayout},
6     Ty,
7 };
8 use rustc_apfloat::Float;
9 use rustc_ast::ast::FloatTy;
10
11 use super::{ImmTy, Immediate, InterpCx, Machine, PlaceTy};
12
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(
17         &mut self,
18         op: mir::BinOp,
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)?;
24         debug_assert_eq!(
25             self.tcx.intern_tup(&[ty, self.tcx.types.bool]),
26             dest.layout.ty,
27             "type mismatch for result of {:?}",
28             op,
29         );
30         let val = Immediate::ScalarPair(val.into(), Scalar::from_bool(overflowed).into());
31         self.write_immediate(val, dest)
32     }
33
34     /// Applies the binary operation `op` to the arguments and writes the result to the
35     /// destination.
36     pub fn binop_ignore_overflow(
37         &mut self,
38         op: mir::BinOp,
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)
46     }
47 }
48
49 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
50     fn binary_char_op(
51         &self,
52         bin_op: mir::BinOp,
53         l: char,
54         r: char,
55     ) -> (Scalar<M::PointerTag>, bool, Ty<'tcx>) {
56         use rustc::mir::BinOp::*;
57
58         let res = match bin_op {
59             Eq => l == r,
60             Ne => l != r,
61             Lt => l < r,
62             Le => l <= r,
63             Gt => l > r,
64             Ge => l >= r,
65             _ => bug!("Invalid operation on char: {:?}", bin_op),
66         };
67         return (Scalar::from_bool(res), false, self.tcx.types.bool);
68     }
69
70     fn binary_bool_op(
71         &self,
72         bin_op: mir::BinOp,
73         l: bool,
74         r: bool,
75     ) -> (Scalar<M::PointerTag>, bool, Ty<'tcx>) {
76         use rustc::mir::BinOp::*;
77
78         let res = match bin_op {
79             Eq => l == r,
80             Ne => l != r,
81             Lt => l < r,
82             Le => l <= r,
83             Gt => l > r,
84             Ge => l >= r,
85             BitAnd => l & r,
86             BitOr => l | r,
87             BitXor => l ^ r,
88             _ => bug!("Invalid operation on bool: {:?}", bin_op),
89         };
90         return (Scalar::from_bool(res), false, self.tcx.types.bool);
91     }
92
93     fn binary_float_op<F: Float + Into<Scalar<M::PointerTag>>>(
94         &self,
95         bin_op: mir::BinOp,
96         ty: Ty<'tcx>,
97         l: F,
98         r: F,
99     ) -> (Scalar<M::PointerTag>, bool, Ty<'tcx>) {
100         use rustc::mir::BinOp::*;
101
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),
115         };
116         return (val, false, ty);
117     }
118
119     fn binary_int_op(
120         &self,
121         bin_op: mir::BinOp,
122         // passing in raw bits
123         l: u128,
124         left_layout: TyLayout<'tcx>,
125         r: u128,
126         right_layout: TyLayout<'tcx>,
127     ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, bool, Ty<'tcx>)> {
128         use rustc::mir::BinOp::*;
129
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 {
141                     Shl => l << r,
142                     Shr => l >> r,
143                     _ => bug!("it has already been checked that this is a shift op"),
144                 };
145                 result as u128
146             } else {
147                 match bin_op {
148                     Shl => l << r,
149                     Shr => l >> r,
150                     _ => bug!("it has already been checked that this is a shift op"),
151                 }
152             };
153             let truncated = self.truncate(result, left_layout);
154             return Ok((Scalar::from_uint(truncated, size), oflo, left_layout.ty));
155         }
156
157         // For the remaining ops, the types must be the same on both sides
158         if left_layout.ty != right_layout.ty {
159             bug!(
160                 "invalid asymmetric binary op {:?}: {:?} ({:?}), {:?} ({:?})",
161                 bin_op,
162                 l,
163                 left_layout.ty,
164                 r,
165                 right_layout.ty,
166             )
167         }
168
169         let size = left_layout.size;
170
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),
178                 _ => None,
179             };
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));
184             }
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),
193                 _ => None,
194             };
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!
201                 match bin_op {
202                     Rem => {
203                         if r == -1 && l == (1 << (size.bits() - 1)) {
204                             return Ok((Scalar::from_int(0, size), true, left_layout.ty));
205                         }
206                     }
207                     _ => {}
208                 }
209
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);
215                 return Ok((
216                     Scalar::from_uint(truncated, size),
217                     oflo || self.sign_extend(truncated, left_layout) != result,
218                     left_layout.ty,
219                 ));
220             }
221         }
222
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),
226
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),
231
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),
235
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,
246                     _ => bug!(),
247                 };
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);
252                 return Ok((
253                     Scalar::from_uint(truncated, size),
254                     oflo || truncated != result,
255                     left_layout.ty,
256                 ));
257             }
258
259             _ => bug!(
260                 "invalid binary op {:?}: {:?}, {:?} (both {:?})",
261                 bin_op,
262                 l,
263                 r,
264                 right_layout.ty,
265             ),
266         };
267
268         Ok((val, false, ty))
269     }
270
271     /// Returns the result of the specified operation, whether it overflowed, and
272     /// the result type.
273     pub fn overflowing_binary_op(
274         &self,
275         bin_op: mir::BinOp,
276         left: ImmTy<'tcx, M::PointerTag>,
277         right: ImmTy<'tcx, M::PointerTag>,
278     ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, bool, Ty<'tcx>)> {
279         trace!(
280             "Running binary op {:?}: {:?} ({:?}), {:?} ({:?})",
281             bin_op,
282             *left,
283             left.layout.ty,
284             *right,
285             right.layout.ty
286         );
287
288         match left.layout.ty.kind {
289             ty::Char => {
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()?))
294             }
295             ty::Bool => {
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()?))
300             }
301             ty::Float(fty) => {
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()?;
306                 Ok(match fty {
307                     FloatTy::F32 => {
308                         self.binary_float_op(bin_op, ty, left.to_f32()?, right.to_f32()?)
309                     }
310                     FloatTy::F64 => {
311                         self.binary_float_op(bin_op, ty, left.to_f64()?, right.to_f64()?)
312                     }
313                 })
314             }
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
317                 assert!(
318                     right.layout.ty.is_integral(),
319                     "Unexpected types for BinOp: {:?} {:?} {:?}",
320                     left.layout.ty,
321                     bin_op,
322                     right.layout.ty
323                 );
324
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)
328             }
329             _ if left.layout.ty.is_any_ptr() => {
330                 // The RHS type must be the same *or an integer type* (for `Offset`).
331                 assert!(
332                     right.layout.ty == left.layout.ty || right.layout.ty.is_integral(),
333                     "Unexpected types for BinOp: {:?} {:?} {:?}",
334                     left.layout.ty,
335                     bin_op,
336                     right.layout.ty
337                 );
338
339                 M::binary_ptr_op(self, bin_op, left, right)
340             }
341             _ => bug!("Invalid MIR: bad LHS type for binop: {:?}", left.layout.ty),
342         }
343     }
344
345     /// Typed version of `overflowing_binary_op`, returning an `ImmTy`. Also ignores overflows.
346     #[inline]
347     pub fn binary_op(
348         &self,
349         bin_op: mir::BinOp,
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)?))
355     }
356
357     /// Returns the result of the specified operation, whether it overflowed, and
358     /// the result type.
359     pub fn overflowing_unary_op(
360         &self,
361         un_op: mir::UnOp,
362         val: ImmTy<'tcx, M::PointerTag>,
363     ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, bool, Ty<'tcx>)> {
364         use rustc::mir::UnOp::*;
365
366         let layout = val.layout;
367         let val = val.to_scalar()?;
368         trace!("Running unary op {:?}: {:?} ({:?})", un_op, val, layout.ty);
369
370         match layout.ty.kind {
371             ty::Bool => {
372                 let val = val.to_bool()?;
373                 let res = match un_op {
374                     Not => !val,
375                     _ => bug!("Invalid bool op {:?}", un_op),
376                 };
377                 Ok((Scalar::from_bool(res), false, self.tcx.types.bool))
378             }
379             ty::Float(fty) => {
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),
384                 };
385                 Ok((res, false, layout.ty))
386             }
387             _ => {
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
392                     Neg => {
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)
402                     }
403                 };
404                 Ok((Scalar::from_uint(res, layout.size), overflow, layout.ty))
405             }
406         }
407     }
408
409     pub fn unary_op(
410         &self,
411         un_op: mir::UnOp,
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)?))
416     }
417 }