]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/intrinsics.rs
Get rid of special const intrinsic query in favour of `const_eval`
[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 rustc::ty;
7 use rustc::ty::layout::{LayoutOf, Primitive, Size};
8 use rustc::ty::subst::SubstsRef;
9 use rustc::hir::def_id::DefId;
10 use rustc::ty::TyCtxt;
11 use rustc::mir::BinOp;
12 use rustc::mir::interpret::{InterpResult, Scalar, GlobalId, ConstValue};
13
14 use super::{
15     Machine, PlaceTy, OpTy, InterpCx,
16 };
17
18 mod type_name;
19
20 fn numeric_intrinsic<'tcx, Tag>(
21     name: &str,
22     bits: u128,
23     kind: Primitive,
24 ) -> InterpResult<'tcx, Scalar<Tag>> {
25     let size = match kind {
26         Primitive::Int(integer, _) => integer.size(),
27         _ => bug!("invalid `{}` argument: {:?}", name, bits),
28     };
29     let extra = 128 - size.bits() as u128;
30     let bits_out = match name {
31         "ctpop" => bits.count_ones() as u128,
32         "ctlz" => bits.leading_zeros() as u128 - extra,
33         "cttz" => (bits << extra).trailing_zeros() as u128 - extra,
34         "bswap" => (bits << extra).swap_bytes(),
35         "bitreverse" => (bits << extra).reverse_bits(),
36         _ => bug!("not a numeric intrinsic: {}", name),
37     };
38     Ok(Scalar::from_uint(bits_out, size))
39 }
40
41 /// The logic for all nullary intrinsics is implemented here. These intrinsics don't get evaluated
42 /// inside an `InterpCx` and instead have their value computed directly from rustc internal info.
43 crate fn eval_nullary_intrinsic<'tcx>(
44     tcx: TyCtxt<'tcx>,
45     param_env: ty::ParamEnv<'tcx>,
46     def_id: DefId,
47     substs: SubstsRef<'tcx>,
48 ) -> InterpResult<'tcx, &'tcx ty::Const<'tcx>> {
49     let tp_ty = substs.type_at(0);
50     let name = &*tcx.item_name(def_id).as_str();
51     Ok(match name {
52         "type_name" => {
53             let alloc = type_name::alloc_type_name(tcx, tp_ty);
54             tcx.mk_const(ty::Const {
55                 val: ConstValue::Slice {
56                     data: alloc,
57                     start: 0,
58                     end: alloc.len(),
59                 },
60                 ty: tcx.mk_static_str(),
61             })
62         },
63         "needs_drop" => ty::Const::from_bool(tcx, tp_ty.needs_drop(tcx, param_env)),
64         "size_of" |
65         "min_align_of" |
66         "pref_align_of" => {
67             let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
68             let n = match name {
69                 "pref_align_of" => layout.align.pref.bytes(),
70                 "min_align_of" => layout.align.abi.bytes(),
71                 "size_of" => layout.size.bytes(),
72                 _ => bug!(),
73             };
74             ty::Const::from_usize(tcx, n)
75         },
76         "type_id" => ty::Const::from_bits(
77             tcx,
78             tcx.type_id_hash(tp_ty).into(),
79             param_env.and(tcx.types.u64),
80         ),
81         other => bug!("`{}` is not a zero arg intrinsic", other),
82     })
83 }
84
85 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
86     /// Returns `true` if emulation happened.
87     pub fn emulate_intrinsic(
88         &mut self,
89         instance: ty::Instance<'tcx>,
90         args: &[OpTy<'tcx, M::PointerTag>],
91         dest: PlaceTy<'tcx, M::PointerTag>,
92     ) -> InterpResult<'tcx, bool> {
93         let substs = instance.substs;
94
95         let intrinsic_name = &self.tcx.item_name(instance.def_id()).as_str()[..];
96         match intrinsic_name {
97             "min_align_of" |
98             "pref_align_of" |
99             "needs_drop" |
100             "size_of" |
101             "type_id" |
102             "type_name" => {
103                 let gid = GlobalId {
104                     instance,
105                     promoted: None,
106                 };
107                 let val = self.tcx.const_eval(self.param_env.and(gid))?;
108                 let val = self.eval_const_to_op(val, None)?;
109                 self.copy_op(val, dest)?;
110             }
111
112             | "ctpop"
113             | "cttz"
114             | "cttz_nonzero"
115             | "ctlz"
116             | "ctlz_nonzero"
117             | "bswap"
118             | "bitreverse" => {
119                 let ty = substs.type_at(0);
120                 let layout_of = self.layout_of(ty)?;
121                 let val = self.read_scalar(args[0])?.not_undef()?;
122                 let bits = self.force_bits(val, layout_of.size)?;
123                 let kind = match layout_of.abi {
124                     ty::layout::Abi::Scalar(ref scalar) => scalar.value,
125                     _ => throw_unsup!(TypeNotPrimitive(ty)),
126                 };
127                 let out_val = if intrinsic_name.ends_with("_nonzero") {
128                     if bits == 0 {
129                         throw_ub_format!("`{}` called on 0", intrinsic_name);
130                     }
131                     numeric_intrinsic(intrinsic_name.trim_end_matches("_nonzero"), bits, kind)?
132                 } else {
133                     numeric_intrinsic(intrinsic_name, bits, kind)?
134                 };
135                 self.write_scalar(out_val, dest)?;
136             }
137             | "wrapping_add"
138             | "wrapping_sub"
139             | "wrapping_mul"
140             | "add_with_overflow"
141             | "sub_with_overflow"
142             | "mul_with_overflow" => {
143                 let lhs = self.read_immediate(args[0])?;
144                 let rhs = self.read_immediate(args[1])?;
145                 let (bin_op, ignore_overflow) = match intrinsic_name {
146                     "wrapping_add" => (BinOp::Add, true),
147                     "wrapping_sub" => (BinOp::Sub, true),
148                     "wrapping_mul" => (BinOp::Mul, true),
149                     "add_with_overflow" => (BinOp::Add, false),
150                     "sub_with_overflow" => (BinOp::Sub, false),
151                     "mul_with_overflow" => (BinOp::Mul, false),
152                     _ => bug!("Already checked for int ops")
153                 };
154                 if ignore_overflow {
155                     self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
156                 } else {
157                     self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
158                 }
159             }
160             "saturating_add" | "saturating_sub" => {
161                 let l = self.read_immediate(args[0])?;
162                 let r = self.read_immediate(args[1])?;
163                 let is_add = intrinsic_name == "saturating_add";
164                 let (val, overflowed, _ty) = self.overflowing_binary_op(if is_add {
165                     BinOp::Add
166                 } else {
167                     BinOp::Sub
168                 }, l, r)?;
169                 let val = if overflowed {
170                     let num_bits = l.layout.size.bits();
171                     if l.layout.abi.is_signed() {
172                         // For signed ints the saturated value depends on the sign of the first
173                         // term since the sign of the second term can be inferred from this and
174                         // the fact that the operation has overflowed (if either is 0 no
175                         // overflow can occur)
176                         let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
177                         let first_term_positive = first_term & (1 << (num_bits-1)) == 0;
178                         if first_term_positive {
179                             // Negative overflow not possible since the positive first term
180                             // can only increase an (in range) negative term for addition
181                             // or corresponding negated positive term for subtraction
182                             Scalar::from_uint((1u128 << (num_bits - 1)) - 1,  // max positive
183                                 Size::from_bits(num_bits))
184                         } else {
185                             // Positive overflow not possible for similar reason
186                             // max negative
187                             Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
188                         }
189                     } else {  // unsigned
190                         if is_add {
191                             // max unsigned
192                             Scalar::from_uint(u128::max_value() >> (128 - num_bits),
193                                 Size::from_bits(num_bits))
194                         } else {  // underflow to 0
195                             Scalar::from_uint(0u128, Size::from_bits(num_bits))
196                         }
197                     }
198                 } else {
199                     val
200                 };
201                 self.write_scalar(val, dest)?;
202             }
203             "unchecked_shl" | "unchecked_shr" => {
204                 let l = self.read_immediate(args[0])?;
205                 let r = self.read_immediate(args[1])?;
206                 let bin_op = match intrinsic_name {
207                     "unchecked_shl" => BinOp::Shl,
208                     "unchecked_shr" => BinOp::Shr,
209                     _ => bug!("Already checked for int ops")
210                 };
211                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
212                 if overflowed {
213                     let layout = self.layout_of(substs.type_at(0))?;
214                     let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
215                     throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
216                 }
217                 self.write_scalar(val, dest)?;
218             }
219             "rotate_left" | "rotate_right" => {
220                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
221                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
222                 let layout = self.layout_of(substs.type_at(0))?;
223                 let val = self.read_scalar(args[0])?.not_undef()?;
224                 let val_bits = self.force_bits(val, layout.size)?;
225                 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
226                 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
227                 let width_bits = layout.size.bits() as u128;
228                 let shift_bits = raw_shift_bits % width_bits;
229                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
230                 let result_bits = if intrinsic_name == "rotate_left" {
231                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
232                 } else {
233                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
234                 };
235                 let truncated_bits = self.truncate(result_bits, layout);
236                 let result = Scalar::from_uint(truncated_bits, layout.size);
237                 self.write_scalar(result, dest)?;
238             }
239             "transmute" => {
240                 self.copy_op_transmute(args[0], dest)?;
241             }
242
243             _ => return Ok(false),
244         }
245
246         Ok(true)
247     }
248
249     /// "Intercept" a function call because we have something special to do for it.
250     /// Returns `true` if an intercept happened.
251     pub fn hook_fn(
252         &mut self,
253         instance: ty::Instance<'tcx>,
254         args: &[OpTy<'tcx, M::PointerTag>],
255         _dest: Option<PlaceTy<'tcx, M::PointerTag>>,
256     ) -> InterpResult<'tcx, bool> {
257         let def_id = instance.def_id();
258         if Some(def_id) == self.tcx.lang_items().panic_fn() {
259             assert!(args.len() == 1);
260             // &(&'static str, &'static str, u32, u32)
261             let place = self.deref_operand(args[0])?;
262             let (msg, file, line, col) = (
263                 self.mplace_field(place, 0)?,
264                 self.mplace_field(place, 1)?,
265                 self.mplace_field(place, 2)?,
266                 self.mplace_field(place, 3)?,
267             );
268
269             let msg_place = self.deref_operand(msg.into())?;
270             let msg = Symbol::intern(self.read_str(msg_place)?);
271             let file_place = self.deref_operand(file.into())?;
272             let file = Symbol::intern(self.read_str(file_place)?);
273             let line = self.read_scalar(line.into())?.to_u32()?;
274             let col = self.read_scalar(col.into())?.to_u32()?;
275             throw_panic!(Panic { msg, file, line, col })
276         } else if Some(def_id) == self.tcx.lang_items().begin_panic_fn() {
277             assert!(args.len() == 2);
278             // &'static str, &(&'static str, u32, u32)
279             let msg = args[0];
280             let place = self.deref_operand(args[1])?;
281             let (file, line, col) = (
282                 self.mplace_field(place, 0)?,
283                 self.mplace_field(place, 1)?,
284                 self.mplace_field(place, 2)?,
285             );
286
287             let msg_place = self.deref_operand(msg.into())?;
288             let msg = Symbol::intern(self.read_str(msg_place)?);
289             let file_place = self.deref_operand(file.into())?;
290             let file = Symbol::intern(self.read_str(file_place)?);
291             let line = self.read_scalar(line.into())?.to_u32()?;
292             let col = self.read_scalar(col.into())?.to_u32()?;
293             throw_panic!(Panic { msg, file, line, col })
294         } else {
295             return Ok(false);
296         }
297     }
298 }