]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/intrinsics.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / librustc_mir / 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 rustc::mir::{
6     self,
7     interpret::{ConstValue, GlobalId, InterpResult, Scalar},
8     BinOp,
9 };
10 use rustc::ty;
11 use rustc::ty::layout::{LayoutOf, Primitive, Size};
12 use rustc::ty::subst::SubstsRef;
13 use rustc::ty::TyCtxt;
14 use rustc_hir::def_id::DefId;
15 use rustc_span::symbol::{sym, Symbol};
16 use rustc_span::Span;
17
18 use super::{ImmTy, InterpCx, Machine, OpTy, PlaceTy};
19
20 mod caller_location;
21 mod type_name;
22
23 fn numeric_intrinsic<'tcx, Tag>(
24     name: Symbol,
25     bits: u128,
26     kind: Primitive,
27 ) -> InterpResult<'tcx, Scalar<Tag>> {
28     let size = match kind {
29         Primitive::Int(integer, _) => integer.size(),
30         _ => bug!("invalid `{}` argument: {:?}", name, bits),
31     };
32     let extra = 128 - size.bits() as u128;
33     let bits_out = match name {
34         sym::ctpop => bits.count_ones() as u128,
35         sym::ctlz => bits.leading_zeros() as u128 - extra,
36         sym::cttz => (bits << extra).trailing_zeros() as u128 - extra,
37         sym::bswap => (bits << extra).swap_bytes(),
38         sym::bitreverse => (bits << extra).reverse_bits(),
39         _ => bug!("not a numeric intrinsic: {}", name),
40     };
41     Ok(Scalar::from_uint(bits_out, size))
42 }
43
44 /// The logic for all nullary intrinsics is implemented here. These intrinsics don't get evaluated
45 /// inside an `InterpCx` and instead have their value computed directly from rustc internal info.
46 crate fn eval_nullary_intrinsic<'tcx>(
47     tcx: TyCtxt<'tcx>,
48     param_env: ty::ParamEnv<'tcx>,
49     def_id: DefId,
50     substs: SubstsRef<'tcx>,
51 ) -> InterpResult<'tcx, ConstValue<'tcx>> {
52     let tp_ty = substs.type_at(0);
53     let name = tcx.item_name(def_id);
54     Ok(match name {
55         sym::type_name => {
56             let alloc = type_name::alloc_type_name(tcx, tp_ty);
57             ConstValue::Slice { data: alloc, start: 0, end: alloc.len() }
58         }
59         sym::needs_drop => ConstValue::from_bool(tp_ty.needs_drop(tcx, param_env)),
60         sym::size_of | sym::min_align_of | sym::pref_align_of => {
61             let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
62             let n = match name {
63                 sym::pref_align_of => layout.align.pref.bytes(),
64                 sym::min_align_of => layout.align.abi.bytes(),
65                 sym::size_of => layout.size.bytes(),
66                 _ => bug!(),
67             };
68             ConstValue::from_machine_usize(n, &tcx)
69         }
70         sym::type_id => ConstValue::from_u64(tcx.type_id_hash(tp_ty)),
71         other => bug!("`{}` is not a zero arg intrinsic", other),
72     })
73 }
74
75 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
76     /// Returns `true` if emulation happened.
77     pub fn emulate_intrinsic(
78         &mut self,
79         span: Span,
80         instance: ty::Instance<'tcx>,
81         args: &[OpTy<'tcx, M::PointerTag>],
82         ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
83     ) -> InterpResult<'tcx, bool> {
84         let substs = instance.substs;
85         let intrinsic_name = self.tcx.item_name(instance.def_id());
86
87         // First handle intrinsics without return place.
88         let (dest, ret) = match ret {
89             None => match intrinsic_name {
90                 sym::transmute => throw_ub_format!("transmuting to uninhabited type"),
91                 sym::abort => M::abort(self)?,
92                 // Unsupported diverging intrinsic.
93                 _ => return Ok(false),
94             },
95             Some(p) => p,
96         };
97
98         // Keep the patterns in this match ordered the same as the list in
99         // `src/librustc/ty/constness.rs`
100         match intrinsic_name {
101             sym::caller_location => {
102                 let span = self.find_closest_untracked_caller_location().unwrap_or(span);
103                 let location = self.alloc_caller_location_for_span(span);
104                 self.write_scalar(location.ptr, dest)?;
105             }
106
107             sym::min_align_of
108             | sym::pref_align_of
109             | sym::needs_drop
110             | sym::size_of
111             | sym::type_id
112             | sym::type_name => {
113                 let gid = GlobalId { instance, promoted: None };
114                 let ty = match intrinsic_name {
115                     sym::min_align_of | sym::pref_align_of | sym::size_of => self.tcx.types.usize,
116                     sym::needs_drop => self.tcx.types.bool,
117                     sym::type_id => self.tcx.types.u64,
118                     sym::type_name => self.tcx.mk_static_str(),
119                     _ => span_bug!(span, "Already checked for nullary intrinsics"),
120                 };
121                 let val = self.const_eval(gid, ty)?;
122                 self.copy_op(val, dest)?;
123             }
124
125             sym::ctpop
126             | sym::cttz
127             | sym::cttz_nonzero
128             | sym::ctlz
129             | sym::ctlz_nonzero
130             | sym::bswap
131             | sym::bitreverse => {
132                 let ty = substs.type_at(0);
133                 let layout_of = self.layout_of(ty)?;
134                 let val = self.read_scalar(args[0])?.not_undef()?;
135                 let bits = self.force_bits(val, layout_of.size)?;
136                 let kind = match layout_of.abi {
137                     ty::layout::Abi::Scalar(ref scalar) => scalar.value,
138                     _ => bug!("{} called on invalid type {:?}", intrinsic_name, ty),
139                 };
140                 let (nonzero, intrinsic_name) = match intrinsic_name {
141                     sym::cttz_nonzero => (true, sym::cttz),
142                     sym::ctlz_nonzero => (true, sym::ctlz),
143                     other => (false, other),
144                 };
145                 if nonzero && bits == 0 {
146                     throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
147                 }
148                 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
149                 self.write_scalar(out_val, dest)?;
150             }
151             sym::wrapping_add
152             | sym::wrapping_sub
153             | sym::wrapping_mul
154             | sym::add_with_overflow
155             | sym::sub_with_overflow
156             | sym::mul_with_overflow => {
157                 let lhs = self.read_immediate(args[0])?;
158                 let rhs = self.read_immediate(args[1])?;
159                 let (bin_op, ignore_overflow) = match intrinsic_name {
160                     sym::wrapping_add => (BinOp::Add, true),
161                     sym::wrapping_sub => (BinOp::Sub, true),
162                     sym::wrapping_mul => (BinOp::Mul, true),
163                     sym::add_with_overflow => (BinOp::Add, false),
164                     sym::sub_with_overflow => (BinOp::Sub, false),
165                     sym::mul_with_overflow => (BinOp::Mul, false),
166                     _ => bug!("Already checked for int ops"),
167                 };
168                 if ignore_overflow {
169                     self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
170                 } else {
171                     self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
172                 }
173             }
174             sym::saturating_add | sym::saturating_sub => {
175                 let l = self.read_immediate(args[0])?;
176                 let r = self.read_immediate(args[1])?;
177                 let is_add = intrinsic_name == sym::saturating_add;
178                 let (val, overflowed, _ty) =
179                     self.overflowing_binary_op(if is_add { BinOp::Add } else { BinOp::Sub }, l, r)?;
180                 let val = if overflowed {
181                     let num_bits = l.layout.size.bits();
182                     if l.layout.abi.is_signed() {
183                         // For signed ints the saturated value depends on the sign of the first
184                         // term since the sign of the second term can be inferred from this and
185                         // the fact that the operation has overflowed (if either is 0 no
186                         // overflow can occur)
187                         let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
188                         let first_term_positive = first_term & (1 << (num_bits - 1)) == 0;
189                         if first_term_positive {
190                             // Negative overflow not possible since the positive first term
191                             // can only increase an (in range) negative term for addition
192                             // or corresponding negated positive term for subtraction
193                             Scalar::from_uint(
194                                 (1u128 << (num_bits - 1)) - 1, // max positive
195                                 Size::from_bits(num_bits),
196                             )
197                         } else {
198                             // Positive overflow not possible for similar reason
199                             // max negative
200                             Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
201                         }
202                     } else {
203                         // unsigned
204                         if is_add {
205                             // max unsigned
206                             Scalar::from_uint(
207                                 u128::MAX >> (128 - num_bits),
208                                 Size::from_bits(num_bits),
209                             )
210                         } else {
211                             // underflow to 0
212                             Scalar::from_uint(0u128, Size::from_bits(num_bits))
213                         }
214                     }
215                 } else {
216                     val
217                 };
218                 self.write_scalar(val, dest)?;
219             }
220             sym::discriminant_value => {
221                 let place = self.deref_operand(args[0])?;
222                 let discr_val = self.read_discriminant(place.into())?.0;
223                 self.write_scalar(Scalar::from_uint(discr_val, dest.layout.size), dest)?;
224             }
225             sym::unchecked_shl
226             | sym::unchecked_shr
227             | sym::unchecked_add
228             | sym::unchecked_sub
229             | sym::unchecked_mul
230             | sym::unchecked_div
231             | sym::unchecked_rem => {
232                 let l = self.read_immediate(args[0])?;
233                 let r = self.read_immediate(args[1])?;
234                 let bin_op = match intrinsic_name {
235                     sym::unchecked_shl => BinOp::Shl,
236                     sym::unchecked_shr => BinOp::Shr,
237                     sym::unchecked_add => BinOp::Add,
238                     sym::unchecked_sub => BinOp::Sub,
239                     sym::unchecked_mul => BinOp::Mul,
240                     sym::unchecked_div => BinOp::Div,
241                     sym::unchecked_rem => BinOp::Rem,
242                     _ => bug!("Already checked for int ops"),
243                 };
244                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
245                 if overflowed {
246                     let layout = self.layout_of(substs.type_at(0))?;
247                     let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
248                     if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
249                         throw_ub_format!("overflowing shift by {} in `{}`", r_val, intrinsic_name);
250                     } else {
251                         throw_ub_format!("overflow executing `{}`", intrinsic_name);
252                     }
253                 }
254                 self.write_scalar(val, dest)?;
255             }
256             sym::rotate_left | sym::rotate_right => {
257                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
258                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
259                 let layout = self.layout_of(substs.type_at(0))?;
260                 let val = self.read_scalar(args[0])?.not_undef()?;
261                 let val_bits = self.force_bits(val, layout.size)?;
262                 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
263                 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
264                 let width_bits = layout.size.bits() as u128;
265                 let shift_bits = raw_shift_bits % width_bits;
266                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
267                 let result_bits = if intrinsic_name == sym::rotate_left {
268                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
269                 } else {
270                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
271                 };
272                 let truncated_bits = self.truncate(result_bits, layout);
273                 let result = Scalar::from_uint(truncated_bits, layout.size);
274                 self.write_scalar(result, dest)?;
275             }
276
277             sym::ptr_offset_from => {
278                 let isize_layout = self.layout_of(self.tcx.types.isize)?;
279                 let a = self.read_immediate(args[0])?.to_scalar()?;
280                 let b = self.read_immediate(args[1])?.to_scalar()?;
281
282                 // Special case: if both scalars are *equal integers*
283                 // and not NULL, we pretend there is an allocation of size 0 right there,
284                 // and their offset is 0. (There's never a valid object at NULL, making it an
285                 // exception from the exception.)
286                 // This is the dual to the special exception for offset-by-0
287                 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
288                 //
289                 // Control flow is weird because we cannot early-return (to reach the
290                 // `go_to_block` at the end).
291                 let done = if a.is_bits() && b.is_bits() {
292                     let a = a.to_machine_usize(self)?;
293                     let b = b.to_machine_usize(self)?;
294                     if a == b && a != 0 {
295                         self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
296                         true
297                     } else {
298                         false
299                     }
300                 } else {
301                     false
302                 };
303
304                 if !done {
305                     // General case: we need two pointers.
306                     let a = self.force_ptr(a)?;
307                     let b = self.force_ptr(b)?;
308                     if a.alloc_id != b.alloc_id {
309                         throw_ub_format!(
310                             "ptr_offset_from cannot compute offset of pointers into different \
311                             allocations.",
312                         );
313                     }
314                     let usize_layout = self.layout_of(self.tcx.types.usize)?;
315                     let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
316                     let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
317                     let (val, _overflowed, _ty) =
318                         self.overflowing_binary_op(BinOp::Sub, a_offset, b_offset)?;
319                     let pointee_layout = self.layout_of(substs.type_at(0))?;
320                     let val = ImmTy::from_scalar(val, isize_layout);
321                     let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
322                     self.exact_div(val, size, dest)?;
323                 }
324             }
325
326             sym::transmute => {
327                 self.copy_op_transmute(args[0], dest)?;
328             }
329             sym::simd_insert => {
330                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
331                 let elem = args[2];
332                 let input = args[0];
333                 let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx.tcx);
334                 assert!(
335                     index < len,
336                     "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
337                     index,
338                     e_ty,
339                     len
340                 );
341                 assert_eq!(
342                     input.layout, dest.layout,
343                     "Return type `{}` must match vector type `{}`",
344                     dest.layout.ty, input.layout.ty
345                 );
346                 assert_eq!(
347                     elem.layout.ty, e_ty,
348                     "Scalar element type `{}` must match vector element type `{}`",
349                     elem.layout.ty, e_ty
350                 );
351
352                 for i in 0..len {
353                     let place = self.place_field(dest, i)?;
354                     let value = if i == index { elem } else { self.operand_field(input, i)? };
355                     self.copy_op(value, place)?;
356                 }
357             }
358             sym::simd_extract => {
359                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
360                 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx);
361                 assert!(
362                     index < len,
363                     "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
364                     index,
365                     e_ty,
366                     len
367                 );
368                 assert_eq!(
369                     e_ty, dest.layout.ty,
370                     "Return type `{}` must match vector element type `{}`",
371                     dest.layout.ty, e_ty
372                 );
373                 self.copy_op(self.operand_field(args[0], index)?, dest)?;
374             }
375             _ => return Ok(false),
376         }
377
378         self.dump_place(*dest);
379         self.go_to_block(ret);
380         Ok(true)
381     }
382
383     pub fn exact_div(
384         &mut self,
385         a: ImmTy<'tcx, M::PointerTag>,
386         b: ImmTy<'tcx, M::PointerTag>,
387         dest: PlaceTy<'tcx, M::PointerTag>,
388     ) -> InterpResult<'tcx> {
389         // Performs an exact division, resulting in undefined behavior where
390         // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
391         // First, check x % y != 0 (or if that computation overflows).
392         let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, a, b)?;
393         if overflow || res.assert_bits(a.layout.size) != 0 {
394             // Then, check if `b` is -1, which is the "MIN / -1" case.
395             let minus1 = Scalar::from_int(-1, dest.layout.size);
396             let b_scalar = b.to_scalar().unwrap();
397             if b_scalar == minus1 {
398                 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
399             } else {
400                 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b,)
401             }
402         }
403         // `Rem` says this is all right, so we can let `Div` do its job.
404         self.binop_ignore_overflow(BinOp::Div, a, b, dest)
405     }
406 }