]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/intrinsics.rs
added test, Operand::const_from_scalar, require_lang_item, & comments
[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 std::convert::TryFrom;
6
7 use rustc_hir::def_id::DefId;
8 use rustc_middle::mir::{
9     self,
10     interpret::{uabs, ConstValue, GlobalId, InterpResult, Scalar},
11     BinOp,
12 };
13 use rustc_middle::ty;
14 use rustc_middle::ty::subst::SubstsRef;
15 use rustc_middle::ty::{Ty, TyCtxt};
16 use rustc_span::symbol::{sym, Symbol};
17 use rustc_target::abi::{Abi, LayoutOf as _, Primitive, Size};
18
19 use super::{CheckInAllocMsg, ImmTy, InterpCx, Machine, OpTy, PlaceTy};
20
21 mod caller_location;
22 mod type_name;
23
24 fn numeric_intrinsic<'tcx, Tag>(
25     name: Symbol,
26     bits: u128,
27     kind: Primitive,
28 ) -> InterpResult<'tcx, Scalar<Tag>> {
29     let size = match kind {
30         Primitive::Int(integer, _) => integer.size(),
31         _ => bug!("invalid `{}` argument: {:?}", name, bits),
32     };
33     let extra = 128 - u128::from(size.bits());
34     let bits_out = match name {
35         sym::ctpop => u128::from(bits.count_ones()),
36         sym::ctlz => u128::from(bits.leading_zeros()) - extra,
37         sym::cttz => u128::from((bits << extra).trailing_zeros()) - extra,
38         sym::bswap => (bits << extra).swap_bytes(),
39         sym::bitreverse => (bits << extra).reverse_bits(),
40         _ => bug!("not a numeric intrinsic: {}", name),
41     };
42     Ok(Scalar::from_uint(bits_out, size))
43 }
44
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>(
48     tcx: TyCtxt<'tcx>,
49     param_env: ty::ParamEnv<'tcx>,
50     def_id: DefId,
51     substs: SubstsRef<'tcx>,
52 ) -> InterpResult<'tcx, ConstValue<'tcx>> {
53     let tp_ty = substs.type_at(0);
54     let name = tcx.item_name(def_id);
55     Ok(match name {
56         sym::type_name => {
57             let alloc = type_name::alloc_type_name(tcx, tp_ty);
58             ConstValue::Slice { data: alloc, start: 0, end: alloc.len() }
59         }
60         sym::needs_drop => ConstValue::from_bool(tp_ty.needs_drop(tcx, param_env)),
61         sym::size_of | sym::min_align_of | sym::pref_align_of => {
62             let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
63             let n = match name {
64                 sym::pref_align_of => layout.align.pref.bytes(),
65                 sym::min_align_of => layout.align.abi.bytes(),
66                 sym::size_of => layout.size.bytes(),
67                 _ => bug!(),
68             };
69             ConstValue::from_machine_usize(n, &tcx)
70         }
71         sym::type_id => ConstValue::from_u64(tcx.type_id_hash(tp_ty)),
72         other => bug!("`{}` is not a zero arg intrinsic", other),
73     })
74 }
75
76 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
77     /// Returns `true` if emulation happened.
78     pub fn emulate_intrinsic(
79         &mut self,
80         instance: ty::Instance<'tcx>,
81         args: &[OpTy<'tcx, M::PointerTag>],
82         ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
83     ) -> InterpResult<'tcx, bool> {
84         let substs = instance.substs;
85         let intrinsic_name = self.tcx.item_name(instance.def_id());
86
87         // First handle intrinsics without return place.
88         let (dest, ret) = match ret {
89             None => match intrinsic_name {
90                 sym::transmute => throw_ub_format!("transmuting to uninhabited type"),
91                 sym::abort => M::abort(self)?,
92                 // Unsupported diverging intrinsic.
93                 _ => return Ok(false),
94             },
95             Some(p) => p,
96         };
97
98         // Keep the patterns in this match ordered the same as the list in
99         // `src/librustc_middle/ty/constness.rs`
100         match intrinsic_name {
101             sym::caller_location => {
102                 let span = self.find_closest_untracked_caller_location();
103                 let location = self.alloc_caller_location_for_span(span);
104                 self.write_scalar(location.ptr, dest)?;
105             }
106
107             sym::min_align_of
108             | sym::pref_align_of
109             | sym::needs_drop
110             | sym::size_of
111             | sym::type_id
112             | sym::type_name => {
113                 let gid = GlobalId { instance, promoted: None };
114                 let ty = match intrinsic_name {
115                     sym::min_align_of | sym::pref_align_of | sym::size_of => self.tcx.types.usize,
116                     sym::needs_drop => self.tcx.types.bool,
117                     sym::type_id => self.tcx.types.u64,
118                     sym::type_name => self.tcx.mk_static_str(),
119                     _ => bug!("already checked for nullary intrinsics"),
120                 };
121                 let val = self.const_eval(gid, ty)?;
122                 self.copy_op(val, dest)?;
123             }
124
125             sym::ctpop
126             | sym::cttz
127             | sym::cttz_nonzero
128             | sym::ctlz
129             | sym::ctlz_nonzero
130             | sym::bswap
131             | sym::bitreverse => {
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                     Abi::Scalar(ref scalar) => scalar.value,
138                     _ => bug!("{} called on invalid type {:?}", intrinsic_name, ty),
139                 };
140                 let (nonzero, intrinsic_name) = match intrinsic_name {
141                     sym::cttz_nonzero => (true, sym::cttz),
142                     sym::ctlz_nonzero => (true, sym::ctlz),
143                     other => (false, other),
144                 };
145                 if nonzero && bits == 0 {
146                     throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
147                 }
148                 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
149                 self.write_scalar(out_val, dest)?;
150             }
151             sym::wrapping_add
152             | sym::wrapping_sub
153             | sym::wrapping_mul
154             | sym::add_with_overflow
155             | sym::sub_with_overflow
156             | sym::mul_with_overflow => {
157                 let lhs = self.read_immediate(args[0])?;
158                 let rhs = self.read_immediate(args[1])?;
159                 let (bin_op, ignore_overflow) = match intrinsic_name {
160                     sym::wrapping_add => (BinOp::Add, true),
161                     sym::wrapping_sub => (BinOp::Sub, true),
162                     sym::wrapping_mul => (BinOp::Mul, true),
163                     sym::add_with_overflow => (BinOp::Add, false),
164                     sym::sub_with_overflow => (BinOp::Sub, false),
165                     sym::mul_with_overflow => (BinOp::Mul, false),
166                     _ => bug!("Already checked for int ops"),
167                 };
168                 if ignore_overflow {
169                     self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
170                 } else {
171                     self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
172                 }
173             }
174             sym::saturating_add | sym::saturating_sub => {
175                 let l = self.read_immediate(args[0])?;
176                 let r = self.read_immediate(args[1])?;
177                 let is_add = intrinsic_name == sym::saturating_add;
178                 let (val, overflowed, _ty) =
179                     self.overflowing_binary_op(if is_add { BinOp::Add } else { BinOp::Sub }, l, r)?;
180                 let val = if overflowed {
181                     let num_bits = l.layout.size.bits();
182                     if l.layout.abi.is_signed() {
183                         // For signed ints the saturated value depends on the sign of the first
184                         // term since the sign of the second term can be inferred from this and
185                         // the fact that the operation has overflowed (if either is 0 no
186                         // overflow can occur)
187                         let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
188                         let first_term_positive = first_term & (1 << (num_bits - 1)) == 0;
189                         if first_term_positive {
190                             // Negative overflow not possible since the positive first term
191                             // can only increase an (in range) negative term for addition
192                             // or corresponding negated positive term for subtraction
193                             Scalar::from_uint(
194                                 (1u128 << (num_bits - 1)) - 1, // max positive
195                                 Size::from_bits(num_bits),
196                             )
197                         } else {
198                             // Positive overflow not possible for similar reason
199                             // max negative
200                             Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
201                         }
202                     } else {
203                         // unsigned
204                         if is_add {
205                             // max unsigned
206                             Scalar::from_uint(
207                                 u128::MAX >> (128 - num_bits),
208                                 Size::from_bits(num_bits),
209                             )
210                         } else {
211                             // underflow to 0
212                             Scalar::from_uint(0u128, Size::from_bits(num_bits))
213                         }
214                     }
215                 } else {
216                     val
217                 };
218                 self.write_scalar(val, dest)?;
219             }
220             sym::discriminant_value => {
221                 let place = self.deref_operand(args[0])?;
222                 let discr_val = self.read_discriminant(place.into())?.0;
223                 self.write_scalar(discr_val, dest)?;
224             }
225             sym::unchecked_shl
226             | sym::unchecked_shr
227             | sym::unchecked_add
228             | sym::unchecked_sub
229             | sym::unchecked_mul
230             | sym::unchecked_div
231             | sym::unchecked_rem => {
232                 let l = self.read_immediate(args[0])?;
233                 let r = self.read_immediate(args[1])?;
234                 let bin_op = match intrinsic_name {
235                     sym::unchecked_shl => BinOp::Shl,
236                     sym::unchecked_shr => BinOp::Shr,
237                     sym::unchecked_add => BinOp::Add,
238                     sym::unchecked_sub => BinOp::Sub,
239                     sym::unchecked_mul => BinOp::Mul,
240                     sym::unchecked_div => BinOp::Div,
241                     sym::unchecked_rem => BinOp::Rem,
242                     _ => bug!("Already checked for int ops"),
243                 };
244                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
245                 if overflowed {
246                     let layout = self.layout_of(substs.type_at(0))?;
247                     let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
248                     if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
249                         throw_ub_format!("overflowing shift by {} in `{}`", r_val, intrinsic_name);
250                     } else {
251                         throw_ub_format!("overflow executing `{}`", intrinsic_name);
252                     }
253                 }
254                 self.write_scalar(val, dest)?;
255             }
256             sym::rotate_left | sym::rotate_right => {
257                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
258                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
259                 let layout = self.layout_of(substs.type_at(0))?;
260                 let val = self.read_scalar(args[0])?.not_undef()?;
261                 let val_bits = self.force_bits(val, layout.size)?;
262                 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
263                 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
264                 let width_bits = u128::from(layout.size.bits());
265                 let shift_bits = raw_shift_bits % width_bits;
266                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
267                 let result_bits = if intrinsic_name == sym::rotate_left {
268                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
269                 } else {
270                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
271                 };
272                 let truncated_bits = self.truncate(result_bits, layout);
273                 let result = Scalar::from_uint(truncated_bits, layout.size);
274                 self.write_scalar(result, dest)?;
275             }
276             sym::offset => {
277                 let ptr = self.read_scalar(args[0])?.not_undef()?;
278                 let offset_count = self.read_scalar(args[1])?.to_machine_isize(self)?;
279                 let pointee_ty = substs.type_at(0);
280
281                 let offset_ptr = self.ptr_offset_inbounds(ptr, pointee_ty, offset_count)?;
282                 self.write_scalar(offset_ptr, dest)?;
283             }
284             sym::arith_offset => {
285                 let ptr = self.read_scalar(args[0])?.not_undef()?;
286                 let offset_count = self.read_scalar(args[1])?.to_machine_isize(self)?;
287                 let pointee_ty = substs.type_at(0);
288
289                 let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
290                 let offset_bytes = offset_count.wrapping_mul(pointee_size);
291                 let offset_ptr = ptr.ptr_wrapping_signed_offset(offset_bytes, self);
292                 self.write_scalar(offset_ptr, dest)?;
293             }
294             sym::ptr_offset_from => {
295                 let a = self.read_immediate(args[0])?.to_scalar()?;
296                 let b = self.read_immediate(args[1])?.to_scalar()?;
297
298                 // Special case: if both scalars are *equal integers*
299                 // and not NULL, we pretend there is an allocation of size 0 right there,
300                 // and their offset is 0. (There's never a valid object at NULL, making it an
301                 // exception from the exception.)
302                 // This is the dual to the special exception for offset-by-0
303                 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
304                 //
305                 // Control flow is weird because we cannot early-return (to reach the
306                 // `go_to_block` at the end).
307                 let done = if a.is_bits() && b.is_bits() {
308                     let a = a.to_machine_usize(self)?;
309                     let b = b.to_machine_usize(self)?;
310                     if a == b && a != 0 {
311                         self.write_scalar(Scalar::from_machine_isize(0, self), dest)?;
312                         true
313                     } else {
314                         false
315                     }
316                 } else {
317                     false
318                 };
319
320                 if !done {
321                     // General case: we need two pointers.
322                     let a = self.force_ptr(a)?;
323                     let b = self.force_ptr(b)?;
324                     if a.alloc_id != b.alloc_id {
325                         throw_ub_format!(
326                             "ptr_offset_from cannot compute offset of pointers into different \
327                             allocations.",
328                         );
329                     }
330                     let usize_layout = self.layout_of(self.tcx.types.usize)?;
331                     let isize_layout = self.layout_of(self.tcx.types.isize)?;
332                     let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
333                     let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
334                     let (val, _overflowed, _ty) =
335                         self.overflowing_binary_op(BinOp::Sub, a_offset, b_offset)?;
336                     let pointee_layout = self.layout_of(substs.type_at(0))?;
337                     let val = ImmTy::from_scalar(val, isize_layout);
338                     let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
339                     self.exact_div(val, size, dest)?;
340                 }
341             }
342
343             sym::transmute => {
344                 self.copy_op_transmute(args[0], dest)?;
345             }
346             sym::simd_insert => {
347                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
348                 let elem = args[2];
349                 let input = args[0];
350                 let (len, e_ty) = input.layout.ty.simd_size_and_type(*self.tcx);
351                 assert!(
352                     index < len,
353                     "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
354                     index,
355                     e_ty,
356                     len
357                 );
358                 assert_eq!(
359                     input.layout, dest.layout,
360                     "Return type `{}` must match vector type `{}`",
361                     dest.layout.ty, input.layout.ty
362                 );
363                 assert_eq!(
364                     elem.layout.ty, e_ty,
365                     "Scalar element type `{}` must match vector element type `{}`",
366                     elem.layout.ty, e_ty
367                 );
368
369                 for i in 0..len {
370                     let place = self.place_index(dest, i)?;
371                     let value = if i == index { elem } else { self.operand_index(input, i)? };
372                     self.copy_op(value, place)?;
373                 }
374             }
375             sym::simd_extract => {
376                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
377                 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(*self.tcx);
378                 assert!(
379                     index < len,
380                     "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
381                     index,
382                     e_ty,
383                     len
384                 );
385                 assert_eq!(
386                     e_ty, dest.layout.ty,
387                     "Return type `{}` must match vector element type `{}`",
388                     dest.layout.ty, e_ty
389                 );
390                 self.copy_op(self.operand_index(args[0], index)?, dest)?;
391             }
392             // FIXME(#73156): Handle source code coverage in const eval
393             sym::count_code_region => (),
394             _ => return Ok(false),
395         }
396
397         self.dump_place(*dest);
398         self.go_to_block(ret);
399         Ok(true)
400     }
401
402     pub fn exact_div(
403         &mut self,
404         a: ImmTy<'tcx, M::PointerTag>,
405         b: ImmTy<'tcx, M::PointerTag>,
406         dest: PlaceTy<'tcx, M::PointerTag>,
407     ) -> InterpResult<'tcx> {
408         // Performs an exact division, resulting in undefined behavior where
409         // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
410         // First, check x % y != 0 (or if that computation overflows).
411         let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, a, b)?;
412         if overflow || res.assert_bits(a.layout.size) != 0 {
413             // Then, check if `b` is -1, which is the "MIN / -1" case.
414             let minus1 = Scalar::from_int(-1, dest.layout.size);
415             let b_scalar = b.to_scalar().unwrap();
416             if b_scalar == minus1 {
417                 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
418             } else {
419                 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b,)
420             }
421         }
422         // `Rem` says this is all right, so we can let `Div` do its job.
423         self.binop_ignore_overflow(BinOp::Div, a, b, dest)
424     }
425
426     /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
427     /// allocation. For integer pointers, we consider each of them their own tiny allocation of size
428     /// 0, so offset-by-0 (and only 0) is okay -- except that NULL cannot be offset by _any_ value.
429     pub fn ptr_offset_inbounds(
430         &self,
431         ptr: Scalar<M::PointerTag>,
432         pointee_ty: Ty<'tcx>,
433         offset_count: i64,
434     ) -> InterpResult<'tcx, Scalar<M::PointerTag>> {
435         // We cannot overflow i64 as a type's size must be <= isize::MAX.
436         let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
437         // The computed offset, in bytes, cannot overflow an isize.
438         let offset_bytes =
439             offset_count.checked_mul(pointee_size).ok_or(err_ub!(PointerArithOverflow))?;
440         // The offset being in bounds cannot rely on "wrapping around" the address space.
441         // So, first rule out overflows in the pointer arithmetic.
442         let offset_ptr = ptr.ptr_signed_offset(offset_bytes, self)?;
443         // ptr and offset_ptr must be in bounds of the same allocated object. This means all of the
444         // memory between these pointers must be accessible. Note that we do not require the
445         // pointers to be properly aligned (unlike a read/write operation).
446         let min_ptr = if offset_bytes >= 0 { ptr } else { offset_ptr };
447         let size: u64 = uabs(offset_bytes);
448         // This call handles checking for integer/NULL pointers.
449         self.memory.check_ptr_access_align(
450             min_ptr,
451             Size::from_bytes(size),
452             None,
453             CheckInAllocMsg::InboundsTest,
454         )?;
455         Ok(offset_ptr)
456     }
457 }