1 //! Intrinsics and other functions that the miri engine executes without
2 //! looking at their MIR. Intrinsics/functions supported here are shared by CTFE
7 interpret::{ConstValue, GlobalId, InterpResult, Scalar},
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};
18 use super::{ImmTy, InterpCx, Machine, OpTy, PlaceTy};
23 fn numeric_intrinsic<'tcx, Tag>(
27 ) -> InterpResult<'tcx, Scalar<Tag>> {
28 let size = match kind {
29 Primitive::Int(integer, _) => integer.size(),
30 _ => bug!("invalid `{}` argument: {:?}", name, bits),
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),
41 Ok(Scalar::from_uint(bits_out, size))
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>(
48 param_env: ty::ParamEnv<'tcx>,
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);
56 let alloc = type_name::alloc_type_name(tcx, tp_ty);
57 ConstValue::Slice { data: alloc, start: 0, end: alloc.len() }
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)))?;
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(),
68 ConstValue::from_machine_usize(&tcx, n)
70 sym::type_id => ConstValue::from_u64(tcx.type_id_hash(tp_ty).into()),
71 other => bug!("`{}` is not a zero arg intrinsic", other),
75 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
76 /// Returns `true` if emulation happened.
77 pub fn emulate_intrinsic(
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());
87 // We currently do not handle any intrinsics that are *allowed* to diverge,
88 // but `transmute` could lack a return place in case of UB.
89 let (dest, ret) = match ret {
91 None => match intrinsic_name {
92 sym::transmute => throw_ub!(Unreachable),
93 _ => return Ok(false),
97 // Keep the patterns in this match ordered the same as the list in
98 // `src/librustc/ty/constness.rs`
99 match intrinsic_name {
100 sym::caller_location => {
101 let span = self.find_closest_untracked_caller_location().unwrap_or(span);
102 let location = self.alloc_caller_location_for_span(span);
103 self.write_scalar(location.ptr, dest)?;
111 | sym::type_name => {
112 let gid = GlobalId { instance, promoted: None };
113 let ty = instance.ty_env(*self.tcx, self.param_env);
114 let val = self.const_eval(gid, ty)?;
115 self.copy_op(val, dest)?;
124 | sym::bitreverse => {
125 let ty = substs.type_at(0);
126 let layout_of = self.layout_of(ty)?;
127 let val = self.read_scalar(args[0])?.not_undef()?;
128 let bits = self.force_bits(val, layout_of.size)?;
129 let kind = match layout_of.abi {
130 ty::layout::Abi::Scalar(ref scalar) => scalar.value,
131 _ => throw_unsup!(TypeNotPrimitive(ty)),
133 let (nonzero, intrinsic_name) = match intrinsic_name {
134 sym::cttz_nonzero => (true, sym::cttz),
135 sym::ctlz_nonzero => (true, sym::ctlz),
136 other => (false, other),
138 if nonzero && bits == 0 {
139 throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
141 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
142 self.write_scalar(out_val, dest)?;
147 | sym::add_with_overflow
148 | sym::sub_with_overflow
149 | sym::mul_with_overflow => {
150 let lhs = self.read_immediate(args[0])?;
151 let rhs = self.read_immediate(args[1])?;
152 let (bin_op, ignore_overflow) = match intrinsic_name {
153 sym::wrapping_add => (BinOp::Add, true),
154 sym::wrapping_sub => (BinOp::Sub, true),
155 sym::wrapping_mul => (BinOp::Mul, true),
156 sym::add_with_overflow => (BinOp::Add, false),
157 sym::sub_with_overflow => (BinOp::Sub, false),
158 sym::mul_with_overflow => (BinOp::Mul, false),
159 _ => bug!("Already checked for int ops"),
162 self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
164 self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
167 sym::saturating_add | sym::saturating_sub => {
168 let l = self.read_immediate(args[0])?;
169 let r = self.read_immediate(args[1])?;
170 let is_add = intrinsic_name == sym::saturating_add;
171 let (val, overflowed, _ty) =
172 self.overflowing_binary_op(if is_add { BinOp::Add } else { BinOp::Sub }, l, r)?;
173 let val = if overflowed {
174 let num_bits = l.layout.size.bits();
175 if l.layout.abi.is_signed() {
176 // For signed ints the saturated value depends on the sign of the first
177 // term since the sign of the second term can be inferred from this and
178 // the fact that the operation has overflowed (if either is 0 no
179 // overflow can occur)
180 let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
181 let first_term_positive = first_term & (1 << (num_bits - 1)) == 0;
182 if first_term_positive {
183 // Negative overflow not possible since the positive first term
184 // can only increase an (in range) negative term for addition
185 // or corresponding negated positive term for subtraction
187 (1u128 << (num_bits - 1)) - 1, // max positive
188 Size::from_bits(num_bits),
191 // Positive overflow not possible for similar reason
193 Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
200 u128::max_value() >> (128 - num_bits),
201 Size::from_bits(num_bits),
205 Scalar::from_uint(0u128, Size::from_bits(num_bits))
211 self.write_scalar(val, dest)?;
219 | sym::unchecked_rem => {
220 let l = self.read_immediate(args[0])?;
221 let r = self.read_immediate(args[1])?;
222 let bin_op = match intrinsic_name {
223 sym::unchecked_shl => BinOp::Shl,
224 sym::unchecked_shr => BinOp::Shr,
225 sym::unchecked_add => BinOp::Add,
226 sym::unchecked_sub => BinOp::Sub,
227 sym::unchecked_mul => BinOp::Mul,
228 sym::unchecked_div => BinOp::Div,
229 sym::unchecked_rem => BinOp::Rem,
230 _ => bug!("Already checked for int ops"),
232 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
234 let layout = self.layout_of(substs.type_at(0))?;
235 let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
236 if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
237 throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
239 throw_ub_format!("Overflow executing `{}`", intrinsic_name);
242 self.write_scalar(val, dest)?;
244 sym::rotate_left | sym::rotate_right => {
245 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
246 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
247 let layout = self.layout_of(substs.type_at(0))?;
248 let val = self.read_scalar(args[0])?.not_undef()?;
249 let val_bits = self.force_bits(val, layout.size)?;
250 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
251 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
252 let width_bits = layout.size.bits() as u128;
253 let shift_bits = raw_shift_bits % width_bits;
254 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
255 let result_bits = if intrinsic_name == sym::rotate_left {
256 (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
258 (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
260 let truncated_bits = self.truncate(result_bits, layout);
261 let result = Scalar::from_uint(truncated_bits, layout.size);
262 self.write_scalar(result, dest)?;
265 sym::ptr_offset_from => {
266 let isize_layout = self.layout_of(self.tcx.types.isize)?;
267 let a = self.read_immediate(args[0])?.to_scalar()?;
268 let b = self.read_immediate(args[1])?.to_scalar()?;
270 // Special case: if both scalars are *equal integers*
271 // and not NULL, we pretend there is an allocation of size 0 right there,
272 // and their offset is 0. (There's never a valid object at NULL, making it an
273 // exception from the exception.)
274 // This is the dual to the special exception for offset-by-0
275 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
277 // Control flow is weird because we cannot early-return (to reach the
278 // `go_to_block` at the end).
279 let done = if a.is_bits() && b.is_bits() {
280 let a = a.to_machine_usize(self)?;
281 let b = b.to_machine_usize(self)?;
282 if a == b && a != 0 {
283 self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
293 // General case: we need two pointers.
294 let a = self.force_ptr(a)?;
295 let b = self.force_ptr(b)?;
296 if a.alloc_id != b.alloc_id {
298 "ptr_offset_from cannot compute offset of pointers into different \
302 let usize_layout = self.layout_of(self.tcx.types.usize)?;
303 let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
304 let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
305 let (val, _overflowed, _ty) =
306 self.overflowing_binary_op(BinOp::Sub, a_offset, b_offset)?;
307 let pointee_layout = self.layout_of(substs.type_at(0))?;
308 let val = ImmTy::from_scalar(val, isize_layout);
309 let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
310 self.exact_div(val, size, dest)?;
315 self.copy_op_transmute(args[0], dest)?;
317 sym::simd_insert => {
318 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
321 let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx.tcx);
324 "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
330 input.layout, dest.layout,
331 "Return type `{}` must match vector type `{}`",
332 dest.layout.ty, input.layout.ty
335 elem.layout.ty, e_ty,
336 "Scalar element type `{}` must match vector element type `{}`",
341 let place = self.place_field(dest, i)?;
342 let value = if i == index { elem } else { self.operand_field(input, i)? };
343 self.copy_op(value, place)?;
346 sym::simd_extract => {
347 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
348 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx);
351 "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
357 e_ty, dest.layout.ty,
358 "Return type `{}` must match vector element type `{}`",
361 self.copy_op(self.operand_field(args[0], index)?, dest)?;
363 _ => return Ok(false),
366 self.dump_place(*dest);
367 self.go_to_block(ret);
373 a: ImmTy<'tcx, M::PointerTag>,
374 b: ImmTy<'tcx, M::PointerTag>,
375 dest: PlaceTy<'tcx, M::PointerTag>,
376 ) -> InterpResult<'tcx> {
377 // Performs an exact division, resulting in undefined behavior where
378 // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
379 // First, check x % y != 0 (or if that computation overflows).
380 let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, a, b)?;
381 if overflow || res.to_bits(a.layout.size)? != 0 {
382 // Then, check if `b` is -1, which is the "min_value / -1" case.
383 let minus1 = Scalar::from_int(-1, dest.layout.size);
384 let b_scalar = b.to_scalar().unwrap();
385 if b_scalar == minus1 {
386 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
388 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b,)
391 // `Rem` says this is all right, so we can let `Div` do its job.
392 self.binop_ignore_overflow(BinOp::Div, a, b, dest)