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::symbol::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;
12 use rustc::mir::BinOp;
13 use rustc::mir::interpret::{InterpResult, Scalar, GlobalId, ConstValue};
16 Machine, PlaceTy, OpTy, InterpCx, ImmTy,
22 fn numeric_intrinsic<'tcx, Tag>(
26 ) -> InterpResult<'tcx, Scalar<Tag>> {
27 let size = match kind {
28 Primitive::Int(integer, _) => integer.size(),
29 _ => bug!("invalid `{}` argument: {:?}", name, bits),
31 let extra = 128 - size.bits() as u128;
32 let bits_out = match name {
33 "ctpop" => bits.count_ones() as u128,
34 "ctlz" => bits.leading_zeros() as u128 - extra,
35 "cttz" => (bits << extra).trailing_zeros() as u128 - extra,
36 "bswap" => (bits << extra).swap_bytes(),
37 "bitreverse" => (bits << extra).reverse_bits(),
38 _ => bug!("not a numeric intrinsic: {}", name),
40 Ok(Scalar::from_uint(bits_out, size))
43 /// The logic for all nullary intrinsics is implemented here. These intrinsics don't get evaluated
44 /// inside an `InterpCx` and instead have their value computed directly from rustc internal info.
45 crate fn eval_nullary_intrinsic<'tcx>(
47 param_env: ty::ParamEnv<'tcx>,
49 substs: SubstsRef<'tcx>,
50 ) -> InterpResult<'tcx, &'tcx ty::Const<'tcx>> {
51 let tp_ty = substs.type_at(0);
52 let name = &*tcx.item_name(def_id).as_str();
55 let alloc = type_name::alloc_type_name(tcx, tp_ty);
56 tcx.mk_const(ty::Const {
57 val: ConstValue::Slice {
62 ty: tcx.mk_static_str(),
65 "needs_drop" => ty::Const::from_bool(tcx, tp_ty.needs_drop(tcx, param_env)),
69 let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
71 "pref_align_of" => layout.align.pref.bytes(),
72 "min_align_of" => layout.align.abi.bytes(),
73 "size_of" => layout.size.bytes(),
76 ty::Const::from_usize(tcx, n)
78 "type_id" => ty::Const::from_bits(
80 tcx.type_id_hash(tp_ty).into(),
81 param_env.and(tcx.types.u64),
83 other => bug!("`{}` is not a zero arg intrinsic", other),
87 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
88 /// Returns `true` if emulation happened.
89 pub fn emulate_intrinsic(
92 instance: ty::Instance<'tcx>,
93 args: &[OpTy<'tcx, M::PointerTag>],
94 dest: PlaceTy<'tcx, M::PointerTag>,
95 ) -> InterpResult<'tcx, bool> {
96 let substs = instance.substs;
98 let intrinsic_name = &*self.tcx.item_name(instance.def_id()).as_str();
99 match intrinsic_name {
100 "caller_location" => {
101 let caller = self.tcx.sess.source_map().lookup_char_pos(span.lo());
102 let location = self.alloc_caller_location(
103 Symbol::intern(&caller.file.name.to_string()),
105 caller.col_display as u32 + 1,
107 self.write_scalar(location.ptr, dest)?;
120 let val = self.tcx.const_eval(self.param_env.and(gid))?;
121 let val = self.eval_const_to_op(val, None)?;
122 self.copy_op(val, dest)?;
132 let ty = substs.type_at(0);
133 let layout_of = self.layout_of(ty)?;
134 let val = self.read_scalar(args[0])?.not_undef()?;
135 let bits = self.force_bits(val, layout_of.size)?;
136 let kind = match layout_of.abi {
137 ty::layout::Abi::Scalar(ref scalar) => scalar.value,
138 _ => throw_unsup!(TypeNotPrimitive(ty)),
140 let out_val = if intrinsic_name.ends_with("_nonzero") {
142 throw_ub_format!("`{}` called on 0", intrinsic_name);
144 numeric_intrinsic(intrinsic_name.trim_end_matches("_nonzero"), bits, kind)?
146 numeric_intrinsic(intrinsic_name, bits, kind)?
148 self.write_scalar(out_val, dest)?;
153 | "add_with_overflow"
154 | "sub_with_overflow"
155 | "mul_with_overflow" => {
156 let lhs = self.read_immediate(args[0])?;
157 let rhs = self.read_immediate(args[1])?;
158 let (bin_op, ignore_overflow) = match intrinsic_name {
159 "wrapping_add" => (BinOp::Add, true),
160 "wrapping_sub" => (BinOp::Sub, true),
161 "wrapping_mul" => (BinOp::Mul, true),
162 "add_with_overflow" => (BinOp::Add, false),
163 "sub_with_overflow" => (BinOp::Sub, false),
164 "mul_with_overflow" => (BinOp::Mul, false),
165 _ => bug!("Already checked for int ops")
168 self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
170 self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
173 "saturating_add" | "saturating_sub" => {
174 let l = self.read_immediate(args[0])?;
175 let r = self.read_immediate(args[1])?;
176 let is_add = intrinsic_name == "saturating_add";
177 let (val, overflowed, _ty) = self.overflowing_binary_op(if is_add {
182 let val = if overflowed {
183 let num_bits = l.layout.size.bits();
184 if l.layout.abi.is_signed() {
185 // For signed ints the saturated value depends on the sign of the first
186 // term since the sign of the second term can be inferred from this and
187 // the fact that the operation has overflowed (if either is 0 no
188 // overflow can occur)
189 let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
190 let first_term_positive = first_term & (1 << (num_bits-1)) == 0;
191 if first_term_positive {
192 // Negative overflow not possible since the positive first term
193 // can only increase an (in range) negative term for addition
194 // or corresponding negated positive term for subtraction
195 Scalar::from_uint((1u128 << (num_bits - 1)) - 1, // max positive
196 Size::from_bits(num_bits))
198 // Positive overflow not possible for similar reason
200 Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
205 Scalar::from_uint(u128::max_value() >> (128 - num_bits),
206 Size::from_bits(num_bits))
207 } else { // underflow to 0
208 Scalar::from_uint(0u128, Size::from_bits(num_bits))
214 self.write_scalar(val, dest)?;
216 "unchecked_shl" | "unchecked_shr" => {
217 let l = self.read_immediate(args[0])?;
218 let r = self.read_immediate(args[1])?;
219 let bin_op = match intrinsic_name {
220 "unchecked_shl" => BinOp::Shl,
221 "unchecked_shr" => BinOp::Shr,
222 _ => bug!("Already checked for int ops")
224 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
226 let layout = self.layout_of(substs.type_at(0))?;
227 let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
228 throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
230 self.write_scalar(val, dest)?;
232 "rotate_left" | "rotate_right" => {
233 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
234 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
235 let layout = self.layout_of(substs.type_at(0))?;
236 let val = self.read_scalar(args[0])?.not_undef()?;
237 let val_bits = self.force_bits(val, layout.size)?;
238 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
239 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
240 let width_bits = layout.size.bits() as u128;
241 let shift_bits = raw_shift_bits % width_bits;
242 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
243 let result_bits = if intrinsic_name == "rotate_left" {
244 (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
246 (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
248 let truncated_bits = self.truncate(result_bits, layout);
249 let result = Scalar::from_uint(truncated_bits, layout.size);
250 self.write_scalar(result, dest)?;
253 "ptr_offset_from" => {
254 let isize_layout = self.layout_of(self.tcx.types.isize)?;
255 let a = self.read_immediate(args[0])?.to_scalar()?;
256 let b = self.read_immediate(args[1])?.to_scalar()?;
258 // Special case: if both scalars are *equal integers*
259 // and not NULL, we pretend there is an allocation of size 0 right there,
260 // and their offset is 0. (There's never a valid object at NULL, making it an
261 // exception from the exception.)
262 // This is the dual to the special exception for offset-by-0
263 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
264 if a.is_bits() && b.is_bits() {
265 let a = a.to_usize(self)?;
266 let b = b.to_usize(self)?;
267 if a == b && a != 0 {
268 self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
273 // General case: we need two pointers.
274 let a = self.force_ptr(a)?;
275 let b = self.force_ptr(b)?;
276 if a.alloc_id != b.alloc_id {
278 "ptr_offset_from cannot compute offset of pointers into different \
282 let usize_layout = self.layout_of(self.tcx.types.usize)?;
283 let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
284 let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
285 let (val, _overflowed, _ty) = self.overflowing_binary_op(
286 BinOp::Sub, a_offset, b_offset,
288 let pointee_layout = self.layout_of(substs.type_at(0))?;
289 let val = ImmTy::from_scalar(val, isize_layout);
290 let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
291 self.exact_div(val, size, dest)?;
295 self.copy_op_transmute(args[0], dest)?;
298 let index = self.read_scalar(args[1])?.to_u32()? as u64;
299 let scalar = args[2];
301 let (len, e_ty) = self.read_vector_ty(input);
304 "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
308 input.layout, dest.layout,
309 "Return type `{}` must match vector type `{}`",
310 dest.layout.ty, input.layout.ty
313 scalar.layout.ty, e_ty,
314 "Scalar type `{}` must match vector element type `{}`",
315 scalar.layout.ty, e_ty
319 let place = self.place_field(dest, i)?;
320 let value = if i == index {
323 self.operand_field(input, i)?
325 self.copy_op(value, place)?;
329 let index = self.read_scalar(args[1])?.to_u32()? as _;
330 let (len, e_ty) = self.read_vector_ty(args[0]);
333 "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
337 e_ty, dest.layout.ty,
338 "Return type `{}` must match vector element type `{}`",
341 self.copy_op(self.operand_field(args[0], index)?, dest)?;
343 _ => return Ok(false),
349 /// "Intercept" a function call because we have something special to do for it.
350 /// Returns `true` if an intercept happened.
353 instance: ty::Instance<'tcx>,
354 args: &[OpTy<'tcx, M::PointerTag>],
355 _dest: Option<PlaceTy<'tcx, M::PointerTag>>,
356 ) -> InterpResult<'tcx, bool> {
357 let def_id = instance.def_id();
358 if Some(def_id) == self.tcx.lang_items().panic_fn() {
359 // &'static str, &core::panic::Location { &'static str, u32, u32 }
360 assert!(args.len() == 2);
362 let msg_place = self.deref_operand(args[0])?;
363 let msg = Symbol::intern(self.read_str(msg_place)?);
365 let location = self.deref_operand(args[1])?;
366 let (file, line, col) = (
367 self.mplace_field(location, 0)?,
368 self.mplace_field(location, 1)?,
369 self.mplace_field(location, 2)?,
372 let file_place = self.deref_operand(file.into())?;
373 let file = Symbol::intern(self.read_str(file_place)?);
374 let line = self.read_scalar(line.into())?.to_u32()?;
375 let col = self.read_scalar(col.into())?.to_u32()?;
376 throw_panic!(Panic { msg, file, line, col })
377 } else if Some(def_id) == self.tcx.lang_items().begin_panic_fn() {
378 assert!(args.len() == 2);
379 // &'static str, &(&'static str, u32, u32)
381 let place = self.deref_operand(args[1])?;
382 let (file, line, col) = (
383 self.mplace_field(place, 0)?,
384 self.mplace_field(place, 1)?,
385 self.mplace_field(place, 2)?,
388 let msg_place = self.deref_operand(msg.into())?;
389 let msg = Symbol::intern(self.read_str(msg_place)?);
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 })
402 a: ImmTy<'tcx, M::PointerTag>,
403 b: ImmTy<'tcx, M::PointerTag>,
404 dest: PlaceTy<'tcx, M::PointerTag>,
405 ) -> InterpResult<'tcx> {
406 // Performs an exact division, resulting in undefined behavior where
407 // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
408 // First, check x % y != 0.
409 if self.binary_op(BinOp::Rem, a, b)?.to_bits()? != 0 {
410 // Then, check if `b` is -1, which is the "min_value / -1" case.
411 let minus1 = Scalar::from_int(-1, dest.layout.size);
412 let b = b.to_scalar().unwrap();
414 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
417 "exact_div: {} cannot be divided by {} without remainder",
418 a.to_scalar().unwrap(),
423 self.binop_ignore_overflow(BinOp::Div, a, b, dest)