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 syntax_pos::symbol::{sym, Symbol};
8 use rustc::ty::layout::{LayoutOf, Primitive, Size};
9 use rustc::ty::subst::SubstsRef;
10 use rustc::hir::def_id::DefId;
11 use rustc::ty::TyCtxt;
14 interpret::{InterpResult, Scalar, GlobalId, ConstValue}
18 Machine, PlaceTy, OpTy, InterpCx, ImmTy,
24 fn numeric_intrinsic<'tcx, Tag>(
28 ) -> InterpResult<'tcx, Scalar<Tag>> {
29 let size = match kind {
30 Primitive::Int(integer, _) => integer.size(),
31 _ => bug!("invalid `{}` argument: {:?}", name, bits),
33 let extra = 128 - size.bits() as u128;
34 let bits_out = match name {
35 sym::ctpop => bits.count_ones() as u128,
36 sym::ctlz => bits.leading_zeros() as u128 - extra,
37 sym::cttz => (bits << extra).trailing_zeros() as u128 - extra,
38 sym::bswap => (bits << extra).swap_bytes(),
39 sym::bitreverse => (bits << extra).reverse_bits(),
40 _ => bug!("not a numeric intrinsic: {}", name),
42 Ok(Scalar::from_uint(bits_out, size))
45 /// The logic for all nullary intrinsics is implemented here. These intrinsics don't get evaluated
46 /// inside an `InterpCx` and instead have their value computed directly from rustc internal info.
47 crate fn eval_nullary_intrinsic<'tcx>(
49 param_env: ty::ParamEnv<'tcx>,
51 substs: SubstsRef<'tcx>,
52 ) -> InterpResult<'tcx, &'tcx ty::Const<'tcx>> {
53 let tp_ty = substs.type_at(0);
54 let name = tcx.item_name(def_id);
57 let alloc = type_name::alloc_type_name(tcx, tp_ty);
58 tcx.mk_const(ty::Const {
59 val: ty::ConstKind::Value(ConstValue::Slice {
64 ty: tcx.mk_static_str(),
67 sym::needs_drop => ty::Const::from_bool(tcx, tp_ty.needs_drop(tcx, param_env)),
70 sym::pref_align_of => {
71 let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
73 sym::pref_align_of => layout.align.pref.bytes(),
74 sym::min_align_of => layout.align.abi.bytes(),
75 sym::size_of => layout.size.bytes(),
78 ty::Const::from_usize(tcx, n)
80 sym::type_id => ty::Const::from_bits(
82 tcx.type_id_hash(tp_ty).into(),
83 param_env.and(tcx.types.u64),
85 other => bug!("`{}` is not a zero arg intrinsic", other),
89 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
90 /// Returns `true` if emulation happened.
91 pub fn emulate_intrinsic(
94 instance: ty::Instance<'tcx>,
95 args: &[OpTy<'tcx, M::PointerTag>],
96 ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
97 ) -> InterpResult<'tcx, bool> {
98 let substs = instance.substs;
99 let intrinsic_name = self.tcx.item_name(instance.def_id());
101 // We currently do not handle any intrinsics that are *allowed* to diverge,
102 // but `transmute` could lack a return place in case of UB.
103 let (dest, ret) = match ret {
105 None => match intrinsic_name {
106 sym::transmute => throw_ub!(Unreachable),
107 _ => return Ok(false),
111 // Keep the patterns in this match ordered the same as the list in
112 // `src/librustc/ty/constness.rs`
113 match intrinsic_name {
114 sym::caller_location => {
115 let location = self.alloc_caller_location_for_span(span);
116 self.write_scalar(location.ptr, dest)?;
129 let val = self.tcx.const_eval(self.param_env.and(gid))?;
130 let val = self.eval_const_to_op(val, None)?;
131 self.copy_op(val, dest)?;
140 | sym::bitreverse => {
141 let ty = substs.type_at(0);
142 let layout_of = self.layout_of(ty)?;
143 let val = self.read_scalar(args[0])?.not_undef()?;
144 let bits = self.force_bits(val, layout_of.size)?;
145 let kind = match layout_of.abi {
146 ty::layout::Abi::Scalar(ref scalar) => scalar.value,
147 _ => throw_unsup!(TypeNotPrimitive(ty)),
149 let (nonzero, intrinsic_name) = match intrinsic_name {
150 sym::cttz_nonzero => (true, sym::cttz),
151 sym::ctlz_nonzero => (true, sym::ctlz),
152 other => (false, other),
154 if nonzero && bits == 0 {
155 throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
157 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
158 self.write_scalar(out_val, dest)?;
163 | sym::add_with_overflow
164 | sym::sub_with_overflow
165 | sym::mul_with_overflow => {
166 let lhs = self.read_immediate(args[0])?;
167 let rhs = self.read_immediate(args[1])?;
168 let (bin_op, ignore_overflow) = match intrinsic_name {
169 sym::wrapping_add => (BinOp::Add, true),
170 sym::wrapping_sub => (BinOp::Sub, true),
171 sym::wrapping_mul => (BinOp::Mul, true),
172 sym::add_with_overflow => (BinOp::Add, false),
173 sym::sub_with_overflow => (BinOp::Sub, false),
174 sym::mul_with_overflow => (BinOp::Mul, false),
175 _ => bug!("Already checked for int ops")
178 self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
180 self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
183 sym::saturating_add | sym::saturating_sub => {
184 let l = self.read_immediate(args[0])?;
185 let r = self.read_immediate(args[1])?;
186 let is_add = intrinsic_name == sym::saturating_add;
187 let (val, overflowed, _ty) = self.overflowing_binary_op(if is_add {
192 let val = if overflowed {
193 let num_bits = l.layout.size.bits();
194 if l.layout.abi.is_signed() {
195 // For signed ints the saturated value depends on the sign of the first
196 // term since the sign of the second term can be inferred from this and
197 // the fact that the operation has overflowed (if either is 0 no
198 // overflow can occur)
199 let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
200 let first_term_positive = first_term & (1 << (num_bits-1)) == 0;
201 if first_term_positive {
202 // Negative overflow not possible since the positive first term
203 // can only increase an (in range) negative term for addition
204 // or corresponding negated positive term for subtraction
205 Scalar::from_uint((1u128 << (num_bits - 1)) - 1, // max positive
206 Size::from_bits(num_bits))
208 // Positive overflow not possible for similar reason
210 Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
215 Scalar::from_uint(u128::max_value() >> (128 - num_bits),
216 Size::from_bits(num_bits))
217 } else { // underflow to 0
218 Scalar::from_uint(0u128, Size::from_bits(num_bits))
224 self.write_scalar(val, dest)?;
226 sym::unchecked_shl | sym::unchecked_shr => {
227 let l = self.read_immediate(args[0])?;
228 let r = self.read_immediate(args[1])?;
229 let bin_op = match intrinsic_name {
230 sym::unchecked_shl => BinOp::Shl,
231 sym::unchecked_shr => BinOp::Shr,
232 _ => bug!("Already checked for int ops")
234 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
236 let layout = self.layout_of(substs.type_at(0))?;
237 let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
238 throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
240 self.write_scalar(val, dest)?;
242 sym::rotate_left | sym::rotate_right => {
243 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
244 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
245 let layout = self.layout_of(substs.type_at(0))?;
246 let val = self.read_scalar(args[0])?.not_undef()?;
247 let val_bits = self.force_bits(val, layout.size)?;
248 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
249 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
250 let width_bits = layout.size.bits() as u128;
251 let shift_bits = raw_shift_bits % width_bits;
252 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
253 let result_bits = if intrinsic_name == sym::rotate_left {
254 (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
256 (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
258 let truncated_bits = self.truncate(result_bits, layout);
259 let result = Scalar::from_uint(truncated_bits, layout.size);
260 self.write_scalar(result, dest)?;
263 sym::ptr_offset_from => {
264 let isize_layout = self.layout_of(self.tcx.types.isize)?;
265 let a = self.read_immediate(args[0])?.to_scalar()?;
266 let b = self.read_immediate(args[1])?.to_scalar()?;
268 // Special case: if both scalars are *equal integers*
269 // and not NULL, we pretend there is an allocation of size 0 right there,
270 // and their offset is 0. (There's never a valid object at NULL, making it an
271 // exception from the exception.)
272 // This is the dual to the special exception for offset-by-0
273 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
275 // Control flow is weird because we cannot early-return (to reach the
276 // `go_to_block` at the end).
277 let done = if a.is_bits() && b.is_bits() {
278 let a = a.to_machine_usize(self)?;
279 let b = b.to_machine_usize(self)?;
280 if a == b && a != 0 {
281 self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
287 // General case: we need two pointers.
288 let a = self.force_ptr(a)?;
289 let b = self.force_ptr(b)?;
290 if a.alloc_id != b.alloc_id {
292 "ptr_offset_from cannot compute offset of pointers into different \
296 let usize_layout = self.layout_of(self.tcx.types.usize)?;
297 let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
298 let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
299 let (val, _overflowed, _ty) = self.overflowing_binary_op(
300 BinOp::Sub, a_offset, b_offset,
302 let pointee_layout = self.layout_of(substs.type_at(0))?;
303 let val = ImmTy::from_scalar(val, isize_layout);
304 let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
305 self.exact_div(val, size, dest)?;
310 self.copy_op_transmute(args[0], dest)?;
312 sym::simd_insert => {
313 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
316 let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx.tcx);
319 "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
323 input.layout, dest.layout,
324 "Return type `{}` must match vector type `{}`",
325 dest.layout.ty, input.layout.ty
328 elem.layout.ty, e_ty,
329 "Scalar element type `{}` must match vector element type `{}`",
334 let place = self.place_field(dest, i)?;
335 let value = if i == index {
338 self.operand_field(input, i)?
340 self.copy_op(value, place)?;
343 sym::simd_extract => {
344 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
345 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx);
348 "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
352 e_ty, dest.layout.ty,
353 "Return type `{}` must match vector element type `{}`",
356 self.copy_op(self.operand_field(args[0], index)?, dest)?;
358 _ => return Ok(false),
361 self.dump_place(*dest);
362 self.go_to_block(ret);
366 /// "Intercept" a function call to a panic-related function
367 /// because we have something special to do for it.
368 /// Returns `true` if an intercept happened.
369 pub fn hook_panic_fn(
371 instance: ty::Instance<'tcx>,
372 args: &[OpTy<'tcx, M::PointerTag>],
373 _ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
374 ) -> InterpResult<'tcx, bool> {
375 let def_id = instance.def_id();
376 if Some(def_id) == self.tcx.lang_items().panic_fn() {
377 // &'static str, &core::panic::Location { &'static str, u32, u32 }
378 assert!(args.len() == 2);
380 let msg_place = self.deref_operand(args[0])?;
381 let msg = Symbol::intern(self.read_str(msg_place)?);
383 let location = self.deref_operand(args[1])?;
384 let (file, line, col) = (
385 self.mplace_field(location, 0)?,
386 self.mplace_field(location, 1)?,
387 self.mplace_field(location, 2)?,
390 let file_place = self.deref_operand(file.into())?;
391 let file = Symbol::intern(self.read_str(file_place)?);
392 let line = self.read_scalar(line.into())?.to_u32()?;
393 let col = self.read_scalar(col.into())?.to_u32()?;
394 throw_panic!(Panic { msg, file, line, col })
395 } else if Some(def_id) == self.tcx.lang_items().begin_panic_fn() {
396 assert!(args.len() == 2);
397 // &'static str, &(&'static str, u32, u32)
399 let place = self.deref_operand(args[1])?;
400 let (file, line, col) = (
401 self.mplace_field(place, 0)?,
402 self.mplace_field(place, 1)?,
403 self.mplace_field(place, 2)?,
406 let msg_place = self.deref_operand(msg.into())?;
407 let msg = Symbol::intern(self.read_str(msg_place)?);
408 let file_place = self.deref_operand(file.into())?;
409 let file = Symbol::intern(self.read_str(file_place)?);
410 let line = self.read_scalar(line.into())?.to_u32()?;
411 let col = self.read_scalar(col.into())?.to_u32()?;
412 throw_panic!(Panic { msg, file, line, col })
420 a: ImmTy<'tcx, M::PointerTag>,
421 b: ImmTy<'tcx, M::PointerTag>,
422 dest: PlaceTy<'tcx, M::PointerTag>,
423 ) -> InterpResult<'tcx> {
424 // Performs an exact division, resulting in undefined behavior where
425 // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
426 // First, check x % y != 0.
427 if self.binary_op(BinOp::Rem, a, b)?.to_bits()? != 0 {
428 // Then, check if `b` is -1, which is the "min_value / -1" case.
429 let minus1 = Scalar::from_int(-1, dest.layout.size);
430 let b_scalar = b.to_scalar().unwrap();
431 if b_scalar == minus1 {
432 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
435 "exact_div: {} cannot be divided by {} without remainder",
441 self.binop_ignore_overflow(BinOp::Div, a, b, dest)