]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/intrinsics.rs
Auto merge of #66952 - 0dvictor:print, r=rkruppe
[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, GlobalId, 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 location = self.alloc_caller_location_for_span(span);
116                 self.write_scalar(location.ptr, dest)?;
117             }
118
119             sym::min_align_of |
120             sym::pref_align_of |
121             sym::needs_drop |
122             sym::size_of |
123             sym::type_id |
124             sym::type_name => {
125                 let gid = GlobalId {
126                     instance,
127                     promoted: None,
128                 };
129                 let val = self.tcx.const_eval(self.param_env.and(gid))?;
130                 let val = self.eval_const_to_op(val, None)?;
131                 self.copy_op(val, dest)?;
132             }
133
134             | sym::ctpop
135             | sym::cttz
136             | sym::cttz_nonzero
137             | sym::ctlz
138             | sym::ctlz_nonzero
139             | sym::bswap
140             | sym::bitreverse => {
141                 let ty = substs.type_at(0);
142                 let layout_of = self.layout_of(ty)?;
143                 let val = self.read_scalar(args[0])?.not_undef()?;
144                 let bits = self.force_bits(val, layout_of.size)?;
145                 let kind = match layout_of.abi {
146                     ty::layout::Abi::Scalar(ref scalar) => scalar.value,
147                     _ => throw_unsup!(TypeNotPrimitive(ty)),
148                 };
149                 let (nonzero, intrinsic_name) = match intrinsic_name {
150                     sym::cttz_nonzero => (true, sym::cttz),
151                     sym::ctlz_nonzero => (true, sym::ctlz),
152                     other => (false, other),
153                 };
154                 if nonzero && bits == 0 {
155                     throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
156                 }
157                 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
158                 self.write_scalar(out_val, dest)?;
159             }
160             | sym::wrapping_add
161             | sym::wrapping_sub
162             | sym::wrapping_mul
163             | sym::add_with_overflow
164             | sym::sub_with_overflow
165             | sym::mul_with_overflow => {
166                 let lhs = self.read_immediate(args[0])?;
167                 let rhs = self.read_immediate(args[1])?;
168                 let (bin_op, ignore_overflow) = match intrinsic_name {
169                     sym::wrapping_add => (BinOp::Add, true),
170                     sym::wrapping_sub => (BinOp::Sub, true),
171                     sym::wrapping_mul => (BinOp::Mul, true),
172                     sym::add_with_overflow => (BinOp::Add, false),
173                     sym::sub_with_overflow => (BinOp::Sub, false),
174                     sym::mul_with_overflow => (BinOp::Mul, false),
175                     _ => bug!("Already checked for int ops")
176                 };
177                 if ignore_overflow {
178                     self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
179                 } else {
180                     self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
181                 }
182             }
183             sym::saturating_add | sym::saturating_sub => {
184                 let l = self.read_immediate(args[0])?;
185                 let r = self.read_immediate(args[1])?;
186                 let is_add = intrinsic_name == sym::saturating_add;
187                 let (val, overflowed, _ty) = self.overflowing_binary_op(if is_add {
188                     BinOp::Add
189                 } else {
190                     BinOp::Sub
191                 }, l, r)?;
192                 let val = if overflowed {
193                     let num_bits = l.layout.size.bits();
194                     if l.layout.abi.is_signed() {
195                         // For signed ints the saturated value depends on the sign of the first
196                         // term since the sign of the second term can be inferred from this and
197                         // the fact that the operation has overflowed (if either is 0 no
198                         // overflow can occur)
199                         let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
200                         let first_term_positive = first_term & (1 << (num_bits-1)) == 0;
201                         if first_term_positive {
202                             // Negative overflow not possible since the positive first term
203                             // can only increase an (in range) negative term for addition
204                             // or corresponding negated positive term for subtraction
205                             Scalar::from_uint((1u128 << (num_bits - 1)) - 1,  // max positive
206                                 Size::from_bits(num_bits))
207                         } else {
208                             // Positive overflow not possible for similar reason
209                             // max negative
210                             Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
211                         }
212                     } else {  // unsigned
213                         if is_add {
214                             // max unsigned
215                             Scalar::from_uint(u128::max_value() >> (128 - num_bits),
216                                 Size::from_bits(num_bits))
217                         } else {  // underflow to 0
218                             Scalar::from_uint(0u128, Size::from_bits(num_bits))
219                         }
220                     }
221                 } else {
222                     val
223                 };
224                 self.write_scalar(val, dest)?;
225             }
226             sym::unchecked_shl | sym::unchecked_shr => {
227                 let l = self.read_immediate(args[0])?;
228                 let r = self.read_immediate(args[1])?;
229                 let bin_op = match intrinsic_name {
230                     sym::unchecked_shl => BinOp::Shl,
231                     sym::unchecked_shr => BinOp::Shr,
232                     _ => bug!("Already checked for int ops")
233                 };
234                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
235                 if overflowed {
236                     let layout = self.layout_of(substs.type_at(0))?;
237                     let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
238                     throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
239                 }
240                 self.write_scalar(val, dest)?;
241             }
242             sym::rotate_left | sym::rotate_right => {
243                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
244                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
245                 let layout = self.layout_of(substs.type_at(0))?;
246                 let val = self.read_scalar(args[0])?.not_undef()?;
247                 let val_bits = self.force_bits(val, layout.size)?;
248                 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
249                 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
250                 let width_bits = layout.size.bits() as u128;
251                 let shift_bits = raw_shift_bits % width_bits;
252                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
253                 let result_bits = if intrinsic_name == sym::rotate_left {
254                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
255                 } else {
256                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
257                 };
258                 let truncated_bits = self.truncate(result_bits, layout);
259                 let result = Scalar::from_uint(truncated_bits, layout.size);
260                 self.write_scalar(result, dest)?;
261             }
262
263             sym::ptr_offset_from => {
264                 let isize_layout = self.layout_of(self.tcx.types.isize)?;
265                 let a = self.read_immediate(args[0])?.to_scalar()?;
266                 let b = self.read_immediate(args[1])?.to_scalar()?;
267
268                 // Special case: if both scalars are *equal integers*
269                 // and not NULL, we pretend there is an allocation of size 0 right there,
270                 // and their offset is 0. (There's never a valid object at NULL, making it an
271                 // exception from the exception.)
272                 // This is the dual to the special exception for offset-by-0
273                 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
274                 //
275                 // Control flow is weird because we cannot early-return (to reach the
276                 // `go_to_block` at the end).
277                 let done = if a.is_bits() && b.is_bits() {
278                     let a = a.to_machine_usize(self)?;
279                     let b = b.to_machine_usize(self)?;
280                     if a == b && a != 0 {
281                         self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
282                         true
283                     } else { false }
284                 } else { false };
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) = self.overflowing_binary_op(
300                         BinOp::Sub, a_offset, b_offset,
301                     )?;
302                     let pointee_layout = self.layout_of(substs.type_at(0))?;
303                     let val = ImmTy::from_scalar(val, isize_layout);
304                     let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
305                     self.exact_div(val, size, dest)?;
306                 }
307             }
308
309             sym::transmute => {
310                 self.copy_op_transmute(args[0], dest)?;
311             }
312             sym::simd_insert => {
313                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
314                 let elem = args[2];
315                 let input = args[0];
316                 let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx.tcx);
317                 assert!(
318                     index < len,
319                     "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
320                     index, e_ty, len
321                 );
322                 assert_eq!(
323                     input.layout, dest.layout,
324                     "Return type `{}` must match vector type `{}`",
325                     dest.layout.ty, input.layout.ty
326                 );
327                 assert_eq!(
328                     elem.layout.ty, e_ty,
329                     "Scalar element type `{}` must match vector element type `{}`",
330                     elem.layout.ty, e_ty
331                 );
332
333                 for i in 0..len {
334                     let place = self.place_field(dest, i)?;
335                     let value = if i == index {
336                         elem
337                     } else {
338                         self.operand_field(input, i)?
339                     };
340                     self.copy_op(value, place)?;
341                 }
342             }
343             sym::simd_extract => {
344                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
345                 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx);
346                 assert!(
347                     index < len,
348                     "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
349                     index, e_ty, len
350                 );
351                 assert_eq!(
352                     e_ty, dest.layout.ty,
353                     "Return type `{}` must match vector element type `{}`",
354                     dest.layout.ty, e_ty
355                 );
356                 self.copy_op(self.operand_field(args[0], index)?, dest)?;
357             }
358             _ => return Ok(false),
359         }
360
361         self.dump_place(*dest);
362         self.go_to_block(ret);
363         Ok(true)
364     }
365
366     /// "Intercept" a function call to a panic-related function
367     /// because we have something special to do for it.
368     /// Returns `true` if an intercept happened.
369     pub fn hook_panic_fn(
370         &mut self,
371         instance: ty::Instance<'tcx>,
372         args: &[OpTy<'tcx, M::PointerTag>],
373         _ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
374     ) -> InterpResult<'tcx, bool> {
375         let def_id = instance.def_id();
376         if Some(def_id) == self.tcx.lang_items().panic_fn() {
377             // &'static str, &core::panic::Location { &'static str, u32, u32 }
378             assert!(args.len() == 2);
379
380             let msg_place = self.deref_operand(args[0])?;
381             let msg = Symbol::intern(self.read_str(msg_place)?);
382
383             let location = self.deref_operand(args[1])?;
384             let (file, line, col) = (
385                 self.mplace_field(location, 0)?,
386                 self.mplace_field(location, 1)?,
387                 self.mplace_field(location, 2)?,
388             );
389
390             let file_place = self.deref_operand(file.into())?;
391             let file = Symbol::intern(self.read_str(file_place)?);
392             let line = self.read_scalar(line.into())?.to_u32()?;
393             let col = self.read_scalar(col.into())?.to_u32()?;
394             throw_panic!(Panic { msg, file, line, col })
395         } else if Some(def_id) == self.tcx.lang_items().begin_panic_fn() {
396             assert!(args.len() == 2);
397             // &'static str, &(&'static str, u32, u32)
398             let msg = args[0];
399             let place = self.deref_operand(args[1])?;
400             let (file, line, col) = (
401                 self.mplace_field(place, 0)?,
402                 self.mplace_field(place, 1)?,
403                 self.mplace_field(place, 2)?,
404             );
405
406             let msg_place = self.deref_operand(msg.into())?;
407             let msg = Symbol::intern(self.read_str(msg_place)?);
408             let file_place = self.deref_operand(file.into())?;
409             let file = Symbol::intern(self.read_str(file_place)?);
410             let line = self.read_scalar(line.into())?.to_u32()?;
411             let col = self.read_scalar(col.into())?.to_u32()?;
412             throw_panic!(Panic { msg, file, line, col })
413         } else {
414             return Ok(false);
415         }
416     }
417
418     pub fn exact_div(
419         &mut self,
420         a: ImmTy<'tcx, M::PointerTag>,
421         b: ImmTy<'tcx, M::PointerTag>,
422         dest: PlaceTy<'tcx, M::PointerTag>,
423     ) -> InterpResult<'tcx> {
424         // Performs an exact division, resulting in undefined behavior where
425         // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
426         // First, check x % y != 0.
427         if self.binary_op(BinOp::Rem, a, b)?.to_bits()? != 0 {
428             // Then, check if `b` is -1, which is the "min_value / -1" case.
429             let minus1 = Scalar::from_int(-1, dest.layout.size);
430             let b_scalar = b.to_scalar().unwrap();
431             if b_scalar == minus1 {
432                 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
433             } else {
434                 throw_ub_format!(
435                     "exact_div: {} cannot be divided by {} without remainder",
436                     a,
437                     b,
438                 )
439             }
440         }
441         self.binop_ignore_overflow(BinOp::Div, a, b, dest)
442     }
443 }