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: Option<PlaceTy<'tcx, M::PointerTag>>,
95 ) -> InterpResult<'tcx, bool> {
96 let substs = instance.substs;
98 // We currently do not handle any diverging intrinsics.
99 let dest = match dest {
101 None => return Ok(false)
103 let intrinsic_name = &*self.tcx.item_name(instance.def_id()).as_str();
105 match intrinsic_name {
106 "caller_location" => {
107 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
108 let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
109 let location = self.alloc_caller_location(
110 Symbol::intern(&caller.file.name.to_string()),
112 caller.col_display as u32 + 1,
114 self.write_scalar(location.ptr, dest)?;
127 let val = self.tcx.const_eval(self.param_env.and(gid))?;
128 let val = self.eval_const_to_op(val, None)?;
129 self.copy_op(val, dest)?;
139 let ty = substs.type_at(0);
140 let layout_of = self.layout_of(ty)?;
141 let val = self.read_scalar(args[0])?.not_undef()?;
142 let bits = self.force_bits(val, layout_of.size)?;
143 let kind = match layout_of.abi {
144 ty::layout::Abi::Scalar(ref scalar) => scalar.value,
145 _ => throw_unsup!(TypeNotPrimitive(ty)),
147 let out_val = if intrinsic_name.ends_with("_nonzero") {
149 throw_ub_format!("`{}` called on 0", intrinsic_name);
151 numeric_intrinsic(intrinsic_name.trim_end_matches("_nonzero"), bits, kind)?
153 numeric_intrinsic(intrinsic_name, bits, kind)?
155 self.write_scalar(out_val, dest)?;
160 | "add_with_overflow"
161 | "sub_with_overflow"
162 | "mul_with_overflow" => {
163 let lhs = self.read_immediate(args[0])?;
164 let rhs = self.read_immediate(args[1])?;
165 let (bin_op, ignore_overflow) = match intrinsic_name {
166 "wrapping_add" => (BinOp::Add, true),
167 "wrapping_sub" => (BinOp::Sub, true),
168 "wrapping_mul" => (BinOp::Mul, true),
169 "add_with_overflow" => (BinOp::Add, false),
170 "sub_with_overflow" => (BinOp::Sub, false),
171 "mul_with_overflow" => (BinOp::Mul, false),
172 _ => bug!("Already checked for int ops")
175 self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
177 self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
180 "saturating_add" | "saturating_sub" => {
181 let l = self.read_immediate(args[0])?;
182 let r = self.read_immediate(args[1])?;
183 let is_add = intrinsic_name == "saturating_add";
184 let (val, overflowed, _ty) = self.overflowing_binary_op(if is_add {
189 let val = if overflowed {
190 let num_bits = l.layout.size.bits();
191 if l.layout.abi.is_signed() {
192 // For signed ints the saturated value depends on the sign of the first
193 // term since the sign of the second term can be inferred from this and
194 // the fact that the operation has overflowed (if either is 0 no
195 // overflow can occur)
196 let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
197 let first_term_positive = first_term & (1 << (num_bits-1)) == 0;
198 if first_term_positive {
199 // Negative overflow not possible since the positive first term
200 // can only increase an (in range) negative term for addition
201 // or corresponding negated positive term for subtraction
202 Scalar::from_uint((1u128 << (num_bits - 1)) - 1, // max positive
203 Size::from_bits(num_bits))
205 // Positive overflow not possible for similar reason
207 Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
212 Scalar::from_uint(u128::max_value() >> (128 - num_bits),
213 Size::from_bits(num_bits))
214 } else { // underflow to 0
215 Scalar::from_uint(0u128, Size::from_bits(num_bits))
221 self.write_scalar(val, dest)?;
223 "unchecked_shl" | "unchecked_shr" => {
224 let l = self.read_immediate(args[0])?;
225 let r = self.read_immediate(args[1])?;
226 let bin_op = match intrinsic_name {
227 "unchecked_shl" => BinOp::Shl,
228 "unchecked_shr" => BinOp::Shr,
229 _ => bug!("Already checked for int ops")
231 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
233 let layout = self.layout_of(substs.type_at(0))?;
234 let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
235 throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
237 self.write_scalar(val, dest)?;
239 "rotate_left" | "rotate_right" => {
240 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
241 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
242 let layout = self.layout_of(substs.type_at(0))?;
243 let val = self.read_scalar(args[0])?.not_undef()?;
244 let val_bits = self.force_bits(val, layout.size)?;
245 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
246 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
247 let width_bits = layout.size.bits() as u128;
248 let shift_bits = raw_shift_bits % width_bits;
249 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
250 let result_bits = if intrinsic_name == "rotate_left" {
251 (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
253 (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
255 let truncated_bits = self.truncate(result_bits, layout);
256 let result = Scalar::from_uint(truncated_bits, layout.size);
257 self.write_scalar(result, dest)?;
260 "ptr_offset_from" => {
261 let isize_layout = self.layout_of(self.tcx.types.isize)?;
262 let a = self.read_immediate(args[0])?.to_scalar()?;
263 let b = self.read_immediate(args[1])?.to_scalar()?;
265 // Special case: if both scalars are *equal integers*
266 // and not NULL, we pretend there is an allocation of size 0 right there,
267 // and their offset is 0. (There's never a valid object at NULL, making it an
268 // exception from the exception.)
269 // This is the dual to the special exception for offset-by-0
270 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
271 if a.is_bits() && b.is_bits() {
272 let a = a.to_machine_usize(self)?;
273 let b = b.to_machine_usize(self)?;
274 if a == b && a != 0 {
275 self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
280 // General case: we need two pointers.
281 let a = self.force_ptr(a)?;
282 let b = self.force_ptr(b)?;
283 if a.alloc_id != b.alloc_id {
285 "ptr_offset_from cannot compute offset of pointers into different \
289 let usize_layout = self.layout_of(self.tcx.types.usize)?;
290 let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
291 let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
292 let (val, _overflowed, _ty) = self.overflowing_binary_op(
293 BinOp::Sub, a_offset, b_offset,
295 let pointee_layout = self.layout_of(substs.type_at(0))?;
296 let val = ImmTy::from_scalar(val, isize_layout);
297 let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
298 self.exact_div(val, size, dest)?;
302 self.copy_op_transmute(args[0], dest)?;
305 let index = self.read_scalar(args[1])?.to_u32()? as u64;
306 let scalar = args[2];
308 let (len, e_ty) = self.read_vector_ty(input);
311 "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
315 input.layout, dest.layout,
316 "Return type `{}` must match vector type `{}`",
317 dest.layout.ty, input.layout.ty
320 scalar.layout.ty, e_ty,
321 "Scalar type `{}` must match vector element type `{}`",
322 scalar.layout.ty, e_ty
326 let place = self.place_field(dest, i)?;
327 let value = if i == index {
330 self.operand_field(input, i)?
332 self.copy_op(value, place)?;
336 let index = self.read_scalar(args[1])?.to_u32()? as _;
337 let (len, e_ty) = self.read_vector_ty(args[0]);
340 "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
344 e_ty, dest.layout.ty,
345 "Return type `{}` must match vector element type `{}`",
348 self.copy_op(self.operand_field(args[0], index)?, dest)?;
350 _ => return Ok(false),
356 /// "Intercept" a function call to a panic-related function
357 /// because we have something special to do for it.
358 /// Returns `true` if an intercept happened.
359 pub fn hook_panic_fn(
361 instance: ty::Instance<'tcx>,
362 args: &[OpTy<'tcx, M::PointerTag>],
363 _dest: Option<PlaceTy<'tcx, M::PointerTag>>,
364 ) -> InterpResult<'tcx, bool> {
365 let def_id = instance.def_id();
366 if Some(def_id) == self.tcx.lang_items().panic_fn() {
367 // &'static str, &core::panic::Location { &'static str, u32, u32 }
368 assert!(args.len() == 2);
370 let msg_place = self.deref_operand(args[0])?;
371 let msg = Symbol::intern(self.read_str(msg_place)?);
373 let location = self.deref_operand(args[1])?;
374 let (file, line, col) = (
375 self.mplace_field(location, 0)?,
376 self.mplace_field(location, 1)?,
377 self.mplace_field(location, 2)?,
380 let file_place = self.deref_operand(file.into())?;
381 let file = Symbol::intern(self.read_str(file_place)?);
382 let line = self.read_scalar(line.into())?.to_u32()?;
383 let col = self.read_scalar(col.into())?.to_u32()?;
384 throw_panic!(Panic { msg, file, line, col })
385 } else if Some(def_id) == self.tcx.lang_items().begin_panic_fn() {
386 assert!(args.len() == 2);
387 // &'static str, &(&'static str, u32, u32)
389 let place = self.deref_operand(args[1])?;
390 let (file, line, col) = (
391 self.mplace_field(place, 0)?,
392 self.mplace_field(place, 1)?,
393 self.mplace_field(place, 2)?,
396 let msg_place = self.deref_operand(msg.into())?;
397 let msg = Symbol::intern(self.read_str(msg_place)?);
398 let file_place = self.deref_operand(file.into())?;
399 let file = Symbol::intern(self.read_str(file_place)?);
400 let line = self.read_scalar(line.into())?.to_u32()?;
401 let col = self.read_scalar(col.into())?.to_u32()?;
402 throw_panic!(Panic { msg, file, line, col })
410 a: ImmTy<'tcx, M::PointerTag>,
411 b: ImmTy<'tcx, M::PointerTag>,
412 dest: PlaceTy<'tcx, M::PointerTag>,
413 ) -> InterpResult<'tcx> {
414 // Performs an exact division, resulting in undefined behavior where
415 // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
416 // First, check x % y != 0.
417 if self.binary_op(BinOp::Rem, a, b)?.to_bits()? != 0 {
418 // Then, check if `b` is -1, which is the "min_value / -1" case.
419 let minus1 = Scalar::from_int(-1, dest.layout.size);
420 let b = b.to_scalar().unwrap();
422 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
425 "exact_div: {} cannot be divided by {} without remainder",
426 a.to_scalar().unwrap(),
431 self.binop_ignore_overflow(BinOp::Div, a, b, dest)