]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/operator.rs
Auto merge of #68494 - matthewjasper:internal-static-ptrs, r=nikomatsakis
[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 syntax::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             if oflo {
138                 r %= size.bits() as u32;
139             }
140             let result = if signed {
141                 let l = self.sign_extend(l, left_layout) as i128;
142                 let result = match bin_op {
143                     Shl => l << r,
144                     Shr => l >> r,
145                     _ => bug!("it has already been checked that this is a shift op"),
146                 };
147                 result as u128
148             } else {
149                 match bin_op {
150                     Shl => l << r,
151                     Shr => l >> r,
152                     _ => bug!("it has already been checked that this is a shift op"),
153                 }
154             };
155             let truncated = self.truncate(result, left_layout);
156             return Ok((Scalar::from_uint(truncated, size), oflo, left_layout.ty));
157         }
158
159         // For the remaining ops, the types must be the same on both sides
160         if left_layout.ty != right_layout.ty {
161             bug!(
162                 "invalid asymmetric binary op {:?}: {:?} ({:?}), {:?} ({:?})",
163                 bin_op,
164                 l,
165                 left_layout.ty,
166                 r,
167                 right_layout.ty,
168             )
169         }
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                 let size = left_layout.size;
199                 match bin_op {
200                     Rem | Div => {
201                         // int_min / -1
202                         if r == -1 && l == (1 << (size.bits() - 1)) {
203                             return Ok((Scalar::from_uint(l, size), true, left_layout.ty));
204                         }
205                     }
206                     _ => {}
207                 }
208                 trace!("{}, {}, {}", l, l128, r);
209                 let (result, mut oflo) = op(l128, r);
210                 trace!("{}, {}", result, oflo);
211                 if !oflo && size.bits() != 128 {
212                     let max = 1 << (size.bits() - 1);
213                     oflo = result >= max || result < -max;
214                 }
215                 // this may be out-of-bounds for the result type, so we have to truncate ourselves
216                 let result = result as u128;
217                 let truncated = self.truncate(result, left_layout);
218                 return Ok((Scalar::from_uint(truncated, size), oflo, left_layout.ty));
219             }
220         }
221
222         let size = left_layout.size;
223
224         let (val, ty) = match bin_op {
225             Eq => (Scalar::from_bool(l == r), self.tcx.types.bool),
226             Ne => (Scalar::from_bool(l != r), self.tcx.types.bool),
227
228             Lt => (Scalar::from_bool(l < r), self.tcx.types.bool),
229             Le => (Scalar::from_bool(l <= r), self.tcx.types.bool),
230             Gt => (Scalar::from_bool(l > r), self.tcx.types.bool),
231             Ge => (Scalar::from_bool(l >= r), self.tcx.types.bool),
232
233             BitOr => (Scalar::from_uint(l | r, size), left_layout.ty),
234             BitAnd => (Scalar::from_uint(l & r, size), left_layout.ty),
235             BitXor => (Scalar::from_uint(l ^ r, size), left_layout.ty),
236
237             Add | Sub | Mul | Rem | Div => {
238                 debug_assert!(!left_layout.abi.is_signed());
239                 let op: fn(u128, u128) -> (u128, bool) = match bin_op {
240                     Add => u128::overflowing_add,
241                     Sub => u128::overflowing_sub,
242                     Mul => u128::overflowing_mul,
243                     Div if r == 0 => throw_ub!(DivisionByZero),
244                     Rem if r == 0 => throw_ub!(RemainderByZero),
245                     Div => u128::overflowing_div,
246                     Rem => u128::overflowing_rem,
247                     _ => bug!(),
248                 };
249                 let (result, oflo) = op(l, r);
250                 let truncated = self.truncate(result, left_layout);
251                 return Ok((
252                     Scalar::from_uint(truncated, size),
253                     oflo || truncated != result,
254                     left_layout.ty,
255                 ));
256             }
257
258             _ => bug!(
259                 "invalid binary op {:?}: {:?}, {:?} (both {:?})",
260                 bin_op,
261                 l,
262                 r,
263                 right_layout.ty,
264             ),
265         };
266
267         Ok((val, false, ty))
268     }
269
270     /// Returns the result of the specified operation, whether it overflowed, and
271     /// the result type.
272     pub fn overflowing_binary_op(
273         &self,
274         bin_op: mir::BinOp,
275         left: ImmTy<'tcx, M::PointerTag>,
276         right: ImmTy<'tcx, M::PointerTag>,
277     ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, bool, Ty<'tcx>)> {
278         trace!(
279             "Running binary op {:?}: {:?} ({:?}), {:?} ({:?})",
280             bin_op,
281             *left,
282             left.layout.ty,
283             *right,
284             right.layout.ty
285         );
286
287         match left.layout.ty.kind {
288             ty::Char => {
289                 assert_eq!(left.layout.ty, right.layout.ty);
290                 let left = left.to_scalar()?;
291                 let right = right.to_scalar()?;
292                 Ok(self.binary_char_op(bin_op, left.to_char()?, right.to_char()?))
293             }
294             ty::Bool => {
295                 assert_eq!(left.layout.ty, right.layout.ty);
296                 let left = left.to_scalar()?;
297                 let right = right.to_scalar()?;
298                 Ok(self.binary_bool_op(bin_op, left.to_bool()?, right.to_bool()?))
299             }
300             ty::Float(fty) => {
301                 assert_eq!(left.layout.ty, right.layout.ty);
302                 let ty = left.layout.ty;
303                 let left = left.to_scalar()?;
304                 let right = right.to_scalar()?;
305                 Ok(match fty {
306                     FloatTy::F32 => {
307                         self.binary_float_op(bin_op, ty, left.to_f32()?, right.to_f32()?)
308                     }
309                     FloatTy::F64 => {
310                         self.binary_float_op(bin_op, ty, left.to_f64()?, right.to_f64()?)
311                     }
312                 })
313             }
314             _ if left.layout.ty.is_integral() => {
315                 // the RHS type can be different, e.g. for shifts -- but it has to be integral, too
316                 assert!(
317                     right.layout.ty.is_integral(),
318                     "Unexpected types for BinOp: {:?} {:?} {:?}",
319                     left.layout.ty,
320                     bin_op,
321                     right.layout.ty
322                 );
323
324                 let l = self.force_bits(left.to_scalar()?, left.layout.size)?;
325                 let r = self.force_bits(right.to_scalar()?, right.layout.size)?;
326                 self.binary_int_op(bin_op, l, left.layout, r, right.layout)
327             }
328             _ if left.layout.ty.is_any_ptr() => {
329                 // The RHS type must be the same *or an integer type* (for `Offset`).
330                 assert!(
331                     right.layout.ty == left.layout.ty || right.layout.ty.is_integral(),
332                     "Unexpected types for BinOp: {:?} {:?} {:?}",
333                     left.layout.ty,
334                     bin_op,
335                     right.layout.ty
336                 );
337
338                 M::binary_ptr_op(self, bin_op, left, right)
339             }
340             _ => bug!("Invalid MIR: bad LHS type for binop: {:?}", left.layout.ty),
341         }
342     }
343
344     /// Typed version of `checked_binary_op`, returning an `ImmTy`. Also ignores overflows.
345     #[inline]
346     pub fn binary_op(
347         &self,
348         bin_op: mir::BinOp,
349         left: ImmTy<'tcx, M::PointerTag>,
350         right: ImmTy<'tcx, M::PointerTag>,
351     ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
352         let (val, _overflow, ty) = self.overflowing_binary_op(bin_op, left, right)?;
353         Ok(ImmTy::from_scalar(val, self.layout_of(ty)?))
354     }
355
356     pub fn unary_op(
357         &self,
358         un_op: mir::UnOp,
359         val: ImmTy<'tcx, M::PointerTag>,
360     ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
361         use rustc::mir::UnOp::*;
362
363         let layout = val.layout;
364         let val = val.to_scalar()?;
365         trace!("Running unary op {:?}: {:?} ({:?})", un_op, val, layout.ty);
366
367         match layout.ty.kind {
368             ty::Bool => {
369                 let val = val.to_bool()?;
370                 let res = match un_op {
371                     Not => !val,
372                     _ => bug!("Invalid bool op {:?}", un_op),
373                 };
374                 Ok(ImmTy::from_scalar(Scalar::from_bool(res), self.layout_of(self.tcx.types.bool)?))
375             }
376             ty::Float(fty) => {
377                 let res = match (un_op, fty) {
378                     (Neg, FloatTy::F32) => Scalar::from_f32(-val.to_f32()?),
379                     (Neg, FloatTy::F64) => Scalar::from_f64(-val.to_f64()?),
380                     _ => bug!("Invalid float op {:?}", un_op),
381                 };
382                 Ok(ImmTy::from_scalar(res, layout))
383             }
384             _ => {
385                 assert!(layout.ty.is_integral());
386                 let val = self.force_bits(val, layout.size)?;
387                 let res = match un_op {
388                     Not => !val,
389                     Neg => {
390                         assert!(layout.abi.is_signed());
391                         (-(val as i128)) as u128
392                     }
393                 };
394                 // res needs tuncating
395                 Ok(ImmTy::from_uint(self.truncate(res, layout), layout))
396             }
397         }
398     }
399 }