]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/projection.rs
Fix off by one error and add ui test.
[rust.git] / compiler / rustc_const_eval / src / interpret / projection.rs
1 //! This file implements "place projections"; basically a symmetric API for 3 types: MPlaceTy, OpTy, PlaceTy.
2 //!
3 //! OpTy and PlaceTy genrally work by "let's see if we are actually an MPlaceTy, and do something custom if not".
4 //! For PlaceTy, the custom thing is basically always to call `force_allocation` and then use the MPlaceTy logic anyway.
5 //! For OpTy, the custom thing on field pojections has to be pretty clever (since `Operand::Immediate` can have fields),
6 //! but for array/slice operations it only has to worry about `Operand::Uninit`. That makes the value part trivial,
7 //! but we still need to do bounds checking and adjust the layout. To not duplicate that with MPlaceTy, we actually
8 //! implement the logic on OpTy, and MPlaceTy calls that.
9
10 use std::hash::Hash;
11
12 use rustc_middle::mir;
13 use rustc_middle::ty;
14 use rustc_middle::ty::layout::LayoutOf;
15 use rustc_target::abi::{self, Abi, VariantIdx};
16
17 use super::{
18     ImmTy, Immediate, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy, PlaceTy,
19     Provenance, Scalar,
20 };
21
22 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
23 impl<'mir, 'tcx: 'mir, Tag, M> InterpCx<'mir, 'tcx, M>
24 where
25     Tag: Provenance + Eq + Hash + 'static,
26     M: Machine<'mir, 'tcx, PointerTag = Tag>,
27 {
28     //# Field access
29
30     /// Offset a pointer to project to a field of a struct/union. Unlike `place_field`, this is
31     /// always possible without allocating, so it can take `&self`. Also return the field's layout.
32     /// This supports both struct and array fields.
33     ///
34     /// This also works for arrays, but then the `usize` index type is restricting.
35     /// For indexing into arrays, use `mplace_index`.
36     pub fn mplace_field(
37         &self,
38         base: &MPlaceTy<'tcx, M::PointerTag>,
39         field: usize,
40     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
41         let offset = base.layout.fields.offset(field);
42         let field_layout = base.layout.field(self, field);
43
44         // Offset may need adjustment for unsized fields.
45         let (meta, offset) = if field_layout.is_unsized() {
46             // Re-use parent metadata to determine dynamic field layout.
47             // With custom DSTS, this *will* execute user-defined code, but the same
48             // happens at run-time so that's okay.
49             match self.size_and_align_of(&base.meta, &field_layout)? {
50                 Some((_, align)) => (base.meta, offset.align_to(align)),
51                 None => {
52                     // For unsized types with an extern type tail we perform no adjustments.
53                     // NOTE: keep this in sync with `PlaceRef::project_field` in the codegen backend.
54                     assert!(matches!(base.meta, MemPlaceMeta::None));
55                     (base.meta, offset)
56                 }
57             }
58         } else {
59             // base.meta could be present; we might be accessing a sized field of an unsized
60             // struct.
61             (MemPlaceMeta::None, offset)
62         };
63
64         // We do not look at `base.layout.align` nor `field_layout.align`, unlike
65         // codegen -- mostly to see if we can get away with that
66         base.offset_with_meta(offset, meta, field_layout, self)
67     }
68
69     /// Gets the place of a field inside the place, and also the field's type.
70     /// Just a convenience function, but used quite a bit.
71     /// This is the only projection that might have a side-effect: We cannot project
72     /// into the field of a local `ScalarPair`, we have to first allocate it.
73     pub fn place_field(
74         &mut self,
75         base: &PlaceTy<'tcx, M::PointerTag>,
76         field: usize,
77     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
78         // FIXME: We could try to be smarter and avoid allocation for fields that span the
79         // entire place.
80         let base = self.force_allocation(base)?;
81         Ok(self.mplace_field(&base, field)?.into())
82     }
83
84     pub fn operand_field(
85         &self,
86         base: &OpTy<'tcx, M::PointerTag>,
87         field: usize,
88     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
89         let base = match base.try_as_mplace() {
90             Ok(ref mplace) => {
91                 // We can reuse the mplace field computation logic for indirect operands.
92                 let field = self.mplace_field(mplace, field)?;
93                 return Ok(field.into());
94             }
95             Err(value) => value,
96         };
97
98         let field_layout = base.layout.field(self, field);
99         let offset = base.layout.fields.offset(field);
100         // This makes several assumptions about what layouts we will encounter; we match what
101         // codegen does as good as we can (see `extract_field` in `rustc_codegen_ssa/src/mir/operand.rs`).
102         let field_val: Immediate<_> = match (*base, base.layout.abi) {
103             // the field contains no information, can be left uninit
104             _ if field_layout.is_zst() => Immediate::Uninit,
105             // the field covers the entire type
106             _ if field_layout.size == base.layout.size => {
107                 assert!(match (base.layout.abi, field_layout.abi) {
108                     (Abi::Scalar(..), Abi::Scalar(..)) => true,
109                     (Abi::ScalarPair(..), Abi::ScalarPair(..)) => true,
110                     _ => false,
111                 });
112                 assert!(offset.bytes() == 0);
113                 *base
114             }
115             // extract fields from types with `ScalarPair` ABI
116             (Immediate::ScalarPair(a_val, b_val), Abi::ScalarPair(a, b)) => {
117                 assert!(matches!(field_layout.abi, Abi::Scalar(..)));
118                 Immediate::from(if offset.bytes() == 0 {
119                     debug_assert_eq!(field_layout.size, a.size(self));
120                     a_val
121                 } else {
122                     debug_assert_eq!(offset, a.size(self).align_to(b.align(self).abi));
123                     debug_assert_eq!(field_layout.size, b.size(self));
124                     b_val
125                 })
126             }
127             _ => span_bug!(
128                 self.cur_span(),
129                 "invalid field access on immediate {}, layout {:#?}",
130                 base,
131                 base.layout
132             ),
133         };
134
135         Ok(ImmTy::from_immediate(field_val, field_layout).into())
136     }
137
138     //# Downcasting
139
140     pub fn mplace_downcast(
141         &self,
142         base: &MPlaceTy<'tcx, M::PointerTag>,
143         variant: VariantIdx,
144     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
145         // Downcasts only change the layout.
146         // (In particular, no check about whether this is even the active variant -- that's by design,
147         // see https://github.com/rust-lang/rust/issues/93688#issuecomment-1032929496.)
148         assert!(!base.meta.has_meta());
149         let mut base = *base;
150         base.layout = base.layout.for_variant(self, variant);
151         Ok(base)
152     }
153
154     pub fn place_downcast(
155         &self,
156         base: &PlaceTy<'tcx, M::PointerTag>,
157         variant: VariantIdx,
158     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
159         // Downcast just changes the layout
160         let mut base = base.clone();
161         base.layout = base.layout.for_variant(self, variant);
162         Ok(base)
163     }
164
165     pub fn operand_downcast(
166         &self,
167         base: &OpTy<'tcx, M::PointerTag>,
168         variant: VariantIdx,
169     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
170         // Downcast just changes the layout
171         let mut base = base.clone();
172         base.layout = base.layout.for_variant(self, variant);
173         Ok(base)
174     }
175
176     //# Slice indexing
177
178     #[inline(always)]
179     pub fn operand_index(
180         &self,
181         base: &OpTy<'tcx, M::PointerTag>,
182         index: u64,
183     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
184         // Not using the layout method because we want to compute on u64
185         match base.layout.fields {
186             abi::FieldsShape::Array { stride, count: _ } => {
187                 // `count` is nonsense for slices, use the dynamic length instead.
188                 let len = base.len(self)?;
189                 if index >= len {
190                     // This can only be reached in ConstProp and non-rustc-MIR.
191                     throw_ub!(BoundsCheckFailed { len, index });
192                 }
193                 let offset = stride * index; // `Size` multiplication
194                 // All fields have the same layout.
195                 let field_layout = base.layout.field(self, 0);
196                 base.offset(offset, field_layout, self)
197             }
198             _ => span_bug!(
199                 self.cur_span(),
200                 "`mplace_index` called on non-array type {:?}",
201                 base.layout.ty
202             ),
203         }
204     }
205
206     // Iterates over all fields of an array. Much more efficient than doing the
207     // same by repeatedly calling `operand_index`.
208     pub fn operand_array_fields<'a>(
209         &self,
210         base: &'a OpTy<'tcx, Tag>,
211     ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, OpTy<'tcx, Tag>>> + 'a> {
212         let len = base.len(self)?; // also asserts that we have a type where this makes sense
213         let abi::FieldsShape::Array { stride, .. } = base.layout.fields else {
214             span_bug!(self.cur_span(), "operand_array_fields: expected an array layout");
215         };
216         let field_layout = base.layout.field(self, 0);
217         let dl = &self.tcx.data_layout;
218         // `Size` multiplication
219         Ok((0..len).map(move |i| base.offset(stride * i, field_layout, dl)))
220     }
221
222     /// Index into an array.
223     pub fn mplace_index(
224         &self,
225         base: &MPlaceTy<'tcx, M::PointerTag>,
226         index: u64,
227     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
228         Ok(self.operand_index(&base.into(), index)?.assert_mem_place())
229     }
230
231     pub fn place_index(
232         &mut self,
233         base: &PlaceTy<'tcx, M::PointerTag>,
234         index: u64,
235     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
236         // There's not a lot we can do here, since we cannot have a place to a part of a local. If
237         // we are accessing the only element of a 1-element array, it's still the entire local...
238         // that doesn't seem worth it.
239         let base = self.force_allocation(base)?;
240         Ok(self.mplace_index(&base, index)?.into())
241     }
242
243     //# ConstantIndex support
244
245     fn operand_constant_index(
246         &self,
247         base: &OpTy<'tcx, M::PointerTag>,
248         offset: u64,
249         min_length: u64,
250         from_end: bool,
251     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
252         let n = base.len(self)?;
253         if n < min_length {
254             // This can only be reached in ConstProp and non-rustc-MIR.
255             throw_ub!(BoundsCheckFailed { len: min_length, index: n });
256         }
257
258         let index = if from_end {
259             assert!(0 < offset && offset <= min_length);
260             n.checked_sub(offset).unwrap()
261         } else {
262             assert!(offset < min_length);
263             offset
264         };
265
266         self.operand_index(base, index)
267     }
268
269     fn place_constant_index(
270         &mut self,
271         base: &PlaceTy<'tcx, M::PointerTag>,
272         offset: u64,
273         min_length: u64,
274         from_end: bool,
275     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
276         let base = self.force_allocation(base)?;
277         Ok(self
278             .operand_constant_index(&base.into(), offset, min_length, from_end)?
279             .assert_mem_place()
280             .into())
281     }
282
283     //# Subslicing
284
285     fn operand_subslice(
286         &self,
287         base: &OpTy<'tcx, M::PointerTag>,
288         from: u64,
289         to: u64,
290         from_end: bool,
291     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
292         let len = base.len(self)?; // also asserts that we have a type where this makes sense
293         let actual_to = if from_end {
294             if from.checked_add(to).map_or(true, |to| to > len) {
295                 // This can only be reached in ConstProp and non-rustc-MIR.
296                 throw_ub!(BoundsCheckFailed { len: len, index: from.saturating_add(to) });
297             }
298             len.checked_sub(to).unwrap()
299         } else {
300             to
301         };
302
303         // Not using layout method because that works with usize, and does not work with slices
304         // (that have count 0 in their layout).
305         let from_offset = match base.layout.fields {
306             abi::FieldsShape::Array { stride, .. } => stride * from, // `Size` multiplication is checked
307             _ => {
308                 span_bug!(self.cur_span(), "unexpected layout of index access: {:#?}", base.layout)
309             }
310         };
311
312         // Compute meta and new layout
313         let inner_len = actual_to.checked_sub(from).unwrap();
314         let (meta, ty) = match base.layout.ty.kind() {
315             // It is not nice to match on the type, but that seems to be the only way to
316             // implement this.
317             ty::Array(inner, _) => (MemPlaceMeta::None, self.tcx.mk_array(*inner, inner_len)),
318             ty::Slice(..) => {
319                 let len = Scalar::from_machine_usize(inner_len, self);
320                 (MemPlaceMeta::Meta(len), base.layout.ty)
321             }
322             _ => {
323                 span_bug!(self.cur_span(), "cannot subslice non-array type: `{:?}`", base.layout.ty)
324             }
325         };
326         let layout = self.layout_of(ty)?;
327         base.offset_with_meta(from_offset, meta, layout, self)
328     }
329
330     pub fn place_subslice(
331         &mut self,
332         base: &PlaceTy<'tcx, M::PointerTag>,
333         from: u64,
334         to: u64,
335         from_end: bool,
336     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
337         let base = self.force_allocation(base)?;
338         Ok(self.operand_subslice(&base.into(), from, to, from_end)?.assert_mem_place().into())
339     }
340
341     //# Applying a general projection
342
343     /// Projects into a place.
344     #[instrument(skip(self), level = "trace")]
345     pub fn place_projection(
346         &mut self,
347         base: &PlaceTy<'tcx, M::PointerTag>,
348         proj_elem: mir::PlaceElem<'tcx>,
349     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
350         use rustc_middle::mir::ProjectionElem::*;
351         Ok(match proj_elem {
352             OpaqueCast(ty) => {
353                 let mut place = base.clone();
354                 place.layout = self.layout_of(ty)?;
355                 place
356             }
357             Field(field, _) => self.place_field(base, field.index())?,
358             Downcast(_, variant) => self.place_downcast(base, variant)?,
359             Deref => self.deref_operand(&self.place_to_op(base)?)?.into(),
360             Index(local) => {
361                 let layout = self.layout_of(self.tcx.types.usize)?;
362                 let n = self.local_to_op(self.frame(), local, Some(layout))?;
363                 let n = self.read_scalar(&n)?.to_machine_usize(self)?;
364                 self.place_index(base, n)?
365             }
366             ConstantIndex { offset, min_length, from_end } => {
367                 self.place_constant_index(base, offset, min_length, from_end)?
368             }
369             Subslice { from, to, from_end } => self.place_subslice(base, from, to, from_end)?,
370         })
371     }
372
373     #[instrument(skip(self), level = "trace")]
374     pub fn operand_projection(
375         &self,
376         base: &OpTy<'tcx, M::PointerTag>,
377         proj_elem: mir::PlaceElem<'tcx>,
378     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
379         use rustc_middle::mir::ProjectionElem::*;
380         Ok(match proj_elem {
381             OpaqueCast(ty) => {
382                 let mut op = base.clone();
383                 op.layout = self.layout_of(ty)?;
384                 op
385             }
386             Field(field, _) => self.operand_field(base, field.index())?,
387             Downcast(_, variant) => self.operand_downcast(base, variant)?,
388             Deref => self.deref_operand(base)?.into(),
389             Index(local) => {
390                 let layout = self.layout_of(self.tcx.types.usize)?;
391                 let n = self.local_to_op(self.frame(), local, Some(layout))?;
392                 let n = self.read_scalar(&n)?.to_machine_usize(self)?;
393                 self.operand_index(base, n)?
394             }
395             ConstantIndex { offset, min_length, from_end } => {
396                 self.operand_constant_index(base, offset, min_length, from_end)?
397             }
398             Subslice { from, to, from_end } => self.operand_subslice(base, from, to, from_end)?,
399         })
400     }
401 }