]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/intrinsics.rs
Rollup merge of #66076 - RalfJung:qpath, r=davidtwco,oli-obk
[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::symbol::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::BinOp;
13 use rustc::mir::interpret::{InterpResult, Scalar, GlobalId, ConstValue};
14
15 use super::{
16     Machine, PlaceTy, OpTy, InterpCx, ImmTy,
17 };
18
19 mod caller_location;
20 mod type_name;
21
22 fn numeric_intrinsic<'tcx, Tag>(
23     name: &str,
24     bits: u128,
25     kind: Primitive,
26 ) -> InterpResult<'tcx, Scalar<Tag>> {
27     let size = match kind {
28         Primitive::Int(integer, _) => integer.size(),
29         _ => bug!("invalid `{}` argument: {:?}", name, bits),
30     };
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),
39     };
40     Ok(Scalar::from_uint(bits_out, size))
41 }
42
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>(
46     tcx: TyCtxt<'tcx>,
47     param_env: ty::ParamEnv<'tcx>,
48     def_id: DefId,
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();
53     Ok(match name {
54         "type_name" => {
55             let alloc = type_name::alloc_type_name(tcx, tp_ty);
56             tcx.mk_const(ty::Const {
57                 val: ConstValue::Slice {
58                     data: alloc,
59                     start: 0,
60                     end: alloc.len(),
61                 },
62                 ty: tcx.mk_static_str(),
63             })
64         },
65         "needs_drop" => ty::Const::from_bool(tcx, tp_ty.needs_drop(tcx, param_env)),
66         "size_of" |
67         "min_align_of" |
68         "pref_align_of" => {
69             let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
70             let n = match name {
71                 "pref_align_of" => layout.align.pref.bytes(),
72                 "min_align_of" => layout.align.abi.bytes(),
73                 "size_of" => layout.size.bytes(),
74                 _ => bug!(),
75             };
76             ty::Const::from_usize(tcx, n)
77         },
78         "type_id" => ty::Const::from_bits(
79             tcx,
80             tcx.type_id_hash(tp_ty).into(),
81             param_env.and(tcx.types.u64),
82         ),
83         other => bug!("`{}` is not a zero arg intrinsic", other),
84     })
85 }
86
87 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
88     /// Returns `true` if emulation happened.
89     pub fn emulate_intrinsic(
90         &mut self,
91         span: Span,
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;
97
98         let intrinsic_name = &*self.tcx.item_name(instance.def_id()).as_str();
99         match intrinsic_name {
100             "caller_location" => {
101                 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
102                 let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
103                 let location = self.alloc_caller_location(
104                     Symbol::intern(&caller.file.name.to_string()),
105                     caller.line as u32,
106                     caller.col_display as u32 + 1,
107                 )?;
108                 self.write_scalar(location.ptr, dest)?;
109             }
110
111             "min_align_of" |
112             "pref_align_of" |
113             "needs_drop" |
114             "size_of" |
115             "type_id" |
116             "type_name" => {
117                 let gid = GlobalId {
118                     instance,
119                     promoted: None,
120                 };
121                 let val = self.tcx.const_eval(self.param_env.and(gid))?;
122                 let val = self.eval_const_to_op(val, None)?;
123                 self.copy_op(val, dest)?;
124             }
125
126             | "ctpop"
127             | "cttz"
128             | "cttz_nonzero"
129             | "ctlz"
130             | "ctlz_nonzero"
131             | "bswap"
132             | "bitreverse" => {
133                 let ty = substs.type_at(0);
134                 let layout_of = self.layout_of(ty)?;
135                 let val = self.read_scalar(args[0])?.not_undef()?;
136                 let bits = self.force_bits(val, layout_of.size)?;
137                 let kind = match layout_of.abi {
138                     ty::layout::Abi::Scalar(ref scalar) => scalar.value,
139                     _ => throw_unsup!(TypeNotPrimitive(ty)),
140                 };
141                 let out_val = if intrinsic_name.ends_with("_nonzero") {
142                     if bits == 0 {
143                         throw_ub_format!("`{}` called on 0", intrinsic_name);
144                     }
145                     numeric_intrinsic(intrinsic_name.trim_end_matches("_nonzero"), bits, kind)?
146                 } else {
147                     numeric_intrinsic(intrinsic_name, bits, kind)?
148                 };
149                 self.write_scalar(out_val, dest)?;
150             }
151             | "wrapping_add"
152             | "wrapping_sub"
153             | "wrapping_mul"
154             | "add_with_overflow"
155             | "sub_with_overflow"
156             | "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                     "wrapping_add" => (BinOp::Add, true),
161                     "wrapping_sub" => (BinOp::Sub, true),
162                     "wrapping_mul" => (BinOp::Mul, true),
163                     "add_with_overflow" => (BinOp::Add, false),
164                     "sub_with_overflow" => (BinOp::Sub, false),
165                     "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             "saturating_add" | "saturating_sub" => {
175                 let l = self.read_immediate(args[0])?;
176                 let r = self.read_immediate(args[1])?;
177                 let is_add = intrinsic_name == "saturating_add";
178                 let (val, overflowed, _ty) = self.overflowing_binary_op(if is_add {
179                     BinOp::Add
180                 } else {
181                     BinOp::Sub
182                 }, l, r)?;
183                 let val = if overflowed {
184                     let num_bits = l.layout.size.bits();
185                     if l.layout.abi.is_signed() {
186                         // For signed ints the saturated value depends on the sign of the first
187                         // term since the sign of the second term can be inferred from this and
188                         // the fact that the operation has overflowed (if either is 0 no
189                         // overflow can occur)
190                         let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
191                         let first_term_positive = first_term & (1 << (num_bits-1)) == 0;
192                         if first_term_positive {
193                             // Negative overflow not possible since the positive first term
194                             // can only increase an (in range) negative term for addition
195                             // or corresponding negated positive term for subtraction
196                             Scalar::from_uint((1u128 << (num_bits - 1)) - 1,  // max positive
197                                 Size::from_bits(num_bits))
198                         } else {
199                             // Positive overflow not possible for similar reason
200                             // max negative
201                             Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
202                         }
203                     } else {  // unsigned
204                         if is_add {
205                             // max unsigned
206                             Scalar::from_uint(u128::max_value() >> (128 - num_bits),
207                                 Size::from_bits(num_bits))
208                         } else {  // underflow to 0
209                             Scalar::from_uint(0u128, Size::from_bits(num_bits))
210                         }
211                     }
212                 } else {
213                     val
214                 };
215                 self.write_scalar(val, dest)?;
216             }
217             "unchecked_shl" | "unchecked_shr" => {
218                 let l = self.read_immediate(args[0])?;
219                 let r = self.read_immediate(args[1])?;
220                 let bin_op = match intrinsic_name {
221                     "unchecked_shl" => BinOp::Shl,
222                     "unchecked_shr" => BinOp::Shr,
223                     _ => bug!("Already checked for int ops")
224                 };
225                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
226                 if overflowed {
227                     let layout = self.layout_of(substs.type_at(0))?;
228                     let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
229                     throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
230                 }
231                 self.write_scalar(val, dest)?;
232             }
233             "rotate_left" | "rotate_right" => {
234                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
235                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
236                 let layout = self.layout_of(substs.type_at(0))?;
237                 let val = self.read_scalar(args[0])?.not_undef()?;
238                 let val_bits = self.force_bits(val, layout.size)?;
239                 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
240                 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
241                 let width_bits = layout.size.bits() as u128;
242                 let shift_bits = raw_shift_bits % width_bits;
243                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
244                 let result_bits = if intrinsic_name == "rotate_left" {
245                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
246                 } else {
247                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
248                 };
249                 let truncated_bits = self.truncate(result_bits, layout);
250                 let result = Scalar::from_uint(truncated_bits, layout.size);
251                 self.write_scalar(result, dest)?;
252             }
253
254             "ptr_offset_from" => {
255                 let isize_layout = self.layout_of(self.tcx.types.isize)?;
256                 let a = self.read_immediate(args[0])?.to_scalar()?;
257                 let b = self.read_immediate(args[1])?.to_scalar()?;
258
259                 // Special case: if both scalars are *equal integers*
260                 // and not NULL, we pretend there is an allocation of size 0 right there,
261                 // and their offset is 0. (There's never a valid object at NULL, making it an
262                 // exception from the exception.)
263                 // This is the dual to the special exception for offset-by-0
264                 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
265                 if a.is_bits() && b.is_bits() {
266                     let a = a.to_usize(self)?;
267                     let b = b.to_usize(self)?;
268                     if a == b && a != 0 {
269                         self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
270                         return Ok(true);
271                     }
272                 }
273
274                 // General case: we need two pointers.
275                 let a = self.force_ptr(a)?;
276                 let b = self.force_ptr(b)?;
277                 if a.alloc_id != b.alloc_id {
278                     throw_ub_format!(
279                         "ptr_offset_from cannot compute offset of pointers into different \
280                         allocations.",
281                     );
282                 }
283                 let usize_layout = self.layout_of(self.tcx.types.usize)?;
284                 let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
285                 let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
286                 let (val, _overflowed, _ty) = self.overflowing_binary_op(
287                     BinOp::Sub, a_offset, b_offset,
288                 )?;
289                 let pointee_layout = self.layout_of(substs.type_at(0))?;
290                 let val = ImmTy::from_scalar(val, isize_layout);
291                 let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
292                 self.exact_div(val, size, dest)?;
293             }
294
295             "transmute" => {
296                 self.copy_op_transmute(args[0], dest)?;
297             }
298             "simd_insert" => {
299                 let index = self.read_scalar(args[1])?.to_u32()? as u64;
300                 let scalar = args[2];
301                 let input = args[0];
302                 let (len, e_ty) = self.read_vector_ty(input);
303                 assert!(
304                     index < len,
305                     "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
306                     index, e_ty, len
307                 );
308                 assert_eq!(
309                     input.layout, dest.layout,
310                     "Return type `{}` must match vector type `{}`",
311                     dest.layout.ty, input.layout.ty
312                 );
313                 assert_eq!(
314                     scalar.layout.ty, e_ty,
315                     "Scalar type `{}` must match vector element type `{}`",
316                     scalar.layout.ty, e_ty
317                 );
318
319                 for i in 0..len {
320                     let place = self.place_field(dest, i)?;
321                     let value = if i == index {
322                         scalar
323                     } else {
324                         self.operand_field(input, i)?
325                     };
326                     self.copy_op(value, place)?;
327                 }
328             }
329             "simd_extract" => {
330                 let index = self.read_scalar(args[1])?.to_u32()? as _;
331                 let (len, e_ty) = self.read_vector_ty(args[0]);
332                 assert!(
333                     index < len,
334                     "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
335                     index, e_ty, len
336                 );
337                 assert_eq!(
338                     e_ty, dest.layout.ty,
339                     "Return type `{}` must match vector element type `{}`",
340                     dest.layout.ty, e_ty
341                 );
342                 self.copy_op(self.operand_field(args[0], index)?, dest)?;
343             }
344             _ => return Ok(false),
345         }
346
347         Ok(true)
348     }
349
350     /// "Intercept" a function call because we have something special to do for it.
351     /// Returns `true` if an intercept happened.
352     pub fn hook_fn(
353         &mut self,
354         instance: ty::Instance<'tcx>,
355         args: &[OpTy<'tcx, M::PointerTag>],
356         _dest: Option<PlaceTy<'tcx, M::PointerTag>>,
357     ) -> InterpResult<'tcx, bool> {
358         let def_id = instance.def_id();
359         if Some(def_id) == self.tcx.lang_items().panic_fn() {
360             // &'static str, &core::panic::Location { &'static str, u32, u32 }
361             assert!(args.len() == 2);
362
363             let msg_place = self.deref_operand(args[0])?;
364             let msg = Symbol::intern(self.read_str(msg_place)?);
365
366             let location = self.deref_operand(args[1])?;
367             let (file, line, col) = (
368                 self.mplace_field(location, 0)?,
369                 self.mplace_field(location, 1)?,
370                 self.mplace_field(location, 2)?,
371             );
372
373             let file_place = self.deref_operand(file.into())?;
374             let file = Symbol::intern(self.read_str(file_place)?);
375             let line = self.read_scalar(line.into())?.to_u32()?;
376             let col = self.read_scalar(col.into())?.to_u32()?;
377             throw_panic!(Panic { msg, file, line, col })
378         } else if Some(def_id) == self.tcx.lang_items().begin_panic_fn() {
379             assert!(args.len() == 2);
380             // &'static str, &(&'static str, u32, u32)
381             let msg = args[0];
382             let place = self.deref_operand(args[1])?;
383             let (file, line, col) = (
384                 self.mplace_field(place, 0)?,
385                 self.mplace_field(place, 1)?,
386                 self.mplace_field(place, 2)?,
387             );
388
389             let msg_place = self.deref_operand(msg.into())?;
390             let msg = Symbol::intern(self.read_str(msg_place)?);
391             let file_place = self.deref_operand(file.into())?;
392             let file = Symbol::intern(self.read_str(file_place)?);
393             let line = self.read_scalar(line.into())?.to_u32()?;
394             let col = self.read_scalar(col.into())?.to_u32()?;
395             throw_panic!(Panic { msg, file, line, col })
396         } else {
397             return Ok(false);
398         }
399     }
400
401     pub fn exact_div(
402         &mut self,
403         a: ImmTy<'tcx, M::PointerTag>,
404         b: ImmTy<'tcx, M::PointerTag>,
405         dest: PlaceTy<'tcx, M::PointerTag>,
406     ) -> InterpResult<'tcx> {
407         // Performs an exact division, resulting in undefined behavior where
408         // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
409         // First, check x % y != 0.
410         if self.binary_op(BinOp::Rem, a, b)?.to_bits()? != 0 {
411             // Then, check if `b` is -1, which is the "min_value / -1" case.
412             let minus1 = Scalar::from_int(-1, dest.layout.size);
413             let b = b.to_scalar().unwrap();
414             if b == minus1 {
415                 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
416             } else {
417                 throw_ub_format!(
418                     "exact_div: {} cannot be divided by {} without remainder",
419                     a.to_scalar().unwrap(),
420                     b,
421                 )
422             }
423         }
424         self.binop_ignore_overflow(BinOp::Div, a, b, dest)
425     }
426 }