1//! Computations on places -- field projections, going from mir::Place, and writing
2//! into a place.
3//! All high-level functions to write to memory work on places as destinations.
45use std::assert_matches;
67use either::{Either, Left, Right};
8use rustc_abi::{BackendRepr, HasDataLayout, Size};
9use rustc_middle::ty::layout::TyAndLayout;
10use rustc_middle::ty::{self, Ty};
11use rustc_middle::{bug, mir, span_bug};
12use tracing::field::Empty;
13use tracing::{instrument, trace};
1415use super::{
16AllocInit, AllocRef, AllocRefMut, CheckAlignMsg, CtfeProvenance, ImmTy, Immediate, InterpCx,
17InterpResult, Machine, MemoryKind, Misalignment, OffsetMode, OpTy, Operand, Pointer,
18Projectable, Provenance, Scalar, alloc_range, interp_ok, mir_assign_valid_types,
19};
20use crate::enter_trace_span;
2122#[derive(#[automatically_derived]
impl<Prov: ::core::marker::Copy + Provenance> ::core::marker::Copy for
MemPlaceMeta<Prov> {
}Copy, #[automatically_derived]
impl<Prov: ::core::clone::Clone + Provenance> ::core::clone::Clone for
MemPlaceMeta<Prov> {
#[inline]
fn clone(&self) -> MemPlaceMeta<Prov> {
match self {
MemPlaceMeta::Meta(__self_0) =>
MemPlaceMeta::Meta(::core::clone::Clone::clone(__self_0)),
MemPlaceMeta::None => MemPlaceMeta::None,
}
}
}Clone, #[automatically_derived]
impl<Prov: ::core::hash::Hash + Provenance> ::core::hash::Hash for
MemPlaceMeta<Prov> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state);
match self {
MemPlaceMeta::Meta(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
_ => {}
}
}
}Hash, #[automatically_derived]
impl<Prov: ::core::cmp::PartialEq + Provenance> ::core::cmp::PartialEq for
MemPlaceMeta<Prov> {
#[inline]
fn eq(&self, other: &MemPlaceMeta<Prov>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(MemPlaceMeta::Meta(__self_0), MemPlaceMeta::Meta(__arg1_0))
=> __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<Prov: ::core::cmp::Eq + Provenance> ::core::cmp::Eq for
MemPlaceMeta<Prov> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Scalar<Prov>>;
}
}Eq, #[automatically_derived]
impl<Prov: ::core::fmt::Debug + Provenance> ::core::fmt::Debug for
MemPlaceMeta<Prov> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
MemPlaceMeta::Meta(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Meta",
&__self_0),
MemPlaceMeta::None =>
::core::fmt::Formatter::write_str(f, "None"),
}
}
}Debug)]
23/// Information required for the sound usage of a `MemPlace`.
24pub enum MemPlaceMeta<Prov: Provenance = CtfeProvenance> {
25/// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
26Meta(Scalar<Prov>),
27/// `Sized` types or unsized `extern type`
28None,
29}
3031impl<Prov: Provenance> MemPlaceMeta<Prov> {
32#[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
33pub fn unwrap_meta(self) -> Scalar<Prov> {
34match self {
35Self::Meta(s) => s,
36Self::None => {
37::rustc_middle::util::bug::bug_fmt(format_args!("expected wide pointer extra data (e.g. slice length or trait object vtable)"))bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")38 }
39 }
40 }
4142#[inline(always)]
43pub fn has_meta(self) -> bool {
44match self {
45Self::Meta(_) => true,
46Self::None => false,
47 }
48 }
49}
5051#[derive(#[automatically_derived]
impl<Prov: ::core::marker::Copy + Provenance> ::core::marker::Copy for
MemPlace<Prov> {
}Copy, #[automatically_derived]
impl<Prov: ::core::clone::Clone + Provenance> ::core::clone::Clone for
MemPlace<Prov> {
#[inline]
fn clone(&self) -> MemPlace<Prov> {
MemPlace {
ptr: ::core::clone::Clone::clone(&self.ptr),
meta: ::core::clone::Clone::clone(&self.meta),
misaligned: ::core::clone::Clone::clone(&self.misaligned),
}
}
}Clone, #[automatically_derived]
impl<Prov: ::core::hash::Hash + Provenance> ::core::hash::Hash for
MemPlace<Prov> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.ptr, state);
::core::hash::Hash::hash(&self.meta, state);
::core::hash::Hash::hash(&self.misaligned, state)
}
}Hash, #[automatically_derived]
impl<Prov: ::core::cmp::PartialEq + Provenance> ::core::cmp::PartialEq for
MemPlace<Prov> {
#[inline]
fn eq(&self, other: &MemPlace<Prov>) -> bool {
self.ptr == other.ptr && self.meta == other.meta &&
self.misaligned == other.misaligned
}
}PartialEq, #[automatically_derived]
impl<Prov: ::core::cmp::Eq + Provenance> ::core::cmp::Eq for MemPlace<Prov> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Pointer<Option<Prov>>>;
let _: ::core::cmp::AssertParamIsEq<MemPlaceMeta<Prov>>;
let _: ::core::cmp::AssertParamIsEq<Option<Misalignment>>;
}
}Eq, #[automatically_derived]
impl<Prov: ::core::fmt::Debug + Provenance> ::core::fmt::Debug for
MemPlace<Prov> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "MemPlace",
"ptr", &self.ptr, "meta", &self.meta, "misaligned",
&&self.misaligned)
}
}Debug)]
52pub(super) struct MemPlace<Prov: Provenance = CtfeProvenance> {
53/// The pointer can be a pure integer, with the `None` provenance.
54pub ptr: Pointer<Option<Prov>>,
55/// Metadata for unsized places. Interpretation is up to the type.
56 /// Must not be present for sized types, but can be missing for unsized types
57 /// (e.g., `extern type`).
58pub meta: MemPlaceMeta<Prov>,
59/// Stores whether this place was created based on a sufficiently aligned pointer.
60misaligned: Option<Misalignment>,
61}
6263impl<Prov: Provenance> MemPlace<Prov> {
64/// Adjust the provenance of the main pointer (metadata is unaffected).
65fn map_provenance(self, f: impl FnOnce(Prov) -> Prov) -> Self {
66MemPlace { ptr: self.ptr.map_provenance(|p| p.map(f)), ..self }
67 }
6869/// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
70#[inline]
71fn to_ref(self, cx: &impl HasDataLayout) -> Immediate<Prov> {
72Immediate::new_pointer_with_meta(self.ptr, self.meta, cx)
73 }
7475#[inline]
76// Not called `offset_with_meta` to avoid confusion with the trait method.
77fn offset_with_meta_<'tcx, M: Machine<'tcx, Provenance = Prov>>(
78self,
79 offset: Size,
80 mode: OffsetMode,
81 meta: MemPlaceMeta<Prov>,
82 ecx: &InterpCx<'tcx, M>,
83 ) -> InterpResult<'tcx, Self> {
84if true {
if !(!meta.has_meta() || self.meta.has_meta()) {
{
::core::panicking::panic_fmt(format_args!("cannot use `offset_with_meta` to add metadata to a place"));
}
};
};debug_assert!(
85 !meta.has_meta() || self.meta.has_meta(),
86"cannot use `offset_with_meta` to add metadata to a place"
87);
88let ptr = match mode {
89 OffsetMode::Inbounds => {
90ecx.ptr_offset_inbounds(self.ptr, offset.bytes().try_into().unwrap())?
91}
92 OffsetMode::Wrapping => self.ptr.wrapping_offset(offset, ecx),
93 };
94interp_ok(MemPlace { ptr, meta, misaligned: self.misaligned })
95 }
96}
9798/// A MemPlace with its layout. Constructing it is only possible in this module.
99#[derive(#[automatically_derived]
impl<'tcx, Prov: ::core::clone::Clone + Provenance> ::core::clone::Clone for
MPlaceTy<'tcx, Prov> {
#[inline]
fn clone(&self) -> MPlaceTy<'tcx, Prov> {
MPlaceTy {
mplace: ::core::clone::Clone::clone(&self.mplace),
layout: ::core::clone::Clone::clone(&self.layout),
}
}
}Clone, #[automatically_derived]
impl<'tcx, Prov: ::core::hash::Hash + Provenance> ::core::hash::Hash for
MPlaceTy<'tcx, Prov> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.mplace, state);
::core::hash::Hash::hash(&self.layout, state)
}
}Hash, #[automatically_derived]
impl<'tcx, Prov: ::core::cmp::Eq + Provenance> ::core::cmp::Eq for
MPlaceTy<'tcx, Prov> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<MemPlace<Prov>>;
let _: ::core::cmp::AssertParamIsEq<TyAndLayout<'tcx>>;
}
}Eq, #[automatically_derived]
impl<'tcx, Prov: ::core::cmp::PartialEq + Provenance> ::core::cmp::PartialEq
for MPlaceTy<'tcx, Prov> {
#[inline]
fn eq(&self, other: &MPlaceTy<'tcx, Prov>) -> bool {
self.mplace == other.mplace && self.layout == other.layout
}
}PartialEq)]
100pub struct MPlaceTy<'tcx, Prov: Provenance = CtfeProvenance> {
101 mplace: MemPlace<Prov>,
102pub layout: TyAndLayout<'tcx>,
103}
104105impl<Prov: Provenance> std::fmt::Debugfor MPlaceTy<'_, Prov> {
106fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107// Printing `layout` results in too much noise; just print a nice version of the type.
108f.debug_struct("MPlaceTy")
109 .field("mplace", &self.mplace)
110 .field("ty", &format_args!("{0}", self.layout.ty)format_args!("{}", self.layout.ty))
111 .finish()
112 }
113}
114115impl<'tcx, Prov: Provenance> MPlaceTy<'tcx, Prov> {
116/// Produces a MemPlace that works for ZST but nothing else.
117 /// Conceptually this is a new allocation, but it doesn't actually create an allocation so you
118 /// don't need to worry about memory leaks.
119#[inline]
120pub fn fake_alloc_zst(layout: TyAndLayout<'tcx>) -> Self {
121if !layout.is_zst() {
::core::panicking::panic("assertion failed: layout.is_zst()")
};assert!(layout.is_zst());
122let align = layout.align.abi;
123let ptr = Pointer::without_provenance(align.bytes()); // no provenance, absolute address
124MPlaceTy { mplace: MemPlace { ptr, meta: MemPlaceMeta::None, misaligned: None }, layout }
125 }
126127/// Adjust the provenance of the main pointer (metadata is unaffected).
128pub fn map_provenance(self, f: impl FnOnce(Prov) -> Prov) -> Self {
129MPlaceTy { mplace: self.mplace.map_provenance(f), ..self }
130 }
131132#[inline(always)]
133pub(super) fn mplace(&self) -> &MemPlace<Prov> {
134&self.mplace
135 }
136137#[inline(always)]
138pub fn ptr(&self) -> Pointer<Option<Prov>> {
139self.mplace.ptr
140 }
141142#[inline(always)]
143pub fn to_ref(&self, cx: &impl HasDataLayout) -> Immediate<Prov> {
144self.mplace.to_ref(cx)
145 }
146}
147148impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for MPlaceTy<'tcx, Prov> {
149#[inline(always)]
150fn layout(&self) -> TyAndLayout<'tcx> {
151self.layout
152 }
153154#[inline(always)]
155fn meta(&self) -> MemPlaceMeta<Prov> {
156self.mplace.meta
157 }
158159fn offset_with_meta<M: Machine<'tcx, Provenance = Prov>>(
160&self,
161 offset: Size,
162 mode: OffsetMode,
163 meta: MemPlaceMeta<Prov>,
164 layout: TyAndLayout<'tcx>,
165 ecx: &InterpCx<'tcx, M>,
166 ) -> InterpResult<'tcx, Self> {
167interp_ok(MPlaceTy {
168 mplace: self.mplace.offset_with_meta_(offset, mode, meta, ecx)?,
169layout,
170 })
171 }
172173#[inline(always)]
174fn to_op<M: Machine<'tcx, Provenance = Prov>>(
175&self,
176 _ecx: &InterpCx<'tcx, M>,
177 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
178interp_ok(self.clone().into())
179 }
180}
181182#[derive(#[automatically_derived]
impl<Prov: ::core::marker::Copy + Provenance> ::core::marker::Copy for
Place<Prov> {
}Copy, #[automatically_derived]
impl<Prov: ::core::clone::Clone + Provenance> ::core::clone::Clone for
Place<Prov> {
#[inline]
fn clone(&self) -> Place<Prov> {
match self {
Place::Ptr(__self_0) =>
Place::Ptr(::core::clone::Clone::clone(__self_0)),
Place::Local {
local: __self_0, offset: __self_1, locals_addr: __self_2 } =>
Place::Local {
local: ::core::clone::Clone::clone(__self_0),
offset: ::core::clone::Clone::clone(__self_1),
locals_addr: ::core::clone::Clone::clone(__self_2),
},
}
}
}Clone, #[automatically_derived]
impl<Prov: ::core::fmt::Debug + Provenance> ::core::fmt::Debug for Place<Prov>
{
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Place::Ptr(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ptr",
&__self_0),
Place::Local {
local: __self_0, offset: __self_1, locals_addr: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f, "Local",
"local", __self_0, "offset", __self_1, "locals_addr",
&__self_2),
}
}
}Debug)]
183pub(super) enum Place<Prov: Provenance = CtfeProvenance> {
184/// A place referring to a value allocated in the `Memory` system.
185Ptr(MemPlace<Prov>),
186187/// To support alloc-free locals, we are able to write directly to a local. The offset indicates
188 /// where in the local this place is located; if it is `None`, no projection has been applied
189 /// and the type of the place is exactly the type of the local.
190 /// Such projections are meaningful even if the offset is 0, since they can change layouts.
191 /// (Without that optimization, we'd just always be a `MemPlace`.)
192 /// `Local` places always refer to the current stack frame, so they are unstable under
193 /// function calls/returns and switching betweens stacks of different threads!
194 /// We carry around the address of the `locals` buffer of the correct stack frame as a sanity
195 /// check to be able to catch some cases of using a dangling `Place`.
196 ///
197 /// This variant shall not be used for unsized types -- those must always live in memory.
198Local { local: mir::Local, offset: Option<Size>, locals_addr: usize },
199}
200201/// An evaluated place, together with its type.
202///
203/// This may reference a stack frame by its index, so `PlaceTy` should generally not be kept around
204/// for longer than a single operation. Popping and then pushing a stack frame can make `PlaceTy`
205/// point to the wrong destination. If the interpreter has multiple stacks, stack switching will
206/// also invalidate a `PlaceTy`.
207#[derive(#[automatically_derived]
impl<'tcx, Prov: ::core::clone::Clone + Provenance> ::core::clone::Clone for
PlaceTy<'tcx, Prov> {
#[inline]
fn clone(&self) -> PlaceTy<'tcx, Prov> {
PlaceTy {
place: ::core::clone::Clone::clone(&self.place),
layout: ::core::clone::Clone::clone(&self.layout),
}
}
}Clone)]
208pub struct PlaceTy<'tcx, Prov: Provenance = CtfeProvenance> {
209 place: Place<Prov>, // Keep this private; it helps enforce invariants.
210pub layout: TyAndLayout<'tcx>,
211}
212213impl<Prov: Provenance> std::fmt::Debugfor PlaceTy<'_, Prov> {
214fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215// Printing `layout` results in too much noise; just print a nice version of the type.
216f.debug_struct("PlaceTy")
217 .field("place", &self.place)
218 .field("ty", &format_args!("{0}", self.layout.ty)format_args!("{}", self.layout.ty))
219 .finish()
220 }
221}
222223impl<'tcx, Prov: Provenance> From<MPlaceTy<'tcx, Prov>> for PlaceTy<'tcx, Prov> {
224#[inline(always)]
225fn from(mplace: MPlaceTy<'tcx, Prov>) -> Self {
226PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout }
227 }
228}
229230impl<'tcx, Prov: Provenance> PlaceTy<'tcx, Prov> {
231#[inline(always)]
232pub(super) fn place(&self) -> &Place<Prov> {
233&self.place
234 }
235236/// A place is either an mplace or some local.
237 ///
238 /// Note that the return value can be different even for logically identical places!
239 /// Specifically, if a local is stored in-memory, this may return `Local` or `MPlaceTy`
240 /// depending on how the place was constructed. In other words, seeing `Local` here does *not*
241 /// imply that this place does not point to memory. Every caller must therefore always handle
242 /// both cases.
243#[inline(always)]
244pub fn as_mplace_or_local(
245&self,
246 ) -> Either<MPlaceTy<'tcx, Prov>, (mir::Local, Option<Size>, usize, TyAndLayout<'tcx>)> {
247match self.place {
248 Place::Ptr(mplace) => Left(MPlaceTy { mplace, layout: self.layout }),
249 Place::Local { local, offset, locals_addr } => {
250Right((local, offset, locals_addr, self.layout))
251 }
252 }
253 }
254255#[inline(always)]
256 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
257pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Prov> {
258self.as_mplace_or_local().left().unwrap_or_else(|| {
259::rustc_middle::util::bug::bug_fmt(format_args!("PlaceTy of type {0} was a local when it was expected to be an MPlace",
self.layout.ty))bug!(
260"PlaceTy of type {} was a local when it was expected to be an MPlace",
261self.layout.ty
262 )263 })
264 }
265}
266267impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for PlaceTy<'tcx, Prov> {
268#[inline(always)]
269fn layout(&self) -> TyAndLayout<'tcx> {
270self.layout
271 }
272273#[inline]
274fn meta(&self) -> MemPlaceMeta<Prov> {
275match self.as_mplace_or_local() {
276Left(mplace) => mplace.meta(),
277Right(_) => {
278if true {
if !self.layout.is_sized() {
{
::core::panicking::panic_fmt(format_args!("unsized locals should live in memory"));
}
};
};debug_assert!(self.layout.is_sized(), "unsized locals should live in memory");
279 MemPlaceMeta::None280 }
281 }
282 }
283284fn offset_with_meta<M: Machine<'tcx, Provenance = Prov>>(
285&self,
286 offset: Size,
287 mode: OffsetMode,
288 meta: MemPlaceMeta<Prov>,
289 layout: TyAndLayout<'tcx>,
290 ecx: &InterpCx<'tcx, M>,
291 ) -> InterpResult<'tcx, Self> {
292interp_ok(match self.as_mplace_or_local() {
293Left(mplace) => mplace.offset_with_meta(offset, mode, meta, layout, ecx)?.into(),
294Right((local, old_offset, locals_addr, _)) => {
295if true {
if !layout.is_sized() {
{
::core::panicking::panic_fmt(format_args!("unsized locals should live in memory"));
}
};
};debug_assert!(layout.is_sized(), "unsized locals should live in memory");
296match meta {
MemPlaceMeta::None => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"MemPlaceMeta::None", ::core::option::Option::None);
}
};assert_matches!(meta, MemPlaceMeta::None); // we couldn't store it anyway...
297 // `Place::Local` are always in-bounds of their surrounding local, so we can just
298 // check directly if this remains in-bounds. This cannot actually be violated since
299 // projections are type-checked and bounds-checked.
300if !(offset + layout.size <= self.layout.size) {
::core::panicking::panic("assertion failed: offset + layout.size <= self.layout.size")
};assert!(offset + layout.size <= self.layout.size);
301302// Size `+`, ensures no overflow.
303let new_offset = old_offset.unwrap_or(Size::ZERO) + offset;
304305PlaceTy {
306 place: Place::Local { local, offset: Some(new_offset), locals_addr },
307layout,
308 }
309 }
310 })
311 }
312313#[inline(always)]
314fn to_op<M: Machine<'tcx, Provenance = Prov>>(
315&self,
316 ecx: &InterpCx<'tcx, M>,
317 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
318ecx.place_to_op(self)
319 }
320}
321322// These are defined here because they produce a place.
323impl<'tcx, Prov: Provenance> OpTy<'tcx, Prov> {
324#[inline(always)]
325pub fn as_mplace_or_imm(&self) -> Either<MPlaceTy<'tcx, Prov>, ImmTy<'tcx, Prov>> {
326match self.op() {
327 Operand::Indirect(mplace) => Left(MPlaceTy { mplace: *mplace, layout: self.layout }),
328 Operand::Immediate(imm) => Right(ImmTy::from_immediate(*imm, self.layout)),
329 }
330 }
331332#[inline(always)]
333 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
334pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Prov> {
335self.as_mplace_or_imm().left().unwrap_or_else(|| {
336::rustc_middle::util::bug::bug_fmt(format_args!("OpTy of type {0} was immediate when it was expected to be an MPlace",
self.layout.ty))bug!(
337"OpTy of type {} was immediate when it was expected to be an MPlace",
338self.layout.ty
339 )340 })
341 }
342}
343344/// The `Weiteable` trait describes interpreter values that can be written to.
345pub trait Writeable<'tcx, Prov: Provenance>: Projectable<'tcx, Prov> {
346fn to_place(&self) -> PlaceTy<'tcx, Prov>;
347348fn force_mplace<M: Machine<'tcx, Provenance = Prov>>(
349&self,
350 ecx: &mut InterpCx<'tcx, M>,
351 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Prov>>;
352}
353354impl<'tcx, Prov: Provenance> Writeable<'tcx, Prov> for PlaceTy<'tcx, Prov> {
355#[inline(always)]
356fn to_place(&self) -> PlaceTy<'tcx, Prov> {
357self.clone()
358 }
359360#[inline(always)]
361fn force_mplace<M: Machine<'tcx, Provenance = Prov>>(
362&self,
363 ecx: &mut InterpCx<'tcx, M>,
364 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Prov>> {
365ecx.force_allocation(self)
366 }
367}
368369impl<'tcx, Prov: Provenance> Writeable<'tcx, Prov> for MPlaceTy<'tcx, Prov> {
370#[inline(always)]
371fn to_place(&self) -> PlaceTy<'tcx, Prov> {
372self.clone().into()
373 }
374375#[inline(always)]
376fn force_mplace<M: Machine<'tcx, Provenance = Prov>>(
377&self,
378 _ecx: &mut InterpCx<'tcx, M>,
379 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Prov>> {
380interp_ok(self.clone())
381 }
382}
383384// FIXME: Working around https://github.com/rust-lang/rust/issues/54385
385impl<'tcx, Prov, M> InterpCx<'tcx, M>
386where
387Prov: Provenance,
388 M: Machine<'tcx, Provenance = Prov>,
389{
390fn ptr_with_meta_to_mplace(
391&self,
392 ptr: Pointer<Option<M::Provenance>>,
393 meta: MemPlaceMeta<M::Provenance>,
394 layout: TyAndLayout<'tcx>,
395 unaligned: bool,
396 ) -> MPlaceTy<'tcx, M::Provenance> {
397let misaligned =
398if unaligned { None } else { self.is_ptr_misaligned(ptr, layout.align.abi) };
399MPlaceTy { mplace: MemPlace { ptr, meta, misaligned }, layout }
400 }
401402pub fn ptr_to_mplace(
403&self,
404 ptr: Pointer<Option<M::Provenance>>,
405 layout: TyAndLayout<'tcx>,
406 ) -> MPlaceTy<'tcx, M::Provenance> {
407if !layout.is_sized() {
::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
408self.ptr_with_meta_to_mplace(ptr, MemPlaceMeta::None, layout, /*unaligned*/ false)
409 }
410411pub fn ptr_to_mplace_unaligned(
412&self,
413 ptr: Pointer<Option<M::Provenance>>,
414 layout: TyAndLayout<'tcx>,
415 ) -> MPlaceTy<'tcx, M::Provenance> {
416if !layout.is_sized() {
::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
417self.ptr_with_meta_to_mplace(ptr, MemPlaceMeta::None, layout, /*unaligned*/ true)
418 }
419420/// Take a value, which represents a (thin or wide) pointer, and make it a place.
421 /// Alignment is just based on the type. This is the inverse of `mplace_to_imm_ptr()`.
422 ///
423 /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
424 /// want to ever use the place for memory access!
425 /// Generally prefer `deref_pointer`.
426pub fn imm_ptr_to_mplace(
427&self,
428 val: &ImmTy<'tcx, M::Provenance>,
429 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
430let pointee_type =
431val.layout.ty.builtin_deref(true).expect("`imm_ptr_to_mplace` called on non-ptr type");
432let layout = self.layout_of(pointee_type)?;
433let (ptr, meta) = val.to_scalar_and_meta();
434435// `imm_ptr_to_mplace` is called on raw pointers even if they don't actually get dereferenced;
436 // we hence can't call `size_and_align_of` since that asserts more validity than we want.
437let ptr = ptr.to_pointer(self)?;
438interp_ok(self.ptr_with_meta_to_mplace(ptr, meta, layout, /*unaligned*/ false))
439 }
440441/// Turn a mplace into a (thin or wide) mutable raw pointer, pointing to the same space.
442 ///
443 /// `align` information is lost!
444 /// This is the inverse of `imm_ptr_to_mplace`.
445 ///
446 /// If `ptr_ty` is provided, the resulting pointer will be of that type. Otherwise, it defaults to `*mut _`.
447 /// `ptr_ty` must be a type with builtin deref which derefs to the type of `mplace` (`mplace.layout.ty`).
448pub fn mplace_to_imm_ptr(
449&self,
450 mplace: &MPlaceTy<'tcx, M::Provenance>,
451 ptr_ty: Option<Ty<'tcx>>,
452 ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
453let imm = mplace.mplace.to_ref(self);
454455let ptr_ty = ptr_ty456 .inspect(|t| match (&t.builtin_deref(true), &Some(mplace.layout.ty)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
}assert_eq!(t.builtin_deref(true), Some(mplace.layout.ty)))
457 .unwrap_or_else(|| Ty::new_mut_ptr(self.tcx.tcx, mplace.layout.ty));
458459let layout = self.layout_of(ptr_ty)?;
460interp_ok(ImmTy::from_immediate(imm, layout))
461 }
462463/// Take an operand, representing a pointer, and dereference it to a place.
464 /// Corresponds to the `*` operator in Rust.
465#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("deref_pointer",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(465u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&["src"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&src)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> = loop {};
return __tracing_attr_fake_return;
}
{
if src.layout().ty.is_box() {
::rustc_middle::util::bug::bug_fmt(format_args!("dereferencing {0}",
src.layout().ty));
}
let val = self.read_immediate(src)?;
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/place.rs:478",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(478u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("deref to {0} on {1:?}",
val.layout.ty, *val) as &dyn Value))])
});
} else { ; }
};
let mplace = self.imm_ptr_to_mplace(&val)?;
interp_ok(mplace)
}
}
}#[instrument(skip(self), level = "trace")]466pub fn deref_pointer(
467&self,
468 src: &impl Projectable<'tcx, M::Provenance>,
469 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
470if src.layout().ty.is_box() {
471// Derefer should have removed all Box derefs.
472 // Some `Box` are not immediates (if they have a custom allocator)
473 // so the code below would fail.
474bug!("dereferencing {}", src.layout().ty);
475 }
476477let val = self.read_immediate(src)?;
478trace!("deref to {} on {:?}", val.layout.ty, *val);
479480let mplace = self.imm_ptr_to_mplace(&val)?;
481 interp_ok(mplace)
482 }
483484#[inline]
485pub(super) fn get_place_alloc(
486&self,
487 mplace: &MPlaceTy<'tcx, M::Provenance>,
488 ) -> InterpResult<'tcx, Option<AllocRef<'_, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
489 {
490let (size, _align) = self491 .size_and_align_of_val(mplace)?
492.unwrap_or((mplace.layout.size, mplace.layout.align.abi));
493// We check alignment separately, and *after* checking everything else.
494 // If an access is both OOB and misaligned, we want to see the bounds error.
495let a = self.get_ptr_alloc(mplace.ptr(), size)?;
496self.check_misalign(mplace.mplace.misaligned, CheckAlignMsg::BasedOn)?;
497interp_ok(a)
498 }
499500#[inline]
501pub(super) fn get_place_alloc_mut(
502&mut self,
503 mplace: &MPlaceTy<'tcx, M::Provenance>,
504 ) -> InterpResult<'tcx, Option<AllocRefMut<'_, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
505 {
506let (size, _align) = self507 .size_and_align_of_val(mplace)?
508.unwrap_or((mplace.layout.size, mplace.layout.align.abi));
509// We check alignment separately, and raise that error *after* checking everything else.
510 // If an access is both OOB and misaligned, we want to see the bounds error.
511 // However we have to call `check_misalign` first to make the borrow checker happy.
512let misalign_res = self.check_misalign(mplace.mplace.misaligned, CheckAlignMsg::BasedOn);
513// An error from get_ptr_alloc_mut takes precedence.
514let (a, ()) = self.get_ptr_alloc_mut(mplace.ptr(), size).and(misalign_res)?;
515interp_ok(a)
516 }
517518/// Turn a local in the current frame into a place.
519pub fn local_to_place(
520&self,
521 local: mir::Local,
522 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
523let frame = self.frame();
524let layout = self.layout_of_local(frame, local, None)?;
525let place = if layout.is_sized() {
526// We can just always use the `Local` for sized values.
527Place::Local { local, offset: None, locals_addr: frame.locals_addr() }
528 } else {
529// Other parts of the system rely on `Place::Local` never being unsized.
530match frame.locals[local].access()? {
531 Operand::Immediate(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
532 Operand::Indirect(mplace) => Place::Ptr(*mplace),
533 }
534 };
535interp_ok(PlaceTy { place, layout })
536 }
537538/// Computes a place. You should only use this if you intend to write into this
539 /// place; for reading, a more efficient alternative is `eval_place_to_op`.
540#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("eval_place",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(540u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&["mir_place"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&mir_place)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> = loop {};
return __tracing_attr_fake_return;
}
{
let _trace =
<M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("step",
"rustc_const_eval::interpret::place",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(546u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&["step", "mir_place",
"tracing_separate_thread"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&display(&"eval_place")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&mir_place)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&Empty as
&dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
});
let mut place = self.local_to_place(mir_place.local)?;
for elem in mir_place.projection.iter() {
place = self.project(&place, elem)?
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/place.rs:554",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(554u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
self.dump_place(&place)) as &dyn Value))])
});
} else { ; }
};
if true {
let normalized_place_ty =
self.instantiate_from_current_frame_and_normalize_erasing_regions(mir_place.ty(&self.frame().body.local_decls,
*self.tcx).ty)?;
if !mir_assign_valid_types(*self.tcx, self.typing_env,
self.layout_of(normalized_place_ty)?, place.layout) {
::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("eval_place of a MIR place with type {0} produced an interpreter place with type {1}",
normalized_place_ty, place.layout.ty))
}
}
interp_ok(place)
}
}
}#[instrument(skip(self), level = "trace")]541pub fn eval_place(
542&self,
543 mir_place: mir::Place<'tcx>,
544 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
545let _trace =
546enter_trace_span!(M, step::eval_place, ?mir_place, tracing_separate_thread = Empty);
547548let mut place = self.local_to_place(mir_place.local)?;
549// Using `try_fold` turned out to be bad for performance, hence the loop.
550for elem in mir_place.projection.iter() {
551 place = self.project(&place, elem)?
552}
553554trace!("{:?}", self.dump_place(&place));
555// Sanity-check the type we ended up with.
556if cfg!(debug_assertions) {
557let normalized_place_ty = self
558.instantiate_from_current_frame_and_normalize_erasing_regions(
559 mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty,
560 )?;
561if !mir_assign_valid_types(
562*self.tcx,
563self.typing_env,
564self.layout_of(normalized_place_ty)?,
565 place.layout,
566 ) {
567span_bug!(
568self.cur_span(),
569"eval_place of a MIR place with type {} produced an interpreter place with type {}",
570 normalized_place_ty,
571 place.layout.ty,
572 )
573 }
574 }
575 interp_ok(place)
576 }
577578/// Given a place, returns either the underlying mplace or a reference to where the value of
579 /// this place is stored.
580#[inline(always)]
581fn as_mplace_or_mutable_local(
582&mut self,
583 place: &PlaceTy<'tcx, M::Provenance>,
584 ) -> InterpResult<
585'tcx,
586Either<
587MPlaceTy<'tcx, M::Provenance>,
588 (&mut Immediate<M::Provenance>, TyAndLayout<'tcx>, mir::Local),
589 >,
590 > {
591interp_ok(match place.to_place().as_mplace_or_local() {
592Left(mplace) => Left(mplace),
593Right((local, offset, locals_addr, layout)) => {
594if offset.is_some() {
595// This has been projected to a part of this local, or had the type changed.
596 // FIXME: there are cases where we could still avoid allocating an mplace.
597Left(place.force_mplace(self)?)
598 } else {
599if true {
match (&locals_addr, &self.frame().locals_addr()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(locals_addr, self.frame().locals_addr());
600if true {
match (&self.layout_of_local(self.frame(), local, None)?, &layout) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(self.layout_of_local(self.frame(), local, None)?, layout);
601match self.frame_mut().locals[local].access_mut()? {
602 Operand::Indirect(mplace) => {
603// The local is in memory.
604Left(MPlaceTy { mplace: *mplace, layout })
605 }
606 Operand::Immediate(local_val) => {
607// The local still has the optimized representation.
608Right((local_val, layout, local))
609 }
610 }
611 }
612 }
613 })
614 }
615616/// Write an immediate to a place
617#[inline(always)]
618#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("write_immediate",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(618u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&["src", "dest"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&src)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dest)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: InterpResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
self.write_immediate_no_validate(src, dest)?;
if M::enforce_validity(self, dest.layout()) {
self.validate_operand(&dest.to_place(),
M::enforce_validity_recursively(self, dest.layout()),
true)?;
}
interp_ok(())
}
}
}#[instrument(skip(self), level = "trace")]619pub fn write_immediate(
620&mut self,
621 src: Immediate<M::Provenance>,
622 dest: &impl Writeable<'tcx, M::Provenance>,
623 ) -> InterpResult<'tcx> {
624self.write_immediate_no_validate(src, dest)?;
625626if M::enforce_validity(self, dest.layout()) {
627// Data got changed, better make sure it matches the type!
628 // Also needed to reset padding.
629self.validate_operand(
630&dest.to_place(),
631 M::enforce_validity_recursively(self, dest.layout()),
632/*reset_provenance_and_padding*/ true,
633 )?;
634 }
635636 interp_ok(())
637 }
638639/// Write a scalar to a place
640#[inline(always)]
641pub fn write_scalar(
642&mut self,
643 val: impl Into<Scalar<M::Provenance>>,
644 dest: &impl Writeable<'tcx, M::Provenance>,
645 ) -> InterpResult<'tcx> {
646self.write_immediate(Immediate::Scalar(val.into()), dest)
647 }
648649/// Write a pointer to a place
650#[inline(always)]
651pub fn write_pointer(
652&mut self,
653 ptr: impl Into<Pointer<Option<M::Provenance>>>,
654 dest: &impl Writeable<'tcx, M::Provenance>,
655 ) -> InterpResult<'tcx> {
656self.write_scalar(Scalar::from_maybe_pointer(ptr.into(), self), dest)
657 }
658659/// Write an immediate to a place.
660 /// If you use this you are responsible for validating that things got copied at the
661 /// right type.
662pub(super) fn write_immediate_no_validate(
663&mut self,
664 src: Immediate<M::Provenance>,
665 dest: &impl Writeable<'tcx, M::Provenance>,
666 ) -> InterpResult<'tcx> {
667if !dest.layout().is_sized() {
{
::core::panicking::panic_fmt(format_args!("Cannot write unsized immediate data"));
}
};assert!(dest.layout().is_sized(), "Cannot write unsized immediate data");
668669match self.as_mplace_or_mutable_local(&dest.to_place())? {
670Right((local_val, local_layout, local)) => {
671// Local can be updated in-place.
672*local_val = src;
673// Call the machine hook (the data race detector needs to know about this write).
674if !self.validation_in_progress() {
675 M::after_local_write(self, local, /*storage_live*/ false)?;
676 }
677// Double-check that the value we are storing and the local fit to each other.
678 // Things can ge wrong in quite weird ways when this is violated.
679 // Unfortunately this is too expensive to do in release builds.
680if truecfg!(debug_assertions) {
681src.assert_matches_abi(
682local_layout.backend_repr,
683"invalid immediate for given destination place",
684self,
685 );
686 }
687 }
688Left(mplace) => {
689self.write_immediate_to_mplace_no_validate(src, mplace.layout, mplace.mplace)?;
690 }
691 }
692interp_ok(())
693 }
694695/// Write an immediate to memory.
696 /// If you use this you are responsible for validating that things got copied at the
697 /// right layout.
698fn write_immediate_to_mplace_no_validate(
699&mut self,
700 value: Immediate<M::Provenance>,
701 layout: TyAndLayout<'tcx>,
702 dest: MemPlace<M::Provenance>,
703 ) -> InterpResult<'tcx> {
704// We use the sizes from `value` below.
705 // Ensure that matches the type of the place it is written to.
706value.assert_matches_abi(
707layout.backend_repr,
708"invalid immediate for given destination place",
709self,
710 );
711// Note that it is really important that the type here is the right one, and matches the
712 // type things are read at. In case `value` is a `ScalarPair`, we don't do any magic here
713 // to handle padding properly, which is only correct if we never look at this data with the
714 // wrong type.
715716let tcx = *self.tcx;
717let will_later_validate = M::enforce_validity(self, layout);
718let Some(mut alloc) = self.get_place_alloc_mut(&MPlaceTy { mplace: dest, layout })? else {
719// zero-sized access
720return interp_ok(());
721 };
722723match value {
724 Immediate::Scalar(scalar) => {
725alloc.write_scalar(alloc_range(Size::ZERO, scalar.size()), scalar)?;
726 }
727 Immediate::ScalarPair(a_val, b_val) => {
728let BackendRepr::ScalarPair(_a, b) = layout.backend_repr else {
729::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("write_immediate_to_mplace: invalid ScalarPair layout: {0:#?}",
layout))span_bug!(
730self.cur_span(),
731"write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
732 layout
733 )734 };
735let a_size = a_val.size();
736let b_offset = a_size.align_to(b.align(&tcx).abi);
737if !(b_offset.bytes() > 0) {
::core::panicking::panic("assertion failed: b_offset.bytes() > 0")
};assert!(b_offset.bytes() > 0); // in `operand_field` we use the offset to tell apart the fields
738739 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
740 // but that does not work: We could be a newtype around a pair, then the
741 // fields do not match the `ScalarPair` components.
742743 // In preparation, if we do *not* later reset the padding, we clear the entire
744 // destination now to ensure that no stray pointer fragments are being
745 // preserved (see <https://github.com/rust-lang/rust/issues/148470>).
746 // We can skip this if there is no padding (e.g. for wide pointers).
747if !will_later_validate && a_size + b_val.size() != layout.size {
748alloc.write_uninit_full();
749 }
750751alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?;
752alloc.write_scalar(alloc_range(b_offset, b_val.size()), b_val)?;
753 }
754 Immediate::Uninit => alloc.write_uninit_full(),
755 }
756interp_ok(())
757 }
758759pub fn write_uninit(
760&mut self,
761 dest: &impl Writeable<'tcx, M::Provenance>,
762 ) -> InterpResult<'tcx> {
763match self.as_mplace_or_mutable_local(&dest.to_place())? {
764Right((local_val, _local_layout, local)) => {
765*local_val = Immediate::Uninit;
766// Call the machine hook (the data race detector needs to know about this write).
767if !self.validation_in_progress() {
768 M::after_local_write(self, local, /*storage_live*/ false)?;
769 }
770 }
771Left(mplace) => {
772let Some(mut alloc) = self.get_place_alloc_mut(&mplace)? else {
773// Zero-sized access
774return interp_ok(());
775 };
776alloc.write_uninit_full();
777 }
778 }
779interp_ok(())
780 }
781782/// Remove all provenance in the given place.
783pub fn clear_provenance(
784&mut self,
785 dest: &impl Writeable<'tcx, M::Provenance>,
786 ) -> InterpResult<'tcx> {
787// If this is an efficiently represented local variable without provenance, skip the
788 // `as_mplace_or_mutable_local` that would otherwise force this local into memory.
789if let Right(imm) = dest.to_op(self)?.as_mplace_or_imm() {
790if !imm.has_provenance() {
791return interp_ok(());
792 }
793 }
794match self.as_mplace_or_mutable_local(&dest.to_place())? {
795Right((local_val, _local_layout, local)) => {
796local_val.clear_provenance()?;
797// Call the machine hook (the data race detector needs to know about this write).
798if !self.validation_in_progress() {
799 M::after_local_write(self, local, /*storage_live*/ false)?;
800 }
801 }
802Left(mplace) => {
803let Some(mut alloc) = self.get_place_alloc_mut(&mplace)? else {
804// Zero-sized access
805return interp_ok(());
806 };
807alloc.clear_provenance();
808 }
809 }
810interp_ok(())
811 }
812813/// Copies the data from an operand to a place.
814 /// The layouts of the `src` and `dest` may disagree.
815#[inline(always)]
816pub fn copy_op_allow_transmute(
817&mut self,
818 src: &impl Projectable<'tcx, M::Provenance>,
819 dest: &impl Writeable<'tcx, M::Provenance>,
820 ) -> InterpResult<'tcx> {
821self.copy_op_inner(src, dest, /* allow_transmute */ true)
822 }
823824/// Copies the data from an operand to a place.
825 /// `src` and `dest` must have the same layout and the copied value will be validated.
826#[inline(always)]
827pub fn copy_op(
828&mut self,
829 src: &impl Projectable<'tcx, M::Provenance>,
830 dest: &impl Writeable<'tcx, M::Provenance>,
831 ) -> InterpResult<'tcx> {
832self.copy_op_inner(src, dest, /* allow_transmute */ false)
833 }
834835/// Copies the data from an operand to a place.
836 /// `allow_transmute` indicates whether the layouts may disagree.
837#[inline(always)]
838#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("copy_op_inner",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(838u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&["src", "dest",
"allow_transmute"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&src)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dest)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&allow_transmute as
&dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: InterpResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
self.copy_op_no_validate(src, dest, allow_transmute)?;
if M::enforce_validity(self, dest.layout()) {
let dest = dest.to_place();
if src.layout().ty != dest.layout().ty {
self.validate_operand(&dest.transmute(src.layout(), self)?,
M::enforce_validity_recursively(self, src.layout()), true)?;
}
self.validate_operand(&dest,
M::enforce_validity_recursively(self, dest.layout()),
true)?;
}
interp_ok(())
}
}
}#[instrument(skip(self), level = "trace")]839fn copy_op_inner(
840&mut self,
841 src: &impl Projectable<'tcx, M::Provenance>,
842 dest: &impl Writeable<'tcx, M::Provenance>,
843 allow_transmute: bool,
844 ) -> InterpResult<'tcx> {
845// These are technically *two* typed copies: `src` is a not-yet-loaded value,
846 // so we're doing a typed copy at `src` type from there to some intermediate storage.
847 // And then we're doing a second typed copy from that intermediate storage to `dest`.
848 // But as an optimization, we only make a single direct copy here.
849850 // Do the actual copy.
851self.copy_op_no_validate(src, dest, allow_transmute)?;
852853if M::enforce_validity(self, dest.layout()) {
854let dest = dest.to_place();
855// Given that there were two typed copies, we have to ensure this is valid at both types,
856 // and we have to ensure this loses provenance and padding according to both types.
857 // But if the types are identical, we only do one pass.
858if src.layout().ty != dest.layout().ty {
859self.validate_operand(
860&dest.transmute(src.layout(), self)?,
861 M::enforce_validity_recursively(self, src.layout()),
862/*reset_provenance_and_padding*/ true,
863 )?;
864 }
865self.validate_operand(
866&dest,
867 M::enforce_validity_recursively(self, dest.layout()),
868/*reset_provenance_and_padding*/ true,
869 )?;
870 }
871872 interp_ok(())
873 }
874875/// Copies the data from an operand to a place.
876 /// `allow_transmute` indicates whether the layouts may disagree.
877 /// Also, if you use this you are responsible for validating that things get copied at the
878 /// right type.
879#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("copy_op_no_validate",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(879u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&["src", "dest",
"allow_transmute"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&src)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dest)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&allow_transmute as
&dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: InterpResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let layout_compat =
mir_assign_valid_types(*self.tcx, self.typing_env,
src.layout(), dest.layout());
if !allow_transmute && !layout_compat {
::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("type mismatch when copying!\nsrc: {0},\ndest: {1}",
src.layout().ty, dest.layout().ty));
}
let src_has_padding =
match src.layout().backend_repr {
BackendRepr::Scalar(_) => false,
BackendRepr::ScalarPair(left, right) if
#[allow(non_exhaustive_omitted_patterns)] match src.layout().ty.kind()
{
ty::Ref(..) | ty::RawPtr(..) => true,
_ => false,
} => {
if true {
match (&(left.size(self) + right.size(self)),
&src.layout().size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};
false
}
BackendRepr::ScalarPair(left, right) => {
let left_size = left.size(self);
let right_size = right.size(self);
left_size + right_size != src.layout().size
}
BackendRepr::SimdVector { .. } |
BackendRepr::SimdScalableVector { .. } |
BackendRepr::Memory { .. } => true,
};
let src_val =
if src_has_padding {
src.to_op(self)?.as_mplace_or_imm()
} else { self.read_immediate_raw(src)? };
let src =
match src_val {
Right(src_val) => {
if !!src.layout().is_unsized() {
::core::panicking::panic("assertion failed: !src.layout().is_unsized()")
};
if !!dest.layout().is_unsized() {
::core::panicking::panic("assertion failed: !dest.layout().is_unsized()")
};
match (&src.layout().size, &dest.layout().size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
return if layout_compat {
self.write_immediate_no_validate(*src_val, dest)
} else {
let dest_mem = dest.force_mplace(self)?;
self.write_immediate_to_mplace_no_validate(*src_val,
src.layout(), dest_mem.mplace)
};
}
Left(mplace) => mplace,
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/place.rs:953",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(953u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("copy_op: {0:?} <- {1:?}: {2}",
*dest, src, dest.layout().ty) as &dyn Value))])
});
} else { ; }
};
let dest = dest.force_mplace(self)?;
let Some((dest_size, _)) =
self.size_and_align_of_val(&dest)? else {
::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("copy_op needs (dynamically) sized values"))
};
if true {
let src_size = self.size_and_align_of_val(&src)?.unwrap().0;
match (&src_size, &dest_size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("Cannot copy differently-sized data")));
}
}
};
} else {
match (&src.layout.size, &dest.layout.size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
}
self.mem_copy(src.ptr(), dest.ptr(), dest_size, true)?;
self.check_misalign(src.mplace.misaligned,
CheckAlignMsg::BasedOn)?;
self.check_misalign(dest.mplace.misaligned,
CheckAlignMsg::BasedOn)?;
interp_ok(())
}
}
}#[instrument(skip(self), level = "trace")]880pub(super) fn copy_op_no_validate(
881&mut self,
882 src: &impl Projectable<'tcx, M::Provenance>,
883 dest: &impl Writeable<'tcx, M::Provenance>,
884 allow_transmute: bool,
885 ) -> InterpResult<'tcx> {
886// We do NOT compare the types for equality, because well-typed code can
887 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
888let layout_compat =
889 mir_assign_valid_types(*self.tcx, self.typing_env, src.layout(), dest.layout());
890if !allow_transmute && !layout_compat {
891span_bug!(
892self.cur_span(),
893"type mismatch when copying!\nsrc: {},\ndest: {}",
894 src.layout().ty,
895 dest.layout().ty,
896 );
897 }
898// If the source has padding, we want to always do a mem-to-mem copy to ensure consistent
899 // padding in the target independent of layout choices.
900let src_has_padding = match src.layout().backend_repr {
901 BackendRepr::Scalar(_) => false,
902 BackendRepr::ScalarPair(left, right)
903if matches!(src.layout().ty.kind(), ty::Ref(..) | ty::RawPtr(..)) =>
904 {
905// Wide pointers never have padding, so we can avoid calling `size()`.
906debug_assert_eq!(left.size(self) + right.size(self), src.layout().size);
907false
908}
909 BackendRepr::ScalarPair(left, right) => {
910let left_size = left.size(self);
911let right_size = right.size(self);
912// We have padding if the sizes don't add up to the total.
913left_size + right_size != src.layout().size
914 }
915// Everything else can only exist in memory anyway, so it doesn't matter.
916BackendRepr::SimdVector { .. }
917 | BackendRepr::SimdScalableVector { .. }
918 | BackendRepr::Memory { .. } => true,
919 };
920921let src_val = if src_has_padding {
922// Do our best to get an mplace. If there's no mplace, then this is stored as an
923 // "optimized" local, so its padding is definitely uninitialized and we are fine.
924src.to_op(self)?.as_mplace_or_imm()
925 } else {
926// Do our best to get an immediate, to avoid having to force_allocate the destination.
927self.read_immediate_raw(src)?
928};
929let src = match src_val {
930 Right(src_val) => {
931assert!(!src.layout().is_unsized());
932assert!(!dest.layout().is_unsized());
933assert_eq!(src.layout().size, dest.layout().size);
934// Yay, we got a value that we can write directly.
935return if layout_compat {
936self.write_immediate_no_validate(*src_val, dest)
937 } else {
938// This is tricky. The problematic case is `ScalarPair`: the `src_val` was
939 // loaded using the offsets defined by `src.layout`. When we put this back into
940 // the destination, we have to use the same offsets! So (a) we make sure we
941 // write back to memory, and (b) we use `dest` *with the source layout*.
942let dest_mem = dest.force_mplace(self)?;
943self.write_immediate_to_mplace_no_validate(
944*src_val,
945 src.layout(),
946 dest_mem.mplace,
947 )
948 };
949 }
950 Left(mplace) => mplace,
951 };
952// Slow path, this does not fit into an immediate. Just memcpy.
953trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout().ty);
954955let dest = dest.force_mplace(self)?;
956let Some((dest_size, _)) = self.size_and_align_of_val(&dest)? else {
957span_bug!(self.cur_span(), "copy_op needs (dynamically) sized values")
958 };
959if cfg!(debug_assertions) {
960let src_size = self.size_and_align_of_val(&src)?.unwrap().0;
961assert_eq!(src_size, dest_size, "Cannot copy differently-sized data");
962 } else {
963// As a cheap approximation, we compare the fixed parts of the size.
964assert_eq!(src.layout.size, dest.layout.size);
965 }
966967// Setting `nonoverlapping` here only has an effect when we don't hit the fast-path above,
968 // but that should at least match what LLVM does where `memcpy` is also only used when the
969 // type does not have Scalar/ScalarPair layout.
970 // (Or as the `Assign` docs put it, assignments "not producing primitives" must be
971 // non-overlapping.)
972 // We check alignment separately, and *after* checking everything else.
973 // If an access is both OOB and misaligned, we want to see the bounds error.
974self.mem_copy(src.ptr(), dest.ptr(), dest_size, /*nonoverlapping*/ true)?;
975self.check_misalign(src.mplace.misaligned, CheckAlignMsg::BasedOn)?;
976self.check_misalign(dest.mplace.misaligned, CheckAlignMsg::BasedOn)?;
977 interp_ok(())
978 }
979980/// Ensures that a place is in memory, and returns where it is.
981 /// If the place currently refers to a local that doesn't yet have a matching allocation,
982 /// create such an allocation.
983 /// This is essentially `force_to_memplace`.
984#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("force_allocation",
"rustc_const_eval::interpret::place",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/place.rs"),
::tracing_core::__macro_support::Option::Some(984u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::place"),
::tracing_core::field::FieldSet::new(&["place"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> = loop {};
return __tracing_attr_fake_return;
}
{
let mplace =
match place.place {
Place::Local { local, offset, locals_addr } => {
if true {
match (&locals_addr, &self.frame().locals_addr()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};
let whole_local =
match self.frame_mut().locals[local].access_mut()? {
&mut Operand::Immediate(local_val) => {
let local_layout =
self.layout_of_local(&self.frame(), local, None)?;
if !local_layout.is_sized() {
{
::core::panicking::panic_fmt(format_args!("unsized locals cannot be immediate"));
}
};
let mplace =
self.allocate(local_layout, MemoryKind::Stack)?;
if !#[allow(non_exhaustive_omitted_patterns)] match local_val
{
Immediate::Uninit => true,
_ => false,
} {
self.write_immediate_to_mplace_no_validate(local_val,
local_layout, mplace.mplace)?;
}
M::after_local_moved_to_memory(self, local, &mplace)?;
*self.frame_mut().locals[local].access_mut().unwrap() =
Operand::Indirect(mplace.mplace);
mplace.mplace
}
&mut Operand::Indirect(mplace) => mplace,
};
if let Some(offset) = offset {
whole_local.offset_with_meta_(offset, OffsetMode::Wrapping,
MemPlaceMeta::None, self)?
} else { whole_local }
}
Place::Ptr(mplace) => mplace,
};
interp_ok(MPlaceTy { mplace, layout: place.layout })
}
}
}#[instrument(skip(self), level = "trace")]985pub fn force_allocation(
986&mut self,
987 place: &PlaceTy<'tcx, M::Provenance>,
988 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
989let mplace = match place.place {
990 Place::Local { local, offset, locals_addr } => {
991debug_assert_eq!(locals_addr, self.frame().locals_addr());
992let whole_local = match self.frame_mut().locals[local].access_mut()? {
993&mut Operand::Immediate(local_val) => {
994// We need to make an allocation.
995996 // We need the layout of the local. We can NOT use the layout we got,
997 // that might e.g., be an inner field of a struct with `Scalar` layout,
998 // that has different alignment than the outer field.
999let local_layout = self.layout_of_local(&self.frame(), local, None)?;
1000assert!(local_layout.is_sized(), "unsized locals cannot be immediate");
1001let mplace = self.allocate(local_layout, MemoryKind::Stack)?;
1002// Preserve old value. (As an optimization, we can skip this if it was uninit.)
1003if !matches!(local_val, Immediate::Uninit) {
1004// We don't have to validate as we can assume the local was already
1005 // valid for its type. We must not use any part of `place` here, that
1006 // could be a projection to a part of the local!
1007self.write_immediate_to_mplace_no_validate(
1008 local_val,
1009 local_layout,
1010 mplace.mplace,
1011 )?;
1012 }
1013 M::after_local_moved_to_memory(self, local, &mplace)?;
1014// Now we can call `access_mut` again, asserting it goes well, and actually
1015 // overwrite things. This points to the entire allocation, not just the part
1016 // the place refers to, i.e. we do this before we apply `offset`.
1017*self.frame_mut().locals[local].access_mut().unwrap() =
1018 Operand::Indirect(mplace.mplace);
1019 mplace.mplace
1020 }
1021&mut Operand::Indirect(mplace) => mplace, // this already was an indirect local
1022};
1023if let Some(offset) = offset {
1024// This offset is always inbounds, no need to check it again.
1025whole_local.offset_with_meta_(
1026 offset,
1027 OffsetMode::Wrapping,
1028 MemPlaceMeta::None,
1029self,
1030 )?
1031} else {
1032// Preserve wide place metadata, do not call `offset`.
1033whole_local
1034 }
1035 }
1036 Place::Ptr(mplace) => mplace,
1037 };
1038// Return with the original layout and align, so that the caller can go on
1039interp_ok(MPlaceTy { mplace, layout: place.layout })
1040 }
10411042pub fn allocate_dyn(
1043&mut self,
1044 layout: TyAndLayout<'tcx>,
1045 kind: MemoryKind<M::MemoryKind>,
1046 meta: MemPlaceMeta<M::Provenance>,
1047 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1048let Some((size, align)) = self.size_and_align_from_meta(&meta, &layout)? else {
1049::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("cannot allocate space for `extern` type, size is not known"))span_bug!(self.cur_span(), "cannot allocate space for `extern` type, size is not known")1050 };
1051let ptr = self.allocate_ptr(size, align, kind, AllocInit::Uninit)?;
1052interp_ok(self.ptr_with_meta_to_mplace(ptr.into(), meta, layout, /*unaligned*/ false))
1053 }
10541055pub fn allocate(
1056&mut self,
1057 layout: TyAndLayout<'tcx>,
1058 kind: MemoryKind<M::MemoryKind>,
1059 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1060if !layout.is_sized() {
::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
1061self.allocate_dyn(layout, kind, MemPlaceMeta::None)
1062 }
10631064/// Allocates a sequence of bytes in the interpreter's memory with alignment 1.
1065 /// This is allocated in immutable global memory and deduplicated.
1066pub fn allocate_bytes_dedup(
1067&mut self,
1068 bytes: &[u8],
1069 ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
1070let salt = M::get_global_alloc_salt(self, None);
1071let id = self.tcx.allocate_bytes_dedup(bytes, salt);
10721073// Turn untagged "global" pointers (obtained via `tcx`) into the machine pointer to the allocation.
1074M::adjust_alloc_root_pointer(
1075&self,
1076Pointer::from(id),
1077 M::GLOBAL_KIND.map(MemoryKind::Machine),
1078 )
1079 }
10801081/// Allocates a string in the interpreter's memory, returning it as a (wide) place.
1082 /// This is allocated in immutable global memory and deduplicated.
1083pub fn allocate_str_dedup(
1084&mut self,
1085 s: &str,
1086 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1087let bytes = s.as_bytes();
1088let ptr = self.allocate_bytes_dedup(bytes)?;
10891090// Create length metadata for the string.
1091let meta = Scalar::from_target_usize(u64::try_from(bytes.len()).unwrap(), self);
10921093// Get layout for Rust's str type.
1094let layout = self.layout_of(self.tcx.types.str_).unwrap();
10951096// Combine pointer and metadata into a wide pointer.
1097interp_ok(self.ptr_with_meta_to_mplace(
1098ptr.into(),
1099 MemPlaceMeta::Meta(meta),
1100layout,
1101/*unaligned*/ false,
1102 ))
1103 }
11041105pub fn raw_const_to_mplace(
1106&self,
1107 raw: mir::ConstAlloc<'tcx>,
1108 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
1109// This must be an allocation in `tcx`
1110let _ = self.tcx.global_alloc(raw.alloc_id);
1111let ptr = self.global_root_pointer(Pointer::from(raw.alloc_id))?;
1112let layout = self.layout_of(raw.ty)?;
1113interp_ok(self.ptr_to_mplace(ptr.into(), layout))
1114 }
1115}
11161117// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
1118#[cfg(target_pointer_width = "64")]
1119mod size_asserts {
1120use rustc_data_structures::static_assert_size;
11211122use super::*;
1123// tidy-alphabetical-start
1124const _: [(); 64] = [(); ::std::mem::size_of::<MPlaceTy<'_>>()];static_assert_size!(MPlaceTy<'_>, 64);
1125const _: [(); 48] = [(); ::std::mem::size_of::<MemPlace>()];static_assert_size!(MemPlace, 48);
1126const _: [(); 24] = [(); ::std::mem::size_of::<MemPlaceMeta>()];static_assert_size!(MemPlaceMeta, 24);
1127const _: [(); 48] = [(); ::std::mem::size_of::<Place>()];static_assert_size!(Place, 48);
1128const _: [(); 64] = [(); ::std::mem::size_of::<PlaceTy<'_>>()];static_assert_size!(PlaceTy<'_>, 64);
1129// tidy-alphabetical-end
1130}