]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/interpret/intrinsics.rs
review comments
[rust.git] / compiler / rustc_mir / src / 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 std::convert::TryFrom;
6
7 use rustc_hir::def_id::DefId;
8 use rustc_middle::mir::{
9     self,
10     interpret::{uabs, ConstValue, GlobalId, InterpResult, Scalar},
11     BinOp,
12 };
13 use rustc_middle::ty;
14 use rustc_middle::ty::subst::SubstsRef;
15 use rustc_middle::ty::{Ty, TyCtxt};
16 use rustc_span::symbol::{sym, Symbol};
17 use rustc_target::abi::{Abi, Align, LayoutOf as _, Primitive, Size};
18
19 use super::{
20     util::ensure_monomorphic_enough, CheckInAllocMsg, ImmTy, InterpCx, Machine, MemoryKind, OpTy,
21     PlaceTy,
22 };
23
24 mod caller_location;
25 mod type_name;
26
27 fn numeric_intrinsic<'tcx, Tag>(
28     name: Symbol,
29     bits: u128,
30     kind: Primitive,
31 ) -> InterpResult<'tcx, Scalar<Tag>> {
32     let size = match kind {
33         Primitive::Int(integer, _) => integer.size(),
34         _ => bug!("invalid `{}` argument: {:?}", name, bits),
35     };
36     let extra = 128 - u128::from(size.bits());
37     let bits_out = match name {
38         sym::ctpop => u128::from(bits.count_ones()),
39         sym::ctlz => u128::from(bits.leading_zeros()) - extra,
40         sym::cttz => u128::from((bits << extra).trailing_zeros()) - extra,
41         sym::bswap => (bits << extra).swap_bytes(),
42         sym::bitreverse => (bits << extra).reverse_bits(),
43         _ => bug!("not a numeric intrinsic: {}", name),
44     };
45     Ok(Scalar::from_uint(bits_out, size))
46 }
47
48 /// The logic for all nullary intrinsics is implemented here. These intrinsics don't get evaluated
49 /// inside an `InterpCx` and instead have their value computed directly from rustc internal info.
50 crate fn eval_nullary_intrinsic<'tcx>(
51     tcx: TyCtxt<'tcx>,
52     param_env: ty::ParamEnv<'tcx>,
53     def_id: DefId,
54     substs: SubstsRef<'tcx>,
55 ) -> InterpResult<'tcx, ConstValue<'tcx>> {
56     let tp_ty = substs.type_at(0);
57     let name = tcx.item_name(def_id);
58     Ok(match name {
59         sym::type_name => {
60             ensure_monomorphic_enough(tcx, tp_ty)?;
61             let alloc = type_name::alloc_type_name(tcx, tp_ty);
62             ConstValue::Slice { data: alloc, start: 0, end: alloc.len() }
63         }
64         sym::needs_drop => ConstValue::from_bool(tp_ty.needs_drop(tcx, param_env)),
65         sym::size_of | sym::min_align_of | sym::pref_align_of => {
66             let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
67             let n = match name {
68                 sym::pref_align_of => layout.align.pref.bytes(),
69                 sym::min_align_of => layout.align.abi.bytes(),
70                 sym::size_of => layout.size.bytes(),
71                 _ => bug!(),
72             };
73             ConstValue::from_machine_usize(n, &tcx)
74         }
75         sym::type_id => {
76             ensure_monomorphic_enough(tcx, tp_ty)?;
77             ConstValue::from_u64(tcx.type_id_hash(tp_ty))
78         }
79         sym::variant_count => match tp_ty.kind() {
80             ty::Adt(ref adt, _) => ConstValue::from_machine_usize(adt.variants.len() as u64, &tcx),
81             ty::Projection(_)
82             | ty::Opaque(_, _)
83             | ty::Param(_)
84             | ty::Bound(_, _)
85             | ty::Placeholder(_)
86             | ty::Infer(_) => throw_inval!(TooGeneric),
87             ty::Bool
88             | ty::Char
89             | ty::Int(_)
90             | ty::Uint(_)
91             | ty::Float(_)
92             | ty::Foreign(_)
93             | ty::Str
94             | ty::Array(_, _)
95             | ty::Slice(_)
96             | ty::RawPtr(_)
97             | ty::Ref(_, _, _)
98             | ty::FnDef(_, _)
99             | ty::FnPtr(_)
100             | ty::Dynamic(_, _)
101             | ty::Closure(_, _)
102             | ty::Generator(_, _, _)
103             | ty::GeneratorWitness(_)
104             | ty::Never
105             | ty::Tuple(_)
106             | ty::Error(_) => ConstValue::from_machine_usize(0u64, &tcx),
107         },
108         other => bug!("`{}` is not a zero arg intrinsic", other),
109     })
110 }
111
112 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
113     /// Returns `true` if emulation happened.
114     /// Here we implement the intrinsics that are common to all Miri instances; individual machines can add their own
115     /// intrinsic handling.
116     pub fn emulate_intrinsic(
117         &mut self,
118         instance: ty::Instance<'tcx>,
119         args: &[OpTy<'tcx, M::PointerTag>],
120         ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
121     ) -> InterpResult<'tcx, bool> {
122         let substs = instance.substs;
123         let intrinsic_name = self.tcx.item_name(instance.def_id());
124
125         // First handle intrinsics without return place.
126         let (dest, ret) = match ret {
127             None => match intrinsic_name {
128                 sym::transmute => throw_ub_format!("transmuting to uninhabited type"),
129                 sym::unreachable => throw_ub!(Unreachable),
130                 sym::abort => M::abort(self)?,
131                 // Unsupported diverging intrinsic.
132                 _ => return Ok(false),
133             },
134             Some(p) => p,
135         };
136
137         // Keep the patterns in this match ordered the same as the list in
138         // `src/librustc_middle/ty/constness.rs`
139         match intrinsic_name {
140             sym::caller_location => {
141                 let span = self.find_closest_untracked_caller_location();
142                 let location = self.alloc_caller_location_for_span(span);
143                 self.write_scalar(location.ptr, dest)?;
144             }
145
146             sym::min_align_of_val | sym::size_of_val => {
147                 let place = self.deref_operand(args[0])?;
148                 let (size, align) = self
149                     .size_and_align_of(place.meta, place.layout)?
150                     .ok_or_else(|| err_unsup_format!("`extern type` does not have known layout"))?;
151
152                 let result = match intrinsic_name {
153                     sym::min_align_of_val => align.bytes(),
154                     sym::size_of_val => size.bytes(),
155                     _ => bug!(),
156                 };
157
158                 self.write_scalar(Scalar::from_machine_usize(result, self), dest)?;
159             }
160
161             sym::min_align_of
162             | sym::pref_align_of
163             | sym::needs_drop
164             | sym::size_of
165             | sym::type_id
166             | sym::type_name
167             | sym::variant_count => {
168                 let gid = GlobalId { instance, promoted: None };
169                 let ty = match intrinsic_name {
170                     sym::min_align_of | sym::pref_align_of | sym::size_of | sym::variant_count => {
171                         self.tcx.types.usize
172                     }
173                     sym::needs_drop => self.tcx.types.bool,
174                     sym::type_id => self.tcx.types.u64,
175                     sym::type_name => self.tcx.mk_static_str(),
176                     _ => bug!("already checked for nullary intrinsics"),
177                 };
178                 let val =
179                     self.tcx.const_eval_global_id(self.param_env, gid, Some(self.tcx.span))?;
180                 let const_ = ty::Const { val: ty::ConstKind::Value(val), ty };
181                 let val = self.const_to_op(&const_, None)?;
182                 self.copy_op(val, dest)?;
183             }
184
185             sym::ctpop
186             | sym::cttz
187             | sym::cttz_nonzero
188             | sym::ctlz
189             | sym::ctlz_nonzero
190             | sym::bswap
191             | sym::bitreverse => {
192                 let ty = substs.type_at(0);
193                 let layout_of = self.layout_of(ty)?;
194                 let val = self.read_scalar(args[0])?.check_init()?;
195                 let bits = self.force_bits(val, layout_of.size)?;
196                 let kind = match layout_of.abi {
197                     Abi::Scalar(ref scalar) => scalar.value,
198                     _ => span_bug!(
199                         self.cur_span(),
200                         "{} called on invalid type {:?}",
201                         intrinsic_name,
202                         ty
203                     ),
204                 };
205                 let (nonzero, intrinsic_name) = match intrinsic_name {
206                     sym::cttz_nonzero => (true, sym::cttz),
207                     sym::ctlz_nonzero => (true, sym::ctlz),
208                     other => (false, other),
209                 };
210                 if nonzero && bits == 0 {
211                     throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
212                 }
213                 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
214                 self.write_scalar(out_val, dest)?;
215             }
216             sym::wrapping_add
217             | sym::wrapping_sub
218             | sym::wrapping_mul
219             | sym::add_with_overflow
220             | sym::sub_with_overflow
221             | sym::mul_with_overflow => {
222                 let lhs = self.read_immediate(args[0])?;
223                 let rhs = self.read_immediate(args[1])?;
224                 let (bin_op, ignore_overflow) = match intrinsic_name {
225                     sym::wrapping_add => (BinOp::Add, true),
226                     sym::wrapping_sub => (BinOp::Sub, true),
227                     sym::wrapping_mul => (BinOp::Mul, true),
228                     sym::add_with_overflow => (BinOp::Add, false),
229                     sym::sub_with_overflow => (BinOp::Sub, false),
230                     sym::mul_with_overflow => (BinOp::Mul, false),
231                     _ => bug!("Already checked for int ops"),
232                 };
233                 if ignore_overflow {
234                     self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
235                 } else {
236                     self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
237                 }
238             }
239             sym::saturating_add | sym::saturating_sub => {
240                 let l = self.read_immediate(args[0])?;
241                 let r = self.read_immediate(args[1])?;
242                 let is_add = intrinsic_name == sym::saturating_add;
243                 let (val, overflowed, _ty) =
244                     self.overflowing_binary_op(if is_add { BinOp::Add } else { BinOp::Sub }, l, r)?;
245                 let val = if overflowed {
246                     let num_bits = l.layout.size.bits();
247                     if l.layout.abi.is_signed() {
248                         // For signed ints the saturated value depends on the sign of the first
249                         // term since the sign of the second term can be inferred from this and
250                         // the fact that the operation has overflowed (if either is 0 no
251                         // overflow can occur)
252                         let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
253                         let first_term_positive = first_term & (1 << (num_bits - 1)) == 0;
254                         if first_term_positive {
255                             // Negative overflow not possible since the positive first term
256                             // can only increase an (in range) negative term for addition
257                             // or corresponding negated positive term for subtraction
258                             Scalar::from_uint(
259                                 (1u128 << (num_bits - 1)) - 1, // max positive
260                                 Size::from_bits(num_bits),
261                             )
262                         } else {
263                             // Positive overflow not possible for similar reason
264                             // max negative
265                             Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
266                         }
267                     } else {
268                         // unsigned
269                         if is_add {
270                             // max unsigned
271                             Scalar::from_uint(
272                                 u128::MAX >> (128 - num_bits),
273                                 Size::from_bits(num_bits),
274                             )
275                         } else {
276                             // underflow to 0
277                             Scalar::from_uint(0u128, Size::from_bits(num_bits))
278                         }
279                     }
280                 } else {
281                     val
282                 };
283                 self.write_scalar(val, dest)?;
284             }
285             sym::discriminant_value => {
286                 let place = self.deref_operand(args[0])?;
287                 let discr_val = self.read_discriminant(place.into())?.0;
288                 self.write_scalar(discr_val, dest)?;
289             }
290             sym::unchecked_shl
291             | sym::unchecked_shr
292             | sym::unchecked_add
293             | sym::unchecked_sub
294             | sym::unchecked_mul
295             | sym::unchecked_div
296             | sym::unchecked_rem => {
297                 let l = self.read_immediate(args[0])?;
298                 let r = self.read_immediate(args[1])?;
299                 let bin_op = match intrinsic_name {
300                     sym::unchecked_shl => BinOp::Shl,
301                     sym::unchecked_shr => BinOp::Shr,
302                     sym::unchecked_add => BinOp::Add,
303                     sym::unchecked_sub => BinOp::Sub,
304                     sym::unchecked_mul => BinOp::Mul,
305                     sym::unchecked_div => BinOp::Div,
306                     sym::unchecked_rem => BinOp::Rem,
307                     _ => bug!("Already checked for int ops"),
308                 };
309                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
310                 if overflowed {
311                     let layout = self.layout_of(substs.type_at(0))?;
312                     let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
313                     if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
314                         throw_ub_format!("overflowing shift by {} in `{}`", r_val, intrinsic_name);
315                     } else {
316                         throw_ub_format!("overflow executing `{}`", intrinsic_name);
317                     }
318                 }
319                 self.write_scalar(val, dest)?;
320             }
321             sym::rotate_left | sym::rotate_right => {
322                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
323                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
324                 let layout = self.layout_of(substs.type_at(0))?;
325                 let val = self.read_scalar(args[0])?.check_init()?;
326                 let val_bits = self.force_bits(val, layout.size)?;
327                 let raw_shift = self.read_scalar(args[1])?.check_init()?;
328                 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
329                 let width_bits = u128::from(layout.size.bits());
330                 let shift_bits = raw_shift_bits % width_bits;
331                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
332                 let result_bits = if intrinsic_name == sym::rotate_left {
333                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
334                 } else {
335                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
336                 };
337                 let truncated_bits = self.truncate(result_bits, layout);
338                 let result = Scalar::from_uint(truncated_bits, layout.size);
339                 self.write_scalar(result, dest)?;
340             }
341             sym::const_allocate => {
342                 let size = self.read_scalar(args[0])?.to_machine_usize(self)?;
343                 let align = self.read_scalar(args[1])?.to_machine_usize(self)?;
344
345                 let align = match Align::from_bytes(align) {
346                     Ok(a) => a,
347                     Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
348                 };
349
350                 let ptr =
351                     self.memory.allocate(Size::from_bytes(size as u64), align, MemoryKind::Heap);
352                 self.write_scalar(Scalar::Ptr(ptr), dest)?;
353             }
354             sym::offset => {
355                 let ptr = self.read_scalar(args[0])?.check_init()?;
356                 let offset_count = self.read_scalar(args[1])?.to_machine_isize(self)?;
357                 let pointee_ty = substs.type_at(0);
358
359                 let offset_ptr = self.ptr_offset_inbounds(ptr, pointee_ty, offset_count)?;
360                 self.write_scalar(offset_ptr, dest)?;
361             }
362             sym::arith_offset => {
363                 let ptr = self.read_scalar(args[0])?.check_init()?;
364                 let offset_count = self.read_scalar(args[1])?.to_machine_isize(self)?;
365                 let pointee_ty = substs.type_at(0);
366
367                 let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
368                 let offset_bytes = offset_count.wrapping_mul(pointee_size);
369                 let offset_ptr = ptr.ptr_wrapping_signed_offset(offset_bytes, self);
370                 self.write_scalar(offset_ptr, dest)?;
371             }
372             sym::ptr_offset_from => {
373                 let a = self.read_immediate(args[0])?.to_scalar()?;
374                 let b = self.read_immediate(args[1])?.to_scalar()?;
375
376                 // Special case: if both scalars are *equal integers*
377                 // and not NULL, we pretend there is an allocation of size 0 right there,
378                 // and their offset is 0. (There's never a valid object at NULL, making it an
379                 // exception from the exception.)
380                 // This is the dual to the special exception for offset-by-0
381                 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
382                 //
383                 // Control flow is weird because we cannot early-return (to reach the
384                 // `go_to_block` at the end).
385                 let done = if a.is_bits() && b.is_bits() {
386                     let a = a.to_machine_usize(self)?;
387                     let b = b.to_machine_usize(self)?;
388                     if a == b && a != 0 {
389                         self.write_scalar(Scalar::from_machine_isize(0, self), dest)?;
390                         true
391                     } else {
392                         false
393                     }
394                 } else {
395                     false
396                 };
397
398                 if !done {
399                     // General case: we need two pointers.
400                     let a = self.force_ptr(a)?;
401                     let b = self.force_ptr(b)?;
402                     if a.alloc_id != b.alloc_id {
403                         throw_ub_format!(
404                             "ptr_offset_from cannot compute offset of pointers into different \
405                             allocations.",
406                         );
407                     }
408                     let usize_layout = self.layout_of(self.tcx.types.usize)?;
409                     let isize_layout = self.layout_of(self.tcx.types.isize)?;
410                     let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
411                     let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
412                     let (val, _overflowed, _ty) =
413                         self.overflowing_binary_op(BinOp::Sub, a_offset, b_offset)?;
414                     let pointee_layout = self.layout_of(substs.type_at(0))?;
415                     let val = ImmTy::from_scalar(val, isize_layout);
416                     let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
417                     self.exact_div(val, size, dest)?;
418                 }
419             }
420
421             sym::transmute => {
422                 self.copy_op_transmute(args[0], dest)?;
423             }
424             sym::simd_insert => {
425                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
426                 let elem = args[2];
427                 let input = args[0];
428                 let (len, e_ty) = input.layout.ty.simd_size_and_type(*self.tcx);
429                 assert!(
430                     index < len,
431                     "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
432                     index,
433                     e_ty,
434                     len
435                 );
436                 assert_eq!(
437                     input.layout, dest.layout,
438                     "Return type `{}` must match vector type `{}`",
439                     dest.layout.ty, input.layout.ty
440                 );
441                 assert_eq!(
442                     elem.layout.ty, e_ty,
443                     "Scalar element type `{}` must match vector element type `{}`",
444                     elem.layout.ty, e_ty
445                 );
446
447                 for i in 0..len {
448                     let place = self.place_index(dest, i)?;
449                     let value = if i == index { elem } else { self.operand_index(input, i)? };
450                     self.copy_op(value, place)?;
451                 }
452             }
453             sym::simd_extract => {
454                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
455                 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(*self.tcx);
456                 assert!(
457                     index < len,
458                     "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
459                     index,
460                     e_ty,
461                     len
462                 );
463                 assert_eq!(
464                     e_ty, dest.layout.ty,
465                     "Return type `{}` must match vector element type `{}`",
466                     dest.layout.ty, e_ty
467                 );
468                 self.copy_op(self.operand_index(args[0], index)?, dest)?;
469             }
470             sym::likely | sym::unlikely => {
471                 // These just return their argument
472                 self.copy_op(args[0], dest)?;
473             }
474             sym::assume => {
475                 let cond = self.read_scalar(args[0])?.check_init()?.to_bool()?;
476                 if !cond {
477                     throw_ub_format!("`assume` intrinsic called with `false`");
478                 }
479             }
480             _ => return Ok(false),
481         }
482
483         trace!("{:?}", self.dump_place(*dest));
484         self.go_to_block(ret);
485         Ok(true)
486     }
487
488     pub fn exact_div(
489         &mut self,
490         a: ImmTy<'tcx, M::PointerTag>,
491         b: ImmTy<'tcx, M::PointerTag>,
492         dest: PlaceTy<'tcx, M::PointerTag>,
493     ) -> InterpResult<'tcx> {
494         // Performs an exact division, resulting in undefined behavior where
495         // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
496         // First, check x % y != 0 (or if that computation overflows).
497         let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, a, b)?;
498         if overflow || res.assert_bits(a.layout.size) != 0 {
499             // Then, check if `b` is -1, which is the "MIN / -1" case.
500             let minus1 = Scalar::from_int(-1, dest.layout.size);
501             let b_scalar = b.to_scalar().unwrap();
502             if b_scalar == minus1 {
503                 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
504             } else {
505                 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b,)
506             }
507         }
508         // `Rem` says this is all right, so we can let `Div` do its job.
509         self.binop_ignore_overflow(BinOp::Div, a, b, dest)
510     }
511
512     /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
513     /// allocation. For integer pointers, we consider each of them their own tiny allocation of size
514     /// 0, so offset-by-0 (and only 0) is okay -- except that NULL cannot be offset by _any_ value.
515     pub fn ptr_offset_inbounds(
516         &self,
517         ptr: Scalar<M::PointerTag>,
518         pointee_ty: Ty<'tcx>,
519         offset_count: i64,
520     ) -> InterpResult<'tcx, Scalar<M::PointerTag>> {
521         // We cannot overflow i64 as a type's size must be <= isize::MAX.
522         let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
523         // The computed offset, in bytes, cannot overflow an isize.
524         let offset_bytes =
525             offset_count.checked_mul(pointee_size).ok_or(err_ub!(PointerArithOverflow))?;
526         // The offset being in bounds cannot rely on "wrapping around" the address space.
527         // So, first rule out overflows in the pointer arithmetic.
528         let offset_ptr = ptr.ptr_signed_offset(offset_bytes, self)?;
529         // ptr and offset_ptr must be in bounds of the same allocated object. This means all of the
530         // memory between these pointers must be accessible. Note that we do not require the
531         // pointers to be properly aligned (unlike a read/write operation).
532         let min_ptr = if offset_bytes >= 0 { ptr } else { offset_ptr };
533         let size: u64 = uabs(offset_bytes);
534         // This call handles checking for integer/NULL pointers.
535         self.memory.check_ptr_access_align(
536             min_ptr,
537             Size::from_bytes(size),
538             None,
539             CheckInAllocMsg::InboundsTest,
540         )?;
541         Ok(offset_ptr)
542     }
543 }