]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/intrinsics.rs
8e4dc87451c326dd845a2e5ef2faf2ac8d8f6f5a
[rust.git] / src / librustc_mir / interpret / intrinsics.rs
1 //! Intrinsics and other functions that the miri engine executes without
2 //! looking at their MIR. Intrinsics/functions supported here are shared by CTFE
3 //! and miri.
4
5 use rustc::hir::def_id::DefId;
6 use rustc::mir::{
7     self,
8     interpret::{ConstValue, InterpResult, Scalar},
9     BinOp,
10 };
11 use rustc::ty;
12 use rustc::ty::layout::{LayoutOf, Primitive, Size};
13 use rustc::ty::subst::SubstsRef;
14 use rustc::ty::TyCtxt;
15 use syntax_pos::symbol::{sym, Symbol};
16 use syntax_pos::Span;
17
18 use super::{ImmTy, InterpCx, Machine, OpTy, PlaceTy};
19
20 mod caller_location;
21 mod type_name;
22
23 fn numeric_intrinsic<'tcx, Tag>(
24     name: Symbol,
25     bits: u128,
26     kind: Primitive,
27 ) -> InterpResult<'tcx, Scalar<Tag>> {
28     let size = match kind {
29         Primitive::Int(integer, _) => integer.size(),
30         _ => bug!("invalid `{}` argument: {:?}", name, bits),
31     };
32     let extra = 128 - size.bits() as u128;
33     let bits_out = match name {
34         sym::ctpop => bits.count_ones() as u128,
35         sym::ctlz => bits.leading_zeros() as u128 - extra,
36         sym::cttz => (bits << extra).trailing_zeros() as u128 - extra,
37         sym::bswap => (bits << extra).swap_bytes(),
38         sym::bitreverse => (bits << extra).reverse_bits(),
39         _ => bug!("not a numeric intrinsic: {}", name),
40     };
41     Ok(Scalar::from_uint(bits_out, size))
42 }
43
44 /// The logic for all nullary intrinsics is implemented here. These intrinsics don't get evaluated
45 /// inside an `InterpCx` and instead have their value computed directly from rustc internal info.
46 crate fn eval_nullary_intrinsic<'tcx>(
47     tcx: TyCtxt<'tcx>,
48     param_env: ty::ParamEnv<'tcx>,
49     def_id: DefId,
50     substs: SubstsRef<'tcx>,
51 ) -> InterpResult<'tcx, &'tcx ty::Const<'tcx>> {
52     let tp_ty = substs.type_at(0);
53     let name = tcx.item_name(def_id);
54     Ok(match name {
55         sym::type_name => {
56             let alloc = type_name::alloc_type_name(tcx, tp_ty);
57             tcx.mk_const(ty::Const {
58                 val: ty::ConstKind::Value(ConstValue::Slice {
59                     data: alloc,
60                     start: 0,
61                     end: alloc.len(),
62                 }),
63                 ty: tcx.mk_static_str(),
64             })
65         }
66         sym::needs_drop => ty::Const::from_bool(tcx, tp_ty.needs_drop(tcx, param_env)),
67         sym::size_of | sym::min_align_of | sym::pref_align_of => {
68             let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
69             let n = match name {
70                 sym::pref_align_of => layout.align.pref.bytes(),
71                 sym::min_align_of => layout.align.abi.bytes(),
72                 sym::size_of => layout.size.bytes(),
73                 _ => bug!(),
74             };
75             ty::Const::from_usize(tcx, n)
76         }
77         sym::type_id => {
78             ty::Const::from_bits(tcx, tcx.type_id_hash(tp_ty).into(), param_env.and(tcx.types.u64))
79         }
80         other => bug!("`{}` is not a zero arg intrinsic", other),
81     })
82 }
83
84 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
85     /// Returns `true` if emulation happened.
86     pub fn emulate_intrinsic(
87         &mut self,
88         span: Span,
89         instance: ty::Instance<'tcx>,
90         args: &[OpTy<'tcx, M::PointerTag>],
91         ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
92     ) -> InterpResult<'tcx, bool> {
93         let substs = instance.substs;
94         let intrinsic_name = self.tcx.item_name(instance.def_id());
95
96         // We currently do not handle any intrinsics that are *allowed* to diverge,
97         // but `transmute` could lack a return place in case of UB.
98         let (dest, ret) = match ret {
99             Some(p) => p,
100             None => match intrinsic_name {
101                 sym::transmute => throw_ub!(Unreachable),
102                 _ => return Ok(false),
103             },
104         };
105
106         // Keep the patterns in this match ordered the same as the list in
107         // `src/librustc/ty/constness.rs`
108         match intrinsic_name {
109             sym::caller_location => {
110                 let span = self.find_closest_untracked_caller_location().unwrap_or(span);
111                 let location = self.alloc_caller_location_for_span(span);
112                 self.write_scalar(location.ptr, dest)?;
113             }
114
115             sym::min_align_of
116             | sym::pref_align_of
117             | sym::needs_drop
118             | sym::size_of
119             | sym::type_id
120             | sym::type_name => {
121                 let val =
122                     self.tcx.const_eval_instance(self.param_env, instance, Some(self.tcx.span))?;
123                 let val = self.eval_const_to_op(val, None)?;
124                 self.copy_op(val, dest)?;
125             }
126
127             sym::ctpop
128             | sym::cttz
129             | sym::cttz_nonzero
130             | sym::ctlz
131             | sym::ctlz_nonzero
132             | sym::bswap
133             | sym::bitreverse => {
134                 let ty = substs.type_at(0);
135                 let layout_of = self.layout_of(ty)?;
136                 let val = self.read_scalar(args[0])?.not_undef()?;
137                 let bits = self.force_bits(val, layout_of.size)?;
138                 let kind = match layout_of.abi {
139                     ty::layout::Abi::Scalar(ref scalar) => scalar.value,
140                     _ => throw_unsup!(TypeNotPrimitive(ty)),
141                 };
142                 let (nonzero, intrinsic_name) = match intrinsic_name {
143                     sym::cttz_nonzero => (true, sym::cttz),
144                     sym::ctlz_nonzero => (true, sym::ctlz),
145                     other => (false, other),
146                 };
147                 if nonzero && bits == 0 {
148                     throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
149                 }
150                 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
151                 self.write_scalar(out_val, dest)?;
152             }
153             sym::wrapping_add
154             | sym::wrapping_sub
155             | sym::wrapping_mul
156             | sym::add_with_overflow
157             | sym::sub_with_overflow
158             | sym::mul_with_overflow => {
159                 let lhs = self.read_immediate(args[0])?;
160                 let rhs = self.read_immediate(args[1])?;
161                 let (bin_op, ignore_overflow) = match intrinsic_name {
162                     sym::wrapping_add => (BinOp::Add, true),
163                     sym::wrapping_sub => (BinOp::Sub, true),
164                     sym::wrapping_mul => (BinOp::Mul, true),
165                     sym::add_with_overflow => (BinOp::Add, false),
166                     sym::sub_with_overflow => (BinOp::Sub, false),
167                     sym::mul_with_overflow => (BinOp::Mul, false),
168                     _ => bug!("Already checked for int ops"),
169                 };
170                 if ignore_overflow {
171                     self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
172                 } else {
173                     self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
174                 }
175             }
176             sym::saturating_add | sym::saturating_sub => {
177                 let l = self.read_immediate(args[0])?;
178                 let r = self.read_immediate(args[1])?;
179                 let is_add = intrinsic_name == sym::saturating_add;
180                 let (val, overflowed, _ty) =
181                     self.overflowing_binary_op(if is_add { BinOp::Add } else { BinOp::Sub }, l, r)?;
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(
196                                 (1u128 << (num_bits - 1)) - 1, // max positive
197                                 Size::from_bits(num_bits),
198                             )
199                         } else {
200                             // Positive overflow not possible for similar reason
201                             // max negative
202                             Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
203                         }
204                     } else {
205                         // unsigned
206                         if is_add {
207                             // max unsigned
208                             Scalar::from_uint(
209                                 u128::max_value() >> (128 - num_bits),
210                                 Size::from_bits(num_bits),
211                             )
212                         } else {
213                             // underflow to 0
214                             Scalar::from_uint(0u128, Size::from_bits(num_bits))
215                         }
216                     }
217                 } else {
218                     val
219                 };
220                 self.write_scalar(val, dest)?;
221             }
222             sym::unchecked_shl | sym::unchecked_shr => {
223                 let l = self.read_immediate(args[0])?;
224                 let r = self.read_immediate(args[1])?;
225                 let bin_op = match intrinsic_name {
226                     sym::unchecked_shl => BinOp::Shl,
227                     sym::unchecked_shr => BinOp::Shr,
228                     _ => bug!("Already checked for int ops"),
229                 };
230                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
231                 if overflowed {
232                     let layout = self.layout_of(substs.type_at(0))?;
233                     let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
234                     throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
235                 }
236                 self.write_scalar(val, dest)?;
237             }
238             sym::rotate_left | sym::rotate_right => {
239                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
240                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
241                 let layout = self.layout_of(substs.type_at(0))?;
242                 let val = self.read_scalar(args[0])?.not_undef()?;
243                 let val_bits = self.force_bits(val, layout.size)?;
244                 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
245                 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
246                 let width_bits = layout.size.bits() as u128;
247                 let shift_bits = raw_shift_bits % width_bits;
248                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
249                 let result_bits = if intrinsic_name == sym::rotate_left {
250                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
251                 } else {
252                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
253                 };
254                 let truncated_bits = self.truncate(result_bits, layout);
255                 let result = Scalar::from_uint(truncated_bits, layout.size);
256                 self.write_scalar(result, dest)?;
257             }
258
259             sym::ptr_offset_from => {
260                 let isize_layout = self.layout_of(self.tcx.types.isize)?;
261                 let a = self.read_immediate(args[0])?.to_scalar()?;
262                 let b = self.read_immediate(args[1])?.to_scalar()?;
263
264                 // Special case: if both scalars are *equal integers*
265                 // and not NULL, we pretend there is an allocation of size 0 right there,
266                 // and their offset is 0. (There's never a valid object at NULL, making it an
267                 // exception from the exception.)
268                 // This is the dual to the special exception for offset-by-0
269                 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
270                 //
271                 // Control flow is weird because we cannot early-return (to reach the
272                 // `go_to_block` at the end).
273                 let done = if a.is_bits() && b.is_bits() {
274                     let a = a.to_machine_usize(self)?;
275                     let b = b.to_machine_usize(self)?;
276                     if a == b && a != 0 {
277                         self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
278                         true
279                     } else {
280                         false
281                     }
282                 } else {
283                     false
284                 };
285
286                 if !done {
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 {
291                         throw_ub_format!(
292                             "ptr_offset_from cannot compute offset of pointers into different \
293                             allocations.",
294                         );
295                     }
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) =
300                         self.overflowing_binary_op(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)?;
305                 }
306             }
307
308             sym::transmute => {
309                 self.copy_op_transmute(args[0], dest)?;
310             }
311             sym::simd_insert => {
312                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
313                 let elem = args[2];
314                 let input = args[0];
315                 let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx.tcx);
316                 assert!(
317                     index < len,
318                     "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
319                     index,
320                     e_ty,
321                     len
322                 );
323                 assert_eq!(
324                     input.layout, dest.layout,
325                     "Return type `{}` must match vector type `{}`",
326                     dest.layout.ty, input.layout.ty
327                 );
328                 assert_eq!(
329                     elem.layout.ty, e_ty,
330                     "Scalar element type `{}` must match vector element type `{}`",
331                     elem.layout.ty, e_ty
332                 );
333
334                 for i in 0..len {
335                     let place = self.place_field(dest, i)?;
336                     let value = if i == index { elem } else { self.operand_field(input, i)? };
337                     self.copy_op(value, place)?;
338                 }
339             }
340             sym::simd_extract => {
341                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
342                 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx);
343                 assert!(
344                     index < len,
345                     "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
346                     index,
347                     e_ty,
348                     len
349                 );
350                 assert_eq!(
351                     e_ty, dest.layout.ty,
352                     "Return type `{}` must match vector element type `{}`",
353                     dest.layout.ty, e_ty
354                 );
355                 self.copy_op(self.operand_field(args[0], index)?, dest)?;
356             }
357             _ => return Ok(false),
358         }
359
360         self.dump_place(*dest);
361         self.go_to_block(ret);
362         Ok(true)
363     }
364
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(
369         &mut self,
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);
378
379             let msg_place = self.deref_operand(args[0])?;
380             let msg = Symbol::intern(self.read_str(msg_place)?);
381
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)?,
387             );
388
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)
397             let msg = args[0];
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)?,
403             );
404
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 })
412         } else {
413             return Ok(false);
414         }
415     }
416
417     pub fn exact_div(
418         &mut self,
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")
432             } else {
433                 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b,)
434             }
435         }
436         self.binop_ignore_overflow(BinOp::Div, a, b, dest)
437     }
438 }