1 //! Intrinsics and other functions that the miri engine executes without
2 //! looking at their MIR. Intrinsics/functions supported here are shared by CTFE
5 use std::convert::TryFrom;
7 use rustc_hir::def_id::DefId;
8 use rustc_middle::mir::{
10 interpret::{uabs, ConstValue, GlobalId, InterpResult, Scalar},
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};
20 util::ensure_monomorphic_enough, CheckInAllocMsg, ImmTy, InterpCx, Machine, MemoryKind, OpTy,
27 fn numeric_intrinsic<'tcx, Tag>(
31 ) -> InterpResult<'tcx, Scalar<Tag>> {
32 let size = match kind {
33 Primitive::Int(integer, _) => integer.size(),
34 _ => bug!("invalid `{}` argument: {:?}", name, bits),
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),
45 Ok(Scalar::from_uint(bits_out, size))
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>(
52 param_env: ty::ParamEnv<'tcx>,
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);
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() }
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)))?;
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(),
73 ConstValue::from_machine_usize(n, &tcx)
76 ensure_monomorphic_enough(tcx, tp_ty)?;
77 ConstValue::from_u64(tcx.type_id_hash(tp_ty))
79 sym::variant_count => match tp_ty.kind() {
80 ty::Adt(ref adt, _) => ConstValue::from_machine_usize(adt.variants.len() as u64, &tcx),
86 | ty::Infer(_) => throw_inval!(TooGeneric),
102 | ty::Generator(_, _, _)
103 | ty::GeneratorWitness(_)
106 | ty::Error(_) => ConstValue::from_machine_usize(0u64, &tcx),
108 other => bug!("`{}` is not a zero arg intrinsic", other),
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(
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());
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),
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)?;
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"))?;
152 let result = match intrinsic_name {
153 sym::min_align_of_val => align.bytes(),
154 sym::size_of_val => size.bytes(),
158 self.write_scalar(Scalar::from_machine_usize(result, self), dest)?;
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 => {
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"),
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)?;
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,
200 "{} called on invalid type {:?}",
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),
210 if nonzero && bits == 0 {
211 throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
213 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
214 self.write_scalar(out_val, dest)?;
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"),
234 self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
236 self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
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
259 (1u128 << (num_bits - 1)) - 1, // max positive
260 Size::from_bits(num_bits),
263 // Positive overflow not possible for similar reason
265 Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
272 u128::MAX >> (128 - num_bits),
273 Size::from_bits(num_bits),
277 Scalar::from_uint(0u128, Size::from_bits(num_bits))
283 self.write_scalar(val, dest)?;
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)?;
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"),
309 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
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);
316 throw_ub_format!("overflow executing `{}`", intrinsic_name);
319 self.write_scalar(val, dest)?;
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)
335 (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
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)?;
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)?;
345 let align = match Align::from_bytes(align) {
347 Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
351 self.memory.allocate(Size::from_bytes(size as u64), align, MemoryKind::Heap);
352 self.write_scalar(Scalar::Ptr(ptr), dest)?;
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);
359 let offset_ptr = self.ptr_offset_inbounds(ptr, pointee_ty, offset_count)?;
360 self.write_scalar(offset_ptr, dest)?;
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);
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)?;
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()?;
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`).
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)?;
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 {
404 "ptr_offset_from cannot compute offset of pointers into different \
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)?;
422 self.copy_op_transmute(args[0], dest)?;
424 sym::simd_insert => {
425 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
428 let (len, e_ty) = input.layout.ty.simd_size_and_type(*self.tcx);
431 "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
437 input.layout, dest.layout,
438 "Return type `{}` must match vector type `{}`",
439 dest.layout.ty, input.layout.ty
442 elem.layout.ty, e_ty,
443 "Scalar element type `{}` must match vector element type `{}`",
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)?;
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);
458 "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
464 e_ty, dest.layout.ty,
465 "Return type `{}` must match vector element type `{}`",
468 self.copy_op(self.operand_index(args[0], index)?, dest)?;
470 sym::likely | sym::unlikely => {
471 // These just return their argument
472 self.copy_op(args[0], dest)?;
475 let cond = self.read_scalar(args[0])?.check_init()?.to_bool()?;
477 throw_ub_format!("`assume` intrinsic called with `false`");
480 _ => return Ok(false),
483 trace!("{:?}", self.dump_place(*dest));
484 self.go_to_block(ret);
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")
505 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b,)
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)
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(
517 ptr: Scalar<M::PointerTag>,
518 pointee_ty: Ty<'tcx>,
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.
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(
537 Size::from_bytes(size),
539 CheckInAllocMsg::InboundsTest,