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, 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 span = self.find_closest_untracked_caller_location().unwrap_or(span);
116 let location = self.alloc_caller_location_for_span(span);
117 self.write_scalar(location.ptr, dest)?;
126 let val = self.tcx.const_eval_instance(self.param_env,
128 Some(self.tcx.span))?;
129 let val = self.eval_const_to_op(val, None)?;
130 self.copy_op(val, dest)?;
139 | sym::bitreverse => {
140 let ty = substs.type_at(0);
141 let layout_of = self.layout_of(ty)?;
142 let val = self.read_scalar(args[0])?.not_undef()?;
143 let bits = self.force_bits(val, layout_of.size)?;
144 let kind = match layout_of.abi {
145 ty::layout::Abi::Scalar(ref scalar) => scalar.value,
146 _ => throw_unsup!(TypeNotPrimitive(ty)),
148 let (nonzero, intrinsic_name) = match intrinsic_name {
149 sym::cttz_nonzero => (true, sym::cttz),
150 sym::ctlz_nonzero => (true, sym::ctlz),
151 other => (false, other),
153 if nonzero && bits == 0 {
154 throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
156 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
157 self.write_scalar(out_val, dest)?;
162 | sym::add_with_overflow
163 | sym::sub_with_overflow
164 | sym::mul_with_overflow => {
165 let lhs = self.read_immediate(args[0])?;
166 let rhs = self.read_immediate(args[1])?;
167 let (bin_op, ignore_overflow) = match intrinsic_name {
168 sym::wrapping_add => (BinOp::Add, true),
169 sym::wrapping_sub => (BinOp::Sub, true),
170 sym::wrapping_mul => (BinOp::Mul, true),
171 sym::add_with_overflow => (BinOp::Add, false),
172 sym::sub_with_overflow => (BinOp::Sub, false),
173 sym::mul_with_overflow => (BinOp::Mul, false),
174 _ => bug!("Already checked for int ops")
177 self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
179 self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
182 sym::saturating_add | sym::saturating_sub => {
183 let l = self.read_immediate(args[0])?;
184 let r = self.read_immediate(args[1])?;
185 let is_add = intrinsic_name == sym::saturating_add;
186 let (val, overflowed, _ty) = self.overflowing_binary_op(if is_add {
191 let val = if overflowed {
192 let num_bits = l.layout.size.bits();
193 if l.layout.abi.is_signed() {
194 // For signed ints the saturated value depends on the sign of the first
195 // term since the sign of the second term can be inferred from this and
196 // the fact that the operation has overflowed (if either is 0 no
197 // overflow can occur)
198 let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
199 let first_term_positive = first_term & (1 << (num_bits-1)) == 0;
200 if first_term_positive {
201 // Negative overflow not possible since the positive first term
202 // can only increase an (in range) negative term for addition
203 // or corresponding negated positive term for subtraction
204 Scalar::from_uint((1u128 << (num_bits - 1)) - 1, // max positive
205 Size::from_bits(num_bits))
207 // Positive overflow not possible for similar reason
209 Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
214 Scalar::from_uint(u128::max_value() >> (128 - num_bits),
215 Size::from_bits(num_bits))
216 } else { // underflow to 0
217 Scalar::from_uint(0u128, Size::from_bits(num_bits))
223 self.write_scalar(val, dest)?;
225 sym::unchecked_shl | sym::unchecked_shr => {
226 let l = self.read_immediate(args[0])?;
227 let r = self.read_immediate(args[1])?;
228 let bin_op = match intrinsic_name {
229 sym::unchecked_shl => BinOp::Shl,
230 sym::unchecked_shr => BinOp::Shr,
231 _ => bug!("Already checked for int ops")
233 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
235 let layout = self.layout_of(substs.type_at(0))?;
236 let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
237 throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
239 self.write_scalar(val, dest)?;
241 sym::rotate_left | sym::rotate_right => {
242 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
243 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
244 let layout = self.layout_of(substs.type_at(0))?;
245 let val = self.read_scalar(args[0])?.not_undef()?;
246 let val_bits = self.force_bits(val, layout.size)?;
247 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
248 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
249 let width_bits = layout.size.bits() as u128;
250 let shift_bits = raw_shift_bits % width_bits;
251 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
252 let result_bits = if intrinsic_name == sym::rotate_left {
253 (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
255 (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
257 let truncated_bits = self.truncate(result_bits, layout);
258 let result = Scalar::from_uint(truncated_bits, layout.size);
259 self.write_scalar(result, dest)?;
262 sym::ptr_offset_from => {
263 let isize_layout = self.layout_of(self.tcx.types.isize)?;
264 let a = self.read_immediate(args[0])?.to_scalar()?;
265 let b = self.read_immediate(args[1])?.to_scalar()?;
267 // Special case: if both scalars are *equal integers*
268 // and not NULL, we pretend there is an allocation of size 0 right there,
269 // and their offset is 0. (There's never a valid object at NULL, making it an
270 // exception from the exception.)
271 // This is the dual to the special exception for offset-by-0
272 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
274 // Control flow is weird because we cannot early-return (to reach the
275 // `go_to_block` at the end).
276 let done = if a.is_bits() && b.is_bits() {
277 let a = a.to_machine_usize(self)?;
278 let b = b.to_machine_usize(self)?;
279 if a == b && a != 0 {
280 self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
286 // General case: we need two pointers.
287 let a = self.force_ptr(a)?;
288 let b = self.force_ptr(b)?;
289 if a.alloc_id != b.alloc_id {
291 "ptr_offset_from cannot compute offset of pointers into different \
295 let usize_layout = self.layout_of(self.tcx.types.usize)?;
296 let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
297 let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
298 let (val, _overflowed, _ty) = self.overflowing_binary_op(
299 BinOp::Sub, a_offset, b_offset,
301 let pointee_layout = self.layout_of(substs.type_at(0))?;
302 let val = ImmTy::from_scalar(val, isize_layout);
303 let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
304 self.exact_div(val, size, dest)?;
309 self.copy_op_transmute(args[0], dest)?;
311 sym::simd_insert => {
312 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
315 let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx.tcx);
318 "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
322 input.layout, dest.layout,
323 "Return type `{}` must match vector type `{}`",
324 dest.layout.ty, input.layout.ty
327 elem.layout.ty, e_ty,
328 "Scalar element type `{}` must match vector element type `{}`",
333 let place = self.place_field(dest, i)?;
334 let value = if i == index {
337 self.operand_field(input, i)?
339 self.copy_op(value, place)?;
342 sym::simd_extract => {
343 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
344 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx);
347 "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
351 e_ty, dest.layout.ty,
352 "Return type `{}` must match vector element type `{}`",
355 self.copy_op(self.operand_field(args[0], index)?, dest)?;
357 _ => return Ok(false),
360 self.dump_place(*dest);
361 self.go_to_block(ret);
365 /// "Intercept" a function call to a panic-related function
366 /// because we have something special to do for it.
367 /// Returns `true` if an intercept happened.
368 pub fn hook_panic_fn(
370 instance: ty::Instance<'tcx>,
371 args: &[OpTy<'tcx, M::PointerTag>],
372 _ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
373 ) -> InterpResult<'tcx, bool> {
374 let def_id = instance.def_id();
375 if Some(def_id) == self.tcx.lang_items().panic_fn() {
376 // &'static str, &core::panic::Location { &'static str, u32, u32 }
377 assert!(args.len() == 2);
379 let msg_place = self.deref_operand(args[0])?;
380 let msg = Symbol::intern(self.read_str(msg_place)?);
382 let location = self.deref_operand(args[1])?;
383 let (file, line, col) = (
384 self.mplace_field(location, 0)?,
385 self.mplace_field(location, 1)?,
386 self.mplace_field(location, 2)?,
389 let file_place = self.deref_operand(file.into())?;
390 let file = Symbol::intern(self.read_str(file_place)?);
391 let line = self.read_scalar(line.into())?.to_u32()?;
392 let col = self.read_scalar(col.into())?.to_u32()?;
393 throw_panic!(Panic { msg, file, line, col })
394 } else if Some(def_id) == self.tcx.lang_items().begin_panic_fn() {
395 assert!(args.len() == 2);
396 // &'static str, &(&'static str, u32, u32)
398 let place = self.deref_operand(args[1])?;
399 let (file, line, col) = (
400 self.mplace_field(place, 0)?,
401 self.mplace_field(place, 1)?,
402 self.mplace_field(place, 2)?,
405 let msg_place = self.deref_operand(msg.into())?;
406 let msg = Symbol::intern(self.read_str(msg_place)?);
407 let file_place = self.deref_operand(file.into())?;
408 let file = Symbol::intern(self.read_str(file_place)?);
409 let line = self.read_scalar(line.into())?.to_u32()?;
410 let col = self.read_scalar(col.into())?.to_u32()?;
411 throw_panic!(Panic { msg, file, line, col })
419 a: ImmTy<'tcx, M::PointerTag>,
420 b: ImmTy<'tcx, M::PointerTag>,
421 dest: PlaceTy<'tcx, M::PointerTag>,
422 ) -> InterpResult<'tcx> {
423 // Performs an exact division, resulting in undefined behavior where
424 // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
425 // First, check x % y != 0.
426 if self.binary_op(BinOp::Rem, a, b)?.to_bits()? != 0 {
427 // Then, check if `b` is -1, which is the "min_value / -1" case.
428 let minus1 = Scalar::from_int(-1, dest.layout.size);
429 let b_scalar = b.to_scalar().unwrap();
430 if b_scalar == minus1 {
431 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
434 "exact_div: {} cannot be divided by {} without remainder",
440 self.binop_ignore_overflow(BinOp::Div, a, b, dest)