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,
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 self.copy_op_transmute(args[0], dest)?;
256 let index = self.read_scalar(args[1])?.to_u32()? as u64;
257 let scalar = args[2];
259 let (len, e_ty) = self.read_vector_ty(input);
262 "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
266 input.layout, dest.layout,
267 "Return type `{}` must match vector type `{}`",
268 dest.layout.ty, input.layout.ty
271 scalar.layout.ty, e_ty,
272 "Scalar type `{}` must match vector element type `{}`",
273 scalar.layout.ty, e_ty
277 let place = self.place_field(dest, i)?;
278 let value = if i == index {
281 self.operand_field(input, i)?
283 self.copy_op(value, place)?;
287 let index = self.read_scalar(args[1])?.to_u32()? as _;
288 let (len, e_ty) = self.read_vector_ty(args[0]);
291 "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
295 e_ty, dest.layout.ty,
296 "Return type `{}` must match vector element type `{}`",
299 self.copy_op(self.operand_field(args[0], index)?, dest)?;
301 _ => return Ok(false),
307 /// "Intercept" a function call because we have something special to do for it.
308 /// Returns `true` if an intercept happened.
311 instance: ty::Instance<'tcx>,
312 args: &[OpTy<'tcx, M::PointerTag>],
313 _dest: Option<PlaceTy<'tcx, M::PointerTag>>,
314 ) -> InterpResult<'tcx, bool> {
315 let def_id = instance.def_id();
316 if Some(def_id) == self.tcx.lang_items().panic_fn() {
317 // &'static str, &core::panic::Location { &'static str, u32, u32 }
318 assert!(args.len() == 2);
320 let msg_place = self.deref_operand(args[0])?;
321 let msg = Symbol::intern(self.read_str(msg_place)?);
323 let location = self.deref_operand(args[1])?;
324 let (file, line, col) = (
325 self.mplace_field(location, 0)?,
326 self.mplace_field(location, 1)?,
327 self.mplace_field(location, 2)?,
330 let file_place = self.deref_operand(file.into())?;
331 let file = Symbol::intern(self.read_str(file_place)?);
332 let line = self.read_scalar(line.into())?.to_u32()?;
333 let col = self.read_scalar(col.into())?.to_u32()?;
334 throw_panic!(Panic { msg, file, line, col })
335 } else if Some(def_id) == self.tcx.lang_items().begin_panic_fn() {
336 assert!(args.len() == 2);
337 // &'static str, &(&'static str, u32, u32)
339 let place = self.deref_operand(args[1])?;
340 let (file, line, col) = (
341 self.mplace_field(place, 0)?,
342 self.mplace_field(place, 1)?,
343 self.mplace_field(place, 2)?,
346 let msg_place = self.deref_operand(msg.into())?;
347 let msg = Symbol::intern(self.read_str(msg_place)?);
348 let file_place = self.deref_operand(file.into())?;
349 let file = Symbol::intern(self.read_str(file_place)?);
350 let line = self.read_scalar(line.into())?.to_u32()?;
351 let col = self.read_scalar(col.into())?.to_u32()?;
352 throw_panic!(Panic { msg, file, line, col })