]>
Commit | Line | Data |
---|---|---|
add651ee | 1 | //! Intrinsics and other functions that the interpreter executes without |
9fa01778 | 2 | //! looking at their MIR. Intrinsics/functions supported here are shared by CTFE |
b7449926 XL |
3 | //! and miri. |
4 | ||
ba9703b0 XL |
5 | use rustc_hir::def_id::DefId; |
6 | use rustc_middle::mir::{ | |
dfeec247 | 7 | self, |
781aab86 FG |
8 | interpret::{Allocation, ConstAllocation, GlobalId, InterpResult, PointerArithmetic, Scalar}, |
9 | BinOp, ConstValue, NonDivergingIntrinsic, | |
dfeec247 | 10 | }; |
ba9703b0 | 11 | use rustc_middle::ty; |
9ffffee4 | 12 | use rustc_middle::ty::layout::{LayoutOf as _, ValidityRequirement}; |
add651ee | 13 | use rustc_middle::ty::GenericArgsRef; |
f9f354fc | 14 | use rustc_middle::ty::{Ty, TyCtxt}; |
dfeec247 | 15 | use rustc_span::symbol::{sym, Symbol}; |
064997fb | 16 | use rustc_target::abi::{Abi, Align, Primitive, Size}; |
b7449926 | 17 | |
3dfed10e XL |
18 | use super::{ |
19 | util::ensure_monomorphic_enough, CheckInAllocMsg, ImmTy, InterpCx, Machine, OpTy, PlaceTy, | |
136023e0 | 20 | Pointer, |
3dfed10e | 21 | }; |
b7449926 | 22 | |
fe692bf9 FG |
23 | use crate::fluent_generated as fluent; |
24 | ||
e74abb32 | 25 | mod caller_location; |
dc9dc135 | 26 | |
064997fb | 27 | fn numeric_intrinsic<Prov>(name: Symbol, bits: u128, kind: Primitive) -> Scalar<Prov> { |
b7449926 XL |
28 | let size = match kind { |
29 | Primitive::Int(integer, _) => integer.size(), | |
30 | _ => bug!("invalid `{}` argument: {:?}", name, bits), | |
31 | }; | |
ba9703b0 | 32 | let extra = 128 - u128::from(size.bits()); |
b7449926 | 33 | let bits_out = match name { |
ba9703b0 XL |
34 | sym::ctpop => u128::from(bits.count_ones()), |
35 | sym::ctlz => u128::from(bits.leading_zeros()) - extra, | |
36 | sym::cttz => u128::from((bits << extra).trailing_zeros()) - extra, | |
60c5eb7d XL |
37 | sym::bswap => (bits << extra).swap_bytes(), |
38 | sym::bitreverse => (bits << extra).reverse_bits(), | |
b7449926 XL |
39 | _ => bug!("not a numeric intrinsic: {}", name), |
40 | }; | |
6a06907d | 41 | Scalar::from_uint(bits_out, size) |
b7449926 XL |
42 | } |
43 | ||
487cf647 FG |
44 | /// Directly returns an `Allocation` containing an absolute path representation of the given type. |
45 | pub(crate) fn alloc_type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ConstAllocation<'tcx> { | |
46 | let path = crate::util::type_name(tcx, ty); | |
47 | let alloc = Allocation::from_bytes_byte_aligned_immutable(path.into_bytes()); | |
9ffffee4 | 48 | tcx.mk_const_alloc(alloc) |
487cf647 FG |
49 | } |
50 | ||
e1599b0c XL |
51 | /// The logic for all nullary intrinsics is implemented here. These intrinsics don't get evaluated |
52 | /// inside an `InterpCx` and instead have their value computed directly from rustc internal info. | |
923072b8 | 53 | pub(crate) fn eval_nullary_intrinsic<'tcx>( |
e1599b0c XL |
54 | tcx: TyCtxt<'tcx>, |
55 | param_env: ty::ParamEnv<'tcx>, | |
56 | def_id: DefId, | |
add651ee | 57 | args: GenericArgsRef<'tcx>, |
74b04a01 | 58 | ) -> InterpResult<'tcx, ConstValue<'tcx>> { |
add651ee | 59 | let tp_ty = args.type_at(0); |
60c5eb7d | 60 | let name = tcx.item_name(def_id); |
e1599b0c | 61 | Ok(match name { |
60c5eb7d | 62 | sym::type_name => { |
3dfed10e | 63 | ensure_monomorphic_enough(tcx, tp_ty)?; |
487cf647 | 64 | let alloc = alloc_type_name(tcx, tp_ty); |
781aab86 | 65 | ConstValue::Slice { data: alloc, meta: alloc.inner().size().bytes() } |
dfeec247 | 66 | } |
17df50a5 XL |
67 | sym::needs_drop => { |
68 | ensure_monomorphic_enough(tcx, tp_ty)?; | |
69 | ConstValue::from_bool(tp_ty.needs_drop(tcx, param_env)) | |
70 | } | |
c295e0f8 | 71 | sym::pref_align_of => { |
17df50a5 | 72 | // Correctly handles non-monomorphic calls, so there is no need for ensure_monomorphic_enough. |
fe692bf9 | 73 | let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(*e)))?; |
9ffffee4 | 74 | ConstValue::from_target_usize(layout.align.pref.bytes(), &tcx) |
dfeec247 | 75 | } |
3dfed10e XL |
76 | sym::type_id => { |
77 | ensure_monomorphic_enough(tcx, tp_ty)?; | |
fe692bf9 | 78 | ConstValue::from_u128(tcx.type_id_hash(tp_ty).as_u128()) |
3dfed10e | 79 | } |
fc512014 | 80 | sym::variant_count => match tp_ty.kind() { |
17df50a5 | 81 | // Correctly handles non-monomorphic calls, so there is no need for ensure_monomorphic_enough. |
9ffffee4 | 82 | ty::Adt(adt, _) => ConstValue::from_target_usize(adt.variants().len() as u64, &tcx), |
9c376795 FG |
83 | ty::Alias(..) | ty::Param(_) | ty::Placeholder(_) | ty::Infer(_) => { |
84 | throw_inval!(TooGeneric) | |
5e7ed085 | 85 | } |
f2b60f7d | 86 | ty::Bound(_, _) => bug!("bound ty during ctfe"), |
fc512014 XL |
87 | ty::Bool |
88 | | ty::Char | |
89 | | ty::Int(_) | |
90 | | ty::Uint(_) | |
91 | | ty::Float(_) | |
92 | | ty::Foreign(_) | |
93 | | ty::Str | |
94 | | ty::Array(_, _) | |
95 | | ty::Slice(_) | |
96 | | ty::RawPtr(_) | |
97 | | ty::Ref(_, _, _) | |
98 | | ty::FnDef(_, _) | |
99 | | ty::FnPtr(_) | |
f2b60f7d | 100 | | ty::Dynamic(_, _, _) |
fc512014 XL |
101 | | ty::Closure(_, _) |
102 | | ty::Generator(_, _, _) | |
781aab86 | 103 | | ty::GeneratorWitness(..) |
fc512014 XL |
104 | | ty::Never |
105 | | ty::Tuple(_) | |
9ffffee4 | 106 | | ty::Error(_) => ConstValue::from_target_usize(0u64, &tcx), |
fc512014 | 107 | }, |
e1599b0c XL |
108 | other => bug!("`{}` is not a zero arg intrinsic", other), |
109 | }) | |
110 | } | |
111 | ||
ba9703b0 | 112 | impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { |
9fa01778 | 113 | /// Returns `true` if emulation happened. |
1b1a35ee XL |
114 | /// Here we implement the intrinsics that are common to all Miri instances; individual machines can add their own |
115 | /// intrinsic handling. | |
b7449926 XL |
116 | pub fn emulate_intrinsic( |
117 | &mut self, | |
118 | instance: ty::Instance<'tcx>, | |
064997fb FG |
119 | args: &[OpTy<'tcx, M::Provenance>], |
120 | dest: &PlaceTy<'tcx, M::Provenance>, | |
923072b8 | 121 | ret: Option<mir::BasicBlock>, |
dc9dc135 | 122 | ) -> InterpResult<'tcx, bool> { |
add651ee | 123 | let instance_args = instance.args; |
60c5eb7d | 124 | let intrinsic_name = self.tcx.item_name(instance.def_id()); |
781aab86 FG |
125 | let Some(ret) = ret else { |
126 | // We don't support any intrinsic without return place. | |
127 | return Ok(false); | |
60c5eb7d | 128 | }; |
b7449926 | 129 | |
b7449926 | 130 | match intrinsic_name { |
60c5eb7d | 131 | sym::caller_location => { |
ba9703b0 | 132 | let span = self.find_closest_untracked_caller_location(); |
60c5eb7d | 133 | let location = self.alloc_caller_location_for_span(span); |
136023e0 | 134 | self.write_immediate(location.to_ref(self), dest)?; |
e74abb32 XL |
135 | } |
136 | ||
3dfed10e | 137 | sym::min_align_of_val | sym::size_of_val => { |
add651ee | 138 | // Avoid `deref_pointer` -- this is not a deref, the ptr does not have to be |
a2a8927a | 139 | // dereferenceable! |
6a06907d | 140 | let place = self.ref_to_mplace(&self.read_immediate(&args[0])?)?; |
3dfed10e | 141 | let (size, align) = self |
6a06907d | 142 | .size_and_align_of_mplace(&place)? |
3dfed10e XL |
143 | .ok_or_else(|| err_unsup_format!("`extern type` does not have known layout"))?; |
144 | ||
145 | let result = match intrinsic_name { | |
146 | sym::min_align_of_val => align.bytes(), | |
147 | sym::size_of_val => size.bytes(), | |
148 | _ => bug!(), | |
149 | }; | |
150 | ||
9ffffee4 | 151 | self.write_scalar(Scalar::from_target_usize(result, self), dest)?; |
3dfed10e XL |
152 | } |
153 | ||
c295e0f8 | 154 | sym::pref_align_of |
dfeec247 | 155 | | sym::needs_drop |
dfeec247 | 156 | | sym::type_id |
f035d41b XL |
157 | | sym::type_name |
158 | | sym::variant_count => { | |
dfeec247 | 159 | let gid = GlobalId { instance, promoted: None }; |
74b04a01 | 160 | let ty = match intrinsic_name { |
c295e0f8 | 161 | sym::pref_align_of | sym::variant_count => self.tcx.types.usize, |
74b04a01 | 162 | sym::needs_drop => self.tcx.types.bool, |
fe692bf9 FG |
163 | sym::type_id => self.tcx.types.u128, |
164 | sym::type_name => Ty::new_static_str(self.tcx.tcx), | |
923072b8 | 165 | _ => bug!(), |
74b04a01 | 166 | }; |
487cf647 FG |
167 | let val = self.ctfe_query(None, |tcx| { |
168 | tcx.const_eval_global_id(self.param_env, gid, Some(tcx.span)) | |
169 | })?; | |
cdc7bbd5 | 170 | let val = self.const_val_to_op(val, ty, Some(dest.layout))?; |
064997fb | 171 | self.copy_op(&val, dest, /*allow_transmute*/ false)?; |
dc9dc135 XL |
172 | } |
173 | ||
dfeec247 | 174 | sym::ctpop |
60c5eb7d XL |
175 | | sym::cttz |
176 | | sym::cttz_nonzero | |
177 | | sym::ctlz | |
178 | | sym::ctlz_nonzero | |
179 | | sym::bswap | |
180 | | sym::bitreverse => { | |
add651ee | 181 | let ty = instance_args.type_at(0); |
b7449926 | 182 | let layout_of = self.layout_of(ty)?; |
f2b60f7d | 183 | let val = self.read_scalar(&args[0])?; |
136023e0 | 184 | let bits = val.to_bits(layout_of.size)?; |
b7449926 | 185 | let kind = match layout_of.abi { |
04454e1e | 186 | Abi::Scalar(scalar) => scalar.primitive(), |
f035d41b XL |
187 | _ => span_bug!( |
188 | self.cur_span(), | |
189 | "{} called on invalid type {:?}", | |
190 | intrinsic_name, | |
191 | ty | |
192 | ), | |
b7449926 | 193 | }; |
fe692bf9 | 194 | let (nonzero, actual_intrinsic_name) = match intrinsic_name { |
60c5eb7d XL |
195 | sym::cttz_nonzero => (true, sym::cttz), |
196 | sym::ctlz_nonzero => (true, sym::ctlz), | |
197 | other => (false, other), | |
b7449926 | 198 | }; |
60c5eb7d | 199 | if nonzero && bits == 0 { |
fe692bf9 FG |
200 | throw_ub_custom!( |
201 | fluent::const_eval_call_nonzero_intrinsic, | |
202 | name = intrinsic_name, | |
203 | ); | |
60c5eb7d | 204 | } |
fe692bf9 | 205 | let out_val = numeric_intrinsic(actual_intrinsic_name, bits, kind); |
b7449926 XL |
206 | self.write_scalar(out_val, dest)?; |
207 | } | |
60c5eb7d | 208 | sym::saturating_add | sym::saturating_sub => { |
6a06907d XL |
209 | let l = self.read_immediate(&args[0])?; |
210 | let r = self.read_immediate(&args[1])?; | |
5e7ed085 FG |
211 | let val = self.saturating_arith( |
212 | if intrinsic_name == sym::saturating_add { BinOp::Add } else { BinOp::Sub }, | |
6a06907d XL |
213 | &l, |
214 | &r, | |
215 | )?; | |
9fa01778 XL |
216 | self.write_scalar(val, dest)?; |
217 | } | |
ba9703b0 | 218 | sym::discriminant_value => { |
add651ee FG |
219 | let place = self.deref_pointer(&args[0])?; |
220 | let variant = self.read_discriminant(&place)?; | |
221 | let discr = self.discriminant_for_variant(place.layout, variant)?; | |
781aab86 | 222 | self.write_immediate(*discr, dest)?; |
ba9703b0 | 223 | } |
487cf647 FG |
224 | sym::exact_div => { |
225 | let l = self.read_immediate(&args[0])?; | |
226 | let r = self.read_immediate(&args[1])?; | |
227 | self.exact_div(&l, &r, dest)?; | |
228 | } | |
60c5eb7d | 229 | sym::rotate_left | sym::rotate_right => { |
a1dfa0c6 XL |
230 | // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW)) |
231 | // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW)) | |
add651ee | 232 | let layout = self.layout_of(instance_args.type_at(0))?; |
f2b60f7d | 233 | let val = self.read_scalar(&args[0])?; |
136023e0 | 234 | let val_bits = val.to_bits(layout.size)?; |
f2b60f7d | 235 | let raw_shift = self.read_scalar(&args[1])?; |
136023e0 | 236 | let raw_shift_bits = raw_shift.to_bits(layout.size)?; |
ba9703b0 | 237 | let width_bits = u128::from(layout.size.bits()); |
a1dfa0c6 | 238 | let shift_bits = raw_shift_bits % width_bits; |
dc9dc135 | 239 | let inv_shift_bits = (width_bits - shift_bits) % width_bits; |
60c5eb7d | 240 | let result_bits = if intrinsic_name == sym::rotate_left { |
a1dfa0c6 XL |
241 | (val_bits << shift_bits) | (val_bits >> inv_shift_bits) |
242 | } else { | |
243 | (val_bits >> shift_bits) | (val_bits << inv_shift_bits) | |
244 | }; | |
245 | let truncated_bits = self.truncate(result_bits, layout); | |
246 | let result = Scalar::from_uint(truncated_bits, layout.size); | |
247 | self.write_scalar(result, dest)?; | |
248 | } | |
6a06907d | 249 | sym::copy => { |
17df50a5 | 250 | self.copy_intrinsic(&args[0], &args[1], &args[2], /*nonoverlapping*/ false)?; |
5869c6ff | 251 | } |
a2a8927a XL |
252 | sym::write_bytes => { |
253 | self.write_bytes_intrinsic(&args[0], &args[1], &args[2])?; | |
254 | } | |
add651ee FG |
255 | sym::compare_bytes => { |
256 | let result = self.compare_bytes_intrinsic(&args[0], &args[1], &args[2])?; | |
257 | self.write_scalar(result, dest)?; | |
258 | } | |
f9f354fc | 259 | sym::arith_offset => { |
136023e0 | 260 | let ptr = self.read_pointer(&args[0])?; |
9ffffee4 | 261 | let offset_count = self.read_target_isize(&args[1])?; |
add651ee | 262 | let pointee_ty = instance_args.type_at(0); |
f9f354fc XL |
263 | |
264 | let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap(); | |
265 | let offset_bytes = offset_count.wrapping_mul(pointee_size); | |
136023e0 XL |
266 | let offset_ptr = ptr.wrapping_signed_offset(offset_bytes, self); |
267 | self.write_pointer(offset_ptr, dest)?; | |
f9f354fc | 268 | } |
04454e1e | 269 | sym::ptr_offset_from | sym::ptr_offset_from_unsigned => { |
5e7ed085 FG |
270 | let a = self.read_pointer(&args[0])?; |
271 | let b = self.read_pointer(&args[1])?; | |
60c5eb7d | 272 | |
923072b8 FG |
273 | let usize_layout = self.layout_of(self.tcx.types.usize)?; |
274 | let isize_layout = self.layout_of(self.tcx.types.isize)?; | |
5e7ed085 | 275 | |
923072b8 FG |
276 | // Get offsets for both that are at least relative to the same base. |
277 | let (a_offset, b_offset) = | |
278 | match (self.ptr_try_get_alloc_id(a), self.ptr_try_get_alloc_id(b)) { | |
279 | (Err(a), Err(b)) => { | |
f2b60f7d | 280 | // Neither pointer points to an allocation. |
923072b8 FG |
281 | // If these are inequal or null, this *will* fail the deref check below. |
282 | (a, b) | |
283 | } | |
284 | (Err(_), _) | (_, Err(_)) => { | |
285 | // We managed to find a valid allocation for one pointer, but not the other. | |
286 | // That means they are definitely not pointing to the same allocation. | |
fe692bf9 FG |
287 | throw_ub_custom!( |
288 | fluent::const_eval_different_allocations, | |
289 | name = intrinsic_name, | |
04454e1e FG |
290 | ); |
291 | } | |
923072b8 FG |
292 | (Ok((a_alloc_id, a_offset, _)), Ok((b_alloc_id, b_offset, _))) => { |
293 | // Found allocation for both. They must be into the same allocation. | |
294 | if a_alloc_id != b_alloc_id { | |
fe692bf9 FG |
295 | throw_ub_custom!( |
296 | fluent::const_eval_different_allocations, | |
297 | name = intrinsic_name, | |
923072b8 FG |
298 | ); |
299 | } | |
300 | // Use these offsets for distance calculation. | |
301 | (a_offset.bytes(), b_offset.bytes()) | |
04454e1e | 302 | } |
923072b8 | 303 | }; |
04454e1e | 304 | |
923072b8 | 305 | // Compute distance. |
064997fb FG |
306 | let dist = { |
307 | // Addresses are unsigned, so this is a `usize` computation. We have to do the | |
308 | // overflow check separately anyway. | |
781aab86 | 309 | let (val, overflowed) = { |
064997fb FG |
310 | let a_offset = ImmTy::from_uint(a_offset, usize_layout); |
311 | let b_offset = ImmTy::from_uint(b_offset, usize_layout); | |
312 | self.overflowing_binary_op(BinOp::Sub, &a_offset, &b_offset)? | |
313 | }; | |
923072b8 | 314 | if overflowed { |
064997fb FG |
315 | // a < b |
316 | if intrinsic_name == sym::ptr_offset_from_unsigned { | |
fe692bf9 FG |
317 | throw_ub_custom!( |
318 | fluent::const_eval_unsigned_offset_from_overflow, | |
319 | a_offset = a_offset, | |
320 | b_offset = b_offset, | |
064997fb FG |
321 | ); |
322 | } | |
323 | // The signed form of the intrinsic allows this. If we interpret the | |
324 | // difference as isize, we'll get the proper signed difference. If that | |
325 | // seems *positive*, they were more than isize::MAX apart. | |
781aab86 | 326 | let dist = val.to_scalar().to_target_isize(self)?; |
064997fb | 327 | if dist >= 0 { |
fe692bf9 FG |
328 | throw_ub_custom!( |
329 | fluent::const_eval_offset_from_underflow, | |
330 | name = intrinsic_name, | |
064997fb FG |
331 | ); |
332 | } | |
333 | dist | |
334 | } else { | |
335 | // b >= a | |
781aab86 | 336 | let dist = val.to_scalar().to_target_isize(self)?; |
064997fb FG |
337 | // If converting to isize produced a *negative* result, we had an overflow |
338 | // because they were more than isize::MAX apart. | |
339 | if dist < 0 { | |
fe692bf9 FG |
340 | throw_ub_custom!( |
341 | fluent::const_eval_offset_from_overflow, | |
342 | name = intrinsic_name, | |
064997fb FG |
343 | ); |
344 | } | |
345 | dist | |
60c5eb7d | 346 | } |
923072b8 FG |
347 | }; |
348 | ||
349 | // Check that the range between them is dereferenceable ("in-bounds or one past the | |
350 | // end of the same allocation"). This is like the check in ptr_offset_inbounds. | |
064997fb | 351 | let min_ptr = if dist >= 0 { b } else { a }; |
923072b8 FG |
352 | self.check_ptr_access_align( |
353 | min_ptr, | |
064997fb | 354 | Size::from_bytes(dist.unsigned_abs()), |
923072b8 FG |
355 | Align::ONE, |
356 | CheckInAllocMsg::OffsetFromTest, | |
357 | )?; | |
358 | ||
923072b8 FG |
359 | // Perform division by size to compute return value. |
360 | let ret_layout = if intrinsic_name == sym::ptr_offset_from_unsigned { | |
9ffffee4 | 361 | assert!(0 <= dist && dist <= self.target_isize_max()); |
923072b8 FG |
362 | usize_layout |
363 | } else { | |
9ffffee4 | 364 | assert!(self.target_isize_min() <= dist && dist <= self.target_isize_max()); |
923072b8 FG |
365 | isize_layout |
366 | }; | |
add651ee | 367 | let pointee_layout = self.layout_of(instance_args.type_at(0))?; |
923072b8 | 368 | // If ret_layout is unsigned, we checked that so is the distance, so we are good. |
064997fb | 369 | let val = ImmTy::from_int(dist, ret_layout); |
923072b8 FG |
370 | let size = ImmTy::from_int(pointee_layout.size.bytes(), ret_layout); |
371 | self.exact_div(&val, &size, dest)?; | |
e74abb32 XL |
372 | } |
373 | ||
9c376795 FG |
374 | sym::assert_inhabited |
375 | | sym::assert_zero_valid | |
376 | | sym::assert_mem_uninitialized_valid => { | |
add651ee | 377 | let ty = instance.args.type_at(0); |
9ffffee4 FG |
378 | let requirement = ValidityRequirement::from_intrinsic(intrinsic_name).unwrap(); |
379 | ||
380 | let should_panic = !self | |
381 | .tcx | |
382 | .check_validity_requirement((requirement, self.param_env.and(ty))) | |
383 | .map_err(|_| err_inval!(TooGeneric))?; | |
384 | ||
385 | if should_panic { | |
386 | let layout = self.layout_of(ty)?; | |
387 | ||
388 | let msg = match requirement { | |
389 | // For *all* intrinsics we first check `is_uninhabited` to give a more specific | |
390 | // error message. | |
391 | _ if layout.abi.is_uninhabited() => format!( | |
add651ee | 392 | "aborted execution: attempted to instantiate uninhabited type `{ty}`" |
fc512014 | 393 | ), |
9ffffee4 FG |
394 | ValidityRequirement::Inhabited => bug!("handled earlier"), |
395 | ValidityRequirement::Zero => format!( | |
add651ee | 396 | "aborted execution: attempted to zero-initialize type `{ty}`, which is invalid" |
9ffffee4 FG |
397 | ), |
398 | ValidityRequirement::UninitMitigated0x01Fill => format!( | |
add651ee | 399 | "aborted execution: attempted to leave type `{ty}` uninitialized, which is invalid" |
9ffffee4 FG |
400 | ), |
401 | ValidityRequirement::Uninit => bug!("assert_uninit_valid doesn't exist"), | |
402 | }; | |
064997fb | 403 | |
781aab86 FG |
404 | M::panic_nounwind(self, &msg)?; |
405 | // Skip the `go_to_block` at the end. | |
406 | return Ok(true); | |
a2a8927a | 407 | } |
fc512014 | 408 | } |
60c5eb7d | 409 | sym::simd_insert => { |
6a06907d XL |
410 | let index = u64::from(self.read_scalar(&args[1])?.to_u32()?); |
411 | let elem = &args[2]; | |
3c0e092e XL |
412 | let (input, input_len) = self.operand_to_simd(&args[0])?; |
413 | let (dest, dest_len) = self.place_to_simd(dest)?; | |
414 | assert_eq!(input_len, dest_len, "Return vector length must match input length"); | |
e74abb32 | 415 | assert!( |
3c0e092e | 416 | index < dest_len, |
add651ee | 417 | "Index `{index}` must be in bounds of vector with length {dest_len}" |
e74abb32 | 418 | ); |
b7449926 | 419 | |
3c0e092e | 420 | for i in 0..dest_len { |
add651ee | 421 | let place = self.project_index(&dest, i)?; |
064997fb FG |
422 | let value = if i == index { |
423 | elem.clone() | |
424 | } else { | |
add651ee | 425 | self.project_index(&input, i)?.into() |
064997fb | 426 | }; |
add651ee | 427 | self.copy_op(&value, &place, /*allow_transmute*/ false)?; |
e74abb32 XL |
428 | } |
429 | } | |
60c5eb7d | 430 | sym::simd_extract => { |
6a06907d | 431 | let index = u64::from(self.read_scalar(&args[1])?.to_u32()?); |
3c0e092e | 432 | let (input, input_len) = self.operand_to_simd(&args[0])?; |
e74abb32 | 433 | assert!( |
3c0e092e | 434 | index < input_len, |
add651ee | 435 | "index `{index}` must be in bounds of vector with length {input_len}" |
e74abb32 | 436 | ); |
064997fb | 437 | self.copy_op( |
add651ee | 438 | &self.project_index(&input, index)?, |
064997fb FG |
439 | dest, |
440 | /*allow_transmute*/ false, | |
441 | )?; | |
e74abb32 | 442 | } |
94222f64 | 443 | sym::likely | sym::unlikely | sym::black_box => { |
f035d41b | 444 | // These just return their argument |
064997fb | 445 | self.copy_op(&args[0], dest, /*allow_transmute*/ false)?; |
f035d41b | 446 | } |
136023e0 XL |
447 | sym::raw_eq => { |
448 | let result = self.raw_eq_intrinsic(&args[0], &args[1])?; | |
449 | self.write_scalar(result, dest)?; | |
450 | } | |
064997fb FG |
451 | |
452 | sym::vtable_size => { | |
453 | let ptr = self.read_pointer(&args[0])?; | |
454 | let (size, _align) = self.get_vtable_size_and_align(ptr)?; | |
9ffffee4 | 455 | self.write_scalar(Scalar::from_target_usize(size.bytes(), self), dest)?; |
064997fb FG |
456 | } |
457 | sym::vtable_align => { | |
458 | let ptr = self.read_pointer(&args[0])?; | |
459 | let (_size, align) = self.get_vtable_size_and_align(ptr)?; | |
9ffffee4 | 460 | self.write_scalar(Scalar::from_target_usize(align.bytes(), self), dest)?; |
064997fb FG |
461 | } |
462 | ||
b7449926 XL |
463 | _ => return Ok(false), |
464 | } | |
465 | ||
781aab86 | 466 | trace!("{:?}", self.dump_place(dest)); |
60c5eb7d | 467 | self.go_to_block(ret); |
b7449926 XL |
468 | Ok(true) |
469 | } | |
470 | ||
f2b60f7d FG |
471 | pub(super) fn emulate_nondiverging_intrinsic( |
472 | &mut self, | |
473 | intrinsic: &NonDivergingIntrinsic<'tcx>, | |
474 | ) -> InterpResult<'tcx> { | |
475 | match intrinsic { | |
476 | NonDivergingIntrinsic::Assume(op) => { | |
477 | let op = self.eval_operand(op, None)?; | |
478 | let cond = self.read_scalar(&op)?.to_bool()?; | |
479 | if !cond { | |
fe692bf9 | 480 | throw_ub_custom!(fluent::const_eval_assume_false); |
f2b60f7d FG |
481 | } |
482 | Ok(()) | |
483 | } | |
484 | NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping { | |
485 | count, | |
486 | src, | |
487 | dst, | |
488 | }) => { | |
489 | let src = self.eval_operand(src, None)?; | |
490 | let dst = self.eval_operand(dst, None)?; | |
491 | let count = self.eval_operand(count, None)?; | |
492 | self.copy_intrinsic(&src, &dst, &count, /* nonoverlapping */ true) | |
493 | } | |
494 | } | |
495 | } | |
496 | ||
e74abb32 XL |
497 | pub fn exact_div( |
498 | &mut self, | |
064997fb FG |
499 | a: &ImmTy<'tcx, M::Provenance>, |
500 | b: &ImmTy<'tcx, M::Provenance>, | |
501 | dest: &PlaceTy<'tcx, M::Provenance>, | |
e74abb32 XL |
502 | ) -> InterpResult<'tcx> { |
503 | // Performs an exact division, resulting in undefined behavior where | |
74b04a01 XL |
504 | // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`. |
505 | // First, check x % y != 0 (or if that computation overflows). | |
781aab86 | 506 | let (res, overflow) = self.overflowing_binary_op(BinOp::Rem, &a, &b)?; |
5e7ed085 | 507 | assert!(!overflow); // All overflow is UB, so this should never return on overflow. |
781aab86 | 508 | if res.to_scalar().assert_bits(a.layout.size) != 0 { |
fe692bf9 FG |
509 | throw_ub_custom!( |
510 | fluent::const_eval_exact_div_has_remainder, | |
511 | a = format!("{a}"), | |
512 | b = format!("{b}") | |
513 | ) | |
e74abb32 | 514 | } |
74b04a01 | 515 | // `Rem` says this is all right, so we can let `Div` do its job. |
6a06907d | 516 | self.binop_ignore_overflow(BinOp::Div, &a, &b, dest) |
e74abb32 | 517 | } |
f9f354fc | 518 | |
5e7ed085 FG |
519 | pub fn saturating_arith( |
520 | &self, | |
521 | mir_op: BinOp, | |
064997fb FG |
522 | l: &ImmTy<'tcx, M::Provenance>, |
523 | r: &ImmTy<'tcx, M::Provenance>, | |
524 | ) -> InterpResult<'tcx, Scalar<M::Provenance>> { | |
5e7ed085 | 525 | assert!(matches!(mir_op, BinOp::Add | BinOp::Sub)); |
781aab86 | 526 | let (val, overflowed) = self.overflowing_binary_op(mir_op, l, r)?; |
5e7ed085 FG |
527 | Ok(if overflowed { |
528 | let size = l.layout.size; | |
529 | let num_bits = size.bits(); | |
530 | if l.layout.abi.is_signed() { | |
531 | // For signed ints the saturated value depends on the sign of the first | |
532 | // term since the sign of the second term can be inferred from this and | |
533 | // the fact that the operation has overflowed (if either is 0 no | |
534 | // overflow can occur) | |
f2b60f7d | 535 | let first_term: u128 = l.to_scalar().to_bits(l.layout.size)?; |
5e7ed085 FG |
536 | let first_term_positive = first_term & (1 << (num_bits - 1)) == 0; |
537 | if first_term_positive { | |
538 | // Negative overflow not possible since the positive first term | |
539 | // can only increase an (in range) negative term for addition | |
540 | // or corresponding negated positive term for subtraction | |
541 | Scalar::from_int(size.signed_int_max(), size) | |
542 | } else { | |
543 | // Positive overflow not possible for similar reason | |
544 | // max negative | |
545 | Scalar::from_int(size.signed_int_min(), size) | |
546 | } | |
547 | } else { | |
548 | // unsigned | |
549 | if matches!(mir_op, BinOp::Add) { | |
550 | // max unsigned | |
551 | Scalar::from_uint(size.unsigned_int_max(), size) | |
552 | } else { | |
553 | // underflow to 0 | |
554 | Scalar::from_uint(0u128, size) | |
555 | } | |
556 | } | |
557 | } else { | |
781aab86 | 558 | val.to_scalar() |
5e7ed085 FG |
559 | }) |
560 | } | |
561 | ||
f9f354fc XL |
562 | /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its |
563 | /// allocation. For integer pointers, we consider each of them their own tiny allocation of size | |
17df50a5 | 564 | /// 0, so offset-by-0 (and only 0) is okay -- except that null cannot be offset by _any_ value. |
f9f354fc XL |
565 | pub fn ptr_offset_inbounds( |
566 | &self, | |
064997fb | 567 | ptr: Pointer<Option<M::Provenance>>, |
f9f354fc XL |
568 | pointee_ty: Ty<'tcx>, |
569 | offset_count: i64, | |
064997fb | 570 | ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> { |
f9f354fc XL |
571 | // We cannot overflow i64 as a type's size must be <= isize::MAX. |
572 | let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap(); | |
5e7ed085 FG |
573 | // The computed offset, in bytes, must not overflow an isize. |
574 | // `checked_mul` enforces a too small bound, but no actual allocation can be big enough for | |
575 | // the difference to be noticeable. | |
f9f354fc XL |
576 | let offset_bytes = |
577 | offset_count.checked_mul(pointee_size).ok_or(err_ub!(PointerArithOverflow))?; | |
578 | // The offset being in bounds cannot rely on "wrapping around" the address space. | |
579 | // So, first rule out overflows in the pointer arithmetic. | |
136023e0 | 580 | let offset_ptr = ptr.signed_offset(offset_bytes, self)?; |
f9f354fc XL |
581 | // ptr and offset_ptr must be in bounds of the same allocated object. This means all of the |
582 | // memory between these pointers must be accessible. Note that we do not require the | |
583 | // pointers to be properly aligned (unlike a read/write operation). | |
584 | let min_ptr = if offset_bytes >= 0 { ptr } else { offset_ptr }; | |
17df50a5 | 585 | // This call handles checking for integer/null pointers. |
04454e1e | 586 | self.check_ptr_access_align( |
f9f354fc | 587 | min_ptr, |
923072b8 | 588 | Size::from_bytes(offset_bytes.unsigned_abs()), |
17df50a5 XL |
589 | Align::ONE, |
590 | CheckInAllocMsg::PointerArithmeticTest, | |
f9f354fc XL |
591 | )?; |
592 | Ok(offset_ptr) | |
593 | } | |
17df50a5 XL |
594 | |
595 | /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`. | |
596 | pub(crate) fn copy_intrinsic( | |
597 | &mut self, | |
064997fb FG |
598 | src: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>, |
599 | dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>, | |
600 | count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>, | |
17df50a5 XL |
601 | nonoverlapping: bool, |
602 | ) -> InterpResult<'tcx> { | |
add651ee | 603 | let count = self.read_target_usize(count)?; |
17df50a5 XL |
604 | let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap().ty)?; |
605 | let (size, align) = (layout.size, layout.align.abi); | |
9ffffee4 | 606 | // `checked_mul` enforces a too small bound (the correct one would probably be target_isize_max), |
5e7ed085 | 607 | // but no actual allocation can be big enough for the difference to be noticeable. |
17df50a5 | 608 | let size = size.checked_mul(count, self).ok_or_else(|| { |
fe692bf9 FG |
609 | err_ub_custom!( |
610 | fluent::const_eval_size_overflow, | |
611 | name = if nonoverlapping { "copy_nonoverlapping" } else { "copy" } | |
17df50a5 XL |
612 | ) |
613 | })?; | |
614 | ||
add651ee FG |
615 | let src = self.read_pointer(src)?; |
616 | let dst = self.read_pointer(dst)?; | |
17df50a5 | 617 | |
04454e1e | 618 | self.mem_copy(src, align, dst, align, size, nonoverlapping) |
17df50a5 | 619 | } |
136023e0 | 620 | |
a2a8927a XL |
621 | pub(crate) fn write_bytes_intrinsic( |
622 | &mut self, | |
064997fb FG |
623 | dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>, |
624 | byte: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>, | |
625 | count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>, | |
a2a8927a XL |
626 | ) -> InterpResult<'tcx> { |
627 | let layout = self.layout_of(dst.layout.ty.builtin_deref(true).unwrap().ty)?; | |
628 | ||
add651ee FG |
629 | let dst = self.read_pointer(dst)?; |
630 | let byte = self.read_scalar(byte)?.to_u8()?; | |
631 | let count = self.read_target_usize(count)?; | |
a2a8927a | 632 | |
9ffffee4 | 633 | // `checked_mul` enforces a too small bound (the correct one would probably be target_isize_max), |
5e7ed085 | 634 | // but no actual allocation can be big enough for the difference to be noticeable. |
fe692bf9 FG |
635 | let len = layout.size.checked_mul(count, self).ok_or_else(|| { |
636 | err_ub_custom!(fluent::const_eval_size_overflow, name = "write_bytes") | |
637 | })?; | |
a2a8927a XL |
638 | |
639 | let bytes = std::iter::repeat(byte).take(len.bytes_usize()); | |
04454e1e | 640 | self.write_bytes_ptr(dst, bytes) |
a2a8927a XL |
641 | } |
642 | ||
add651ee FG |
643 | pub(crate) fn compare_bytes_intrinsic( |
644 | &mut self, | |
645 | left: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>, | |
646 | right: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>, | |
647 | byte_count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>, | |
648 | ) -> InterpResult<'tcx, Scalar<M::Provenance>> { | |
649 | let left = self.read_pointer(left)?; | |
650 | let right = self.read_pointer(right)?; | |
651 | let n = Size::from_bytes(self.read_target_usize(byte_count)?); | |
652 | ||
653 | let left_bytes = self.read_bytes_ptr_strip_provenance(left, n)?; | |
654 | let right_bytes = self.read_bytes_ptr_strip_provenance(right, n)?; | |
655 | ||
656 | // `Ordering`'s discriminants are -1/0/+1, so casting does the right thing. | |
657 | let result = Ord::cmp(left_bytes, right_bytes) as i32; | |
658 | Ok(Scalar::from_i32(result)) | |
659 | } | |
660 | ||
136023e0 XL |
661 | pub(crate) fn raw_eq_intrinsic( |
662 | &mut self, | |
064997fb FG |
663 | lhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>, |
664 | rhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>, | |
665 | ) -> InterpResult<'tcx, Scalar<M::Provenance>> { | |
136023e0 | 666 | let layout = self.layout_of(lhs.layout.ty.builtin_deref(true).unwrap().ty)?; |
487cf647 | 667 | assert!(layout.is_sized()); |
136023e0 | 668 | |
f2b60f7d FG |
669 | let get_bytes = |this: &InterpCx<'mir, 'tcx, M>, |
670 | op: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>, | |
671 | size| | |
672 | -> InterpResult<'tcx, &[u8]> { | |
673 | let ptr = this.read_pointer(op)?; | |
674 | let Some(alloc_ref) = self.get_ptr_alloc(ptr, size, Align::ONE)? else { | |
675 | // zero-sized access | |
676 | return Ok(&[]); | |
677 | }; | |
678 | if alloc_ref.has_provenance() { | |
fe692bf9 | 679 | throw_ub_custom!(fluent::const_eval_raw_eq_with_provenance); |
f2b60f7d FG |
680 | } |
681 | alloc_ref.get_bytes_strip_provenance() | |
682 | }; | |
683 | ||
684 | let lhs_bytes = get_bytes(self, lhs, layout.size)?; | |
685 | let rhs_bytes = get_bytes(self, rhs, layout.size)?; | |
136023e0 XL |
686 | Ok(Scalar::from_bool(lhs_bytes == rhs_bytes)) |
687 | } | |
b7449926 | 688 | } |