]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/intrinsics.rs
Rollup merge of #67508 - davesque:master, r=Dylan-DPC
[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 syntax_pos::symbol::{sym, Symbol};
6 use syntax_pos::Span;
7 use rustc::ty;
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::{
13     self, BinOp,
14     interpret::{InterpResult, Scalar, ConstValue}
15 };
16
17 use super::{
18     Machine, PlaceTy, OpTy, InterpCx, ImmTy,
19 };
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 - size.bits() as u128;
34     let bits_out = match name {
35         sym::ctpop => bits.count_ones() as u128,
36         sym::ctlz => bits.leading_zeros() as u128 - extra,
37         sym::cttz => (bits << extra).trailing_zeros() as u128 - 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, &'tcx ty::Const<'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             tcx.mk_const(ty::Const {
59                 val: ty::ConstKind::Value(ConstValue::Slice {
60                     data: alloc,
61                     start: 0,
62                     end: alloc.len(),
63                 }),
64                 ty: tcx.mk_static_str(),
65             })
66         },
67         sym::needs_drop => ty::Const::from_bool(tcx, tp_ty.needs_drop(tcx, param_env)),
68         sym::size_of |
69         sym::min_align_of |
70         sym::pref_align_of => {
71             let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
72             let n = match name {
73                 sym::pref_align_of => layout.align.pref.bytes(),
74                 sym::min_align_of => layout.align.abi.bytes(),
75                 sym::size_of => layout.size.bytes(),
76                 _ => bug!(),
77             };
78             ty::Const::from_usize(tcx, n)
79         },
80         sym::type_id => ty::Const::from_bits(
81             tcx,
82             tcx.type_id_hash(tp_ty).into(),
83             param_env.and(tcx.types.u64),
84         ),
85         other => bug!("`{}` is not a zero arg intrinsic", other),
86     })
87 }
88
89 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
90     /// Returns `true` if emulation happened.
91     pub fn emulate_intrinsic(
92         &mut self,
93         span: Span,
94         instance: ty::Instance<'tcx>,
95         args: &[OpTy<'tcx, M::PointerTag>],
96         ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
97     ) -> InterpResult<'tcx, bool> {
98         let substs = instance.substs;
99         let intrinsic_name = self.tcx.item_name(instance.def_id());
100
101         // We currently do not handle any intrinsics that are *allowed* to diverge,
102         // but `transmute` could lack a return place in case of UB.
103         let (dest, ret) = match ret {
104             Some(p) => p,
105             None => match intrinsic_name {
106                 sym::transmute => throw_ub!(Unreachable),
107                 _ => return Ok(false),
108             }
109         };
110
111         // Keep the patterns in this match ordered the same as the list in
112         // `src/librustc/ty/constness.rs`
113         match intrinsic_name {
114             sym::caller_location => {
115                 let span = self.find_closest_untracked_caller_location().unwrap_or(span);
116                 let location = self.alloc_caller_location_for_span(span);
117                 self.write_scalar(location.ptr, dest)?;
118             }
119
120             sym::min_align_of |
121             sym::pref_align_of |
122             sym::needs_drop |
123             sym::size_of |
124             sym::type_id |
125             sym::type_name => {
126                 let val = self.tcx.const_eval_instance(self.param_env,
127                                                        instance,
128                                                        Some(self.tcx.span))?;
129                 let val = self.eval_const_to_op(val, None)?;
130                 self.copy_op(val, dest)?;
131             }
132
133             | sym::ctpop
134             | sym::cttz
135             | sym::cttz_nonzero
136             | sym::ctlz
137             | sym::ctlz_nonzero
138             | sym::bswap
139             | sym::bitreverse => {
140                 let ty = substs.type_at(0);
141                 let layout_of = self.layout_of(ty)?;
142                 let val = self.read_scalar(args[0])?.not_undef()?;
143                 let bits = self.force_bits(val, layout_of.size)?;
144                 let kind = match layout_of.abi {
145                     ty::layout::Abi::Scalar(ref scalar) => scalar.value,
146                     _ => throw_unsup!(TypeNotPrimitive(ty)),
147                 };
148                 let (nonzero, intrinsic_name) = match intrinsic_name {
149                     sym::cttz_nonzero => (true, sym::cttz),
150                     sym::ctlz_nonzero => (true, sym::ctlz),
151                     other => (false, other),
152                 };
153                 if nonzero && bits == 0 {
154                     throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
155                 }
156                 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
157                 self.write_scalar(out_val, dest)?;
158             }
159             | sym::wrapping_add
160             | sym::wrapping_sub
161             | sym::wrapping_mul
162             | sym::add_with_overflow
163             | sym::sub_with_overflow
164             | sym::mul_with_overflow => {
165                 let lhs = self.read_immediate(args[0])?;
166                 let rhs = self.read_immediate(args[1])?;
167                 let (bin_op, ignore_overflow) = match intrinsic_name {
168                     sym::wrapping_add => (BinOp::Add, true),
169                     sym::wrapping_sub => (BinOp::Sub, true),
170                     sym::wrapping_mul => (BinOp::Mul, true),
171                     sym::add_with_overflow => (BinOp::Add, false),
172                     sym::sub_with_overflow => (BinOp::Sub, false),
173                     sym::mul_with_overflow => (BinOp::Mul, false),
174                     _ => bug!("Already checked for int ops")
175                 };
176                 if ignore_overflow {
177                     self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
178                 } else {
179                     self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
180                 }
181             }
182             sym::saturating_add | sym::saturating_sub => {
183                 let l = self.read_immediate(args[0])?;
184                 let r = self.read_immediate(args[1])?;
185                 let is_add = intrinsic_name == sym::saturating_add;
186                 let (val, overflowed, _ty) = self.overflowing_binary_op(if is_add {
187                     BinOp::Add
188                 } else {
189                     BinOp::Sub
190                 }, l, r)?;
191                 let val = if overflowed {
192                     let num_bits = l.layout.size.bits();
193                     if l.layout.abi.is_signed() {
194                         // For signed ints the saturated value depends on the sign of the first
195                         // term since the sign of the second term can be inferred from this and
196                         // the fact that the operation has overflowed (if either is 0 no
197                         // overflow can occur)
198                         let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
199                         let first_term_positive = first_term & (1 << (num_bits-1)) == 0;
200                         if first_term_positive {
201                             // Negative overflow not possible since the positive first term
202                             // can only increase an (in range) negative term for addition
203                             // or corresponding negated positive term for subtraction
204                             Scalar::from_uint((1u128 << (num_bits - 1)) - 1,  // max positive
205                                 Size::from_bits(num_bits))
206                         } else {
207                             // Positive overflow not possible for similar reason
208                             // max negative
209                             Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
210                         }
211                     } else {  // unsigned
212                         if is_add {
213                             // max unsigned
214                             Scalar::from_uint(u128::max_value() >> (128 - num_bits),
215                                 Size::from_bits(num_bits))
216                         } else {  // underflow to 0
217                             Scalar::from_uint(0u128, Size::from_bits(num_bits))
218                         }
219                     }
220                 } else {
221                     val
222                 };
223                 self.write_scalar(val, dest)?;
224             }
225             sym::unchecked_shl | sym::unchecked_shr => {
226                 let l = self.read_immediate(args[0])?;
227                 let r = self.read_immediate(args[1])?;
228                 let bin_op = match intrinsic_name {
229                     sym::unchecked_shl => BinOp::Shl,
230                     sym::unchecked_shr => BinOp::Shr,
231                     _ => bug!("Already checked for int ops")
232                 };
233                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
234                 if overflowed {
235                     let layout = self.layout_of(substs.type_at(0))?;
236                     let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
237                     throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
238                 }
239                 self.write_scalar(val, dest)?;
240             }
241             sym::rotate_left | sym::rotate_right => {
242                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
243                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
244                 let layout = self.layout_of(substs.type_at(0))?;
245                 let val = self.read_scalar(args[0])?.not_undef()?;
246                 let val_bits = self.force_bits(val, layout.size)?;
247                 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
248                 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
249                 let width_bits = layout.size.bits() as u128;
250                 let shift_bits = raw_shift_bits % width_bits;
251                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
252                 let result_bits = if intrinsic_name == sym::rotate_left {
253                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
254                 } else {
255                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
256                 };
257                 let truncated_bits = self.truncate(result_bits, layout);
258                 let result = Scalar::from_uint(truncated_bits, layout.size);
259                 self.write_scalar(result, dest)?;
260             }
261
262             sym::ptr_offset_from => {
263                 let isize_layout = self.layout_of(self.tcx.types.isize)?;
264                 let a = self.read_immediate(args[0])?.to_scalar()?;
265                 let b = self.read_immediate(args[1])?.to_scalar()?;
266
267                 // Special case: if both scalars are *equal integers*
268                 // and not NULL, we pretend there is an allocation of size 0 right there,
269                 // and their offset is 0. (There's never a valid object at NULL, making it an
270                 // exception from the exception.)
271                 // This is the dual to the special exception for offset-by-0
272                 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
273                 //
274                 // Control flow is weird because we cannot early-return (to reach the
275                 // `go_to_block` at the end).
276                 let done = if a.is_bits() && b.is_bits() {
277                     let a = a.to_machine_usize(self)?;
278                     let b = b.to_machine_usize(self)?;
279                     if a == b && a != 0 {
280                         self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
281                         true
282                     } else { false }
283                 } else { false };
284
285                 if !done {
286                     // General case: we need two pointers.
287                     let a = self.force_ptr(a)?;
288                     let b = self.force_ptr(b)?;
289                     if a.alloc_id != b.alloc_id {
290                         throw_ub_format!(
291                             "ptr_offset_from cannot compute offset of pointers into different \
292                             allocations.",
293                         );
294                     }
295                     let usize_layout = self.layout_of(self.tcx.types.usize)?;
296                     let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
297                     let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
298                     let (val, _overflowed, _ty) = self.overflowing_binary_op(
299                         BinOp::Sub, a_offset, b_offset,
300                     )?;
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, e_ty, len
320                 );
321                 assert_eq!(
322                     input.layout, dest.layout,
323                     "Return type `{}` must match vector type `{}`",
324                     dest.layout.ty, input.layout.ty
325                 );
326                 assert_eq!(
327                     elem.layout.ty, e_ty,
328                     "Scalar element type `{}` must match vector element type `{}`",
329                     elem.layout.ty, e_ty
330                 );
331
332                 for i in 0..len {
333                     let place = self.place_field(dest, i)?;
334                     let value = if i == index {
335                         elem
336                     } else {
337                         self.operand_field(input, i)?
338                     };
339                     self.copy_op(value, place)?;
340                 }
341             }
342             sym::simd_extract => {
343                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
344                 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx);
345                 assert!(
346                     index < len,
347                     "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
348                     index, e_ty, 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!(
434                     "exact_div: {} cannot be divided by {} without remainder",
435                     a,
436                     b,
437                 )
438             }
439         }
440         self.binop_ignore_overflow(BinOp::Div, a, b, dest)
441     }
442 }