]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/operand.rs
Stop passing the self-type as a separate argument.
[rust.git] / compiler / rustc_const_eval / src / interpret / operand.rs
1 //! Functions concerning immediate values and operands, and reading from operands.
2 //! All high-level functions to read from memory work on operands as sources.
3
4 use either::{Either, Left, Right};
5
6 use rustc_hir::def::Namespace;
7 use rustc_middle::ty::layout::{LayoutOf, PrimitiveExt, TyAndLayout};
8 use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter};
9 use rustc_middle::ty::{ConstInt, Ty, ValTree};
10 use rustc_middle::{mir, ty};
11 use rustc_span::Span;
12 use rustc_target::abi::{self, Abi, Align, HasDataLayout, Size, TagEncoding};
13 use rustc_target::abi::{VariantIdx, Variants};
14
15 use super::{
16     alloc_range, from_known_layout, mir_assign_valid_types, AllocId, ConstValue, Frame, GlobalId,
17     InterpCx, InterpResult, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Place, PlaceTy, Pointer,
18     Provenance, Scalar,
19 };
20
21 /// An `Immediate` represents a single immediate self-contained Rust value.
22 ///
23 /// For optimization of a few very common cases, there is also a representation for a pair of
24 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
25 /// operations and wide pointers. This idea was taken from rustc's codegen.
26 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
27 /// defined on `Immediate`, and do not have to work with a `Place`.
28 #[derive(Copy, Clone, Debug)]
29 pub enum Immediate<Prov: Provenance = AllocId> {
30     /// A single scalar value (must have *initialized* `Scalar` ABI).
31     Scalar(Scalar<Prov>),
32     /// A pair of two scalar value (must have `ScalarPair` ABI where both fields are
33     /// `Scalar::Initialized`).
34     ScalarPair(Scalar<Prov>, Scalar<Prov>),
35     /// A value of fully uninitialized memory. Can have and size and layout.
36     Uninit,
37 }
38
39 impl<Prov: Provenance> From<Scalar<Prov>> for Immediate<Prov> {
40     #[inline(always)]
41     fn from(val: Scalar<Prov>) -> Self {
42         Immediate::Scalar(val.into())
43     }
44 }
45
46 impl<Prov: Provenance> Immediate<Prov> {
47     pub fn from_pointer(p: Pointer<Prov>, cx: &impl HasDataLayout) -> Self {
48         Immediate::Scalar(Scalar::from_pointer(p, cx))
49     }
50
51     pub fn from_maybe_pointer(p: Pointer<Option<Prov>>, cx: &impl HasDataLayout) -> Self {
52         Immediate::Scalar(Scalar::from_maybe_pointer(p, cx))
53     }
54
55     pub fn new_slice(val: Scalar<Prov>, len: u64, cx: &impl HasDataLayout) -> Self {
56         Immediate::ScalarPair(val.into(), Scalar::from_machine_usize(len, cx).into())
57     }
58
59     pub fn new_dyn_trait(
60         val: Scalar<Prov>,
61         vtable: Pointer<Option<Prov>>,
62         cx: &impl HasDataLayout,
63     ) -> Self {
64         Immediate::ScalarPair(val.into(), Scalar::from_maybe_pointer(vtable, cx))
65     }
66
67     #[inline]
68     #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
69     pub fn to_scalar(self) -> Scalar<Prov> {
70         match self {
71             Immediate::Scalar(val) => val,
72             Immediate::ScalarPair(..) => bug!("Got a scalar pair where a scalar was expected"),
73             Immediate::Uninit => bug!("Got uninit where a scalar was expected"),
74         }
75     }
76
77     #[inline]
78     #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
79     pub fn to_scalar_pair(self) -> (Scalar<Prov>, Scalar<Prov>) {
80         match self {
81             Immediate::ScalarPair(val1, val2) => (val1, val2),
82             Immediate::Scalar(..) => bug!("Got a scalar where a scalar pair was expected"),
83             Immediate::Uninit => bug!("Got uninit where a scalar pair was expected"),
84         }
85     }
86 }
87
88 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
89 // as input for binary and cast operations.
90 #[derive(Clone, Debug)]
91 pub struct ImmTy<'tcx, Prov: Provenance = AllocId> {
92     imm: Immediate<Prov>,
93     pub layout: TyAndLayout<'tcx>,
94 }
95
96 impl<Prov: Provenance> std::fmt::Display for ImmTy<'_, Prov> {
97     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98         /// Helper function for printing a scalar to a FmtPrinter
99         fn p<'a, 'tcx, Prov: Provenance>(
100             cx: FmtPrinter<'a, 'tcx>,
101             s: Scalar<Prov>,
102             ty: Ty<'tcx>,
103         ) -> Result<FmtPrinter<'a, 'tcx>, std::fmt::Error> {
104             match s {
105                 Scalar::Int(int) => cx.pretty_print_const_scalar_int(int, ty, true),
106                 Scalar::Ptr(ptr, _sz) => {
107                     // Just print the ptr value. `pretty_print_const_scalar_ptr` would also try to
108                     // print what is points to, which would fail since it has no access to the local
109                     // memory.
110                     cx.pretty_print_const_pointer(ptr, ty, true)
111                 }
112             }
113         }
114         ty::tls::with(|tcx| {
115             match self.imm {
116                 Immediate::Scalar(s) => {
117                     if let Some(ty) = tcx.lift(self.layout.ty) {
118                         let cx = FmtPrinter::new(tcx, Namespace::ValueNS);
119                         f.write_str(&p(cx, s, ty)?.into_buffer())?;
120                         return Ok(());
121                     }
122                     write!(f, "{:x}: {}", s, self.layout.ty)
123                 }
124                 Immediate::ScalarPair(a, b) => {
125                     // FIXME(oli-obk): at least print tuples and slices nicely
126                     write!(f, "({:x}, {:x}): {}", a, b, self.layout.ty)
127                 }
128                 Immediate::Uninit => {
129                     write!(f, "uninit: {}", self.layout.ty)
130                 }
131             }
132         })
133     }
134 }
135
136 impl<'tcx, Prov: Provenance> std::ops::Deref for ImmTy<'tcx, Prov> {
137     type Target = Immediate<Prov>;
138     #[inline(always)]
139     fn deref(&self) -> &Immediate<Prov> {
140         &self.imm
141     }
142 }
143
144 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
145 /// or still in memory. The latter is an optimization, to delay reading that chunk of
146 /// memory and to avoid having to store arbitrary-sized data here.
147 #[derive(Copy, Clone, Debug)]
148 pub enum Operand<Prov: Provenance = AllocId> {
149     Immediate(Immediate<Prov>),
150     Indirect(MemPlace<Prov>),
151 }
152
153 #[derive(Clone, Debug)]
154 pub struct OpTy<'tcx, Prov: Provenance = AllocId> {
155     op: Operand<Prov>, // Keep this private; it helps enforce invariants.
156     pub layout: TyAndLayout<'tcx>,
157     /// rustc does not have a proper way to represent the type of a field of a `repr(packed)` struct:
158     /// it needs to have a different alignment than the field type would usually have.
159     /// So we represent this here with a separate field that "overwrites" `layout.align`.
160     /// This means `layout.align` should never be used for an `OpTy`!
161     /// `None` means "alignment does not matter since this is a by-value operand"
162     /// (`Operand::Immediate`); this field is only relevant for `Operand::Indirect`.
163     /// Also CTFE ignores alignment anyway, so this is for Miri only.
164     pub align: Option<Align>,
165 }
166
167 impl<'tcx, Prov: Provenance> std::ops::Deref for OpTy<'tcx, Prov> {
168     type Target = Operand<Prov>;
169     #[inline(always)]
170     fn deref(&self) -> &Operand<Prov> {
171         &self.op
172     }
173 }
174
175 impl<'tcx, Prov: Provenance> From<MPlaceTy<'tcx, Prov>> for OpTy<'tcx, Prov> {
176     #[inline(always)]
177     fn from(mplace: MPlaceTy<'tcx, Prov>) -> Self {
178         OpTy { op: Operand::Indirect(*mplace), layout: mplace.layout, align: Some(mplace.align) }
179     }
180 }
181
182 impl<'tcx, Prov: Provenance> From<&'_ MPlaceTy<'tcx, Prov>> for OpTy<'tcx, Prov> {
183     #[inline(always)]
184     fn from(mplace: &MPlaceTy<'tcx, Prov>) -> Self {
185         OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout, align: Some(mplace.align) }
186     }
187 }
188
189 impl<'tcx, Prov: Provenance> From<&'_ mut MPlaceTy<'tcx, Prov>> for OpTy<'tcx, Prov> {
190     #[inline(always)]
191     fn from(mplace: &mut MPlaceTy<'tcx, Prov>) -> Self {
192         OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout, align: Some(mplace.align) }
193     }
194 }
195
196 impl<'tcx, Prov: Provenance> From<ImmTy<'tcx, Prov>> for OpTy<'tcx, Prov> {
197     #[inline(always)]
198     fn from(val: ImmTy<'tcx, Prov>) -> Self {
199         OpTy { op: Operand::Immediate(val.imm), layout: val.layout, align: None }
200     }
201 }
202
203 impl<'tcx, Prov: Provenance> ImmTy<'tcx, Prov> {
204     #[inline]
205     pub fn from_scalar(val: Scalar<Prov>, layout: TyAndLayout<'tcx>) -> Self {
206         ImmTy { imm: val.into(), layout }
207     }
208
209     #[inline]
210     pub fn from_immediate(imm: Immediate<Prov>, layout: TyAndLayout<'tcx>) -> Self {
211         ImmTy { imm, layout }
212     }
213
214     #[inline]
215     pub fn uninit(layout: TyAndLayout<'tcx>) -> Self {
216         ImmTy { imm: Immediate::Uninit, layout }
217     }
218
219     #[inline]
220     pub fn try_from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
221         Some(Self::from_scalar(Scalar::try_from_uint(i, layout.size)?, layout))
222     }
223     #[inline]
224     pub fn from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Self {
225         Self::from_scalar(Scalar::from_uint(i, layout.size), layout)
226     }
227
228     #[inline]
229     pub fn try_from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
230         Some(Self::from_scalar(Scalar::try_from_int(i, layout.size)?, layout))
231     }
232
233     #[inline]
234     pub fn from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Self {
235         Self::from_scalar(Scalar::from_int(i, layout.size), layout)
236     }
237
238     #[inline]
239     pub fn to_const_int(self) -> ConstInt {
240         assert!(self.layout.ty.is_integral());
241         let int = self.to_scalar().assert_int();
242         ConstInt::new(int, self.layout.ty.is_signed(), self.layout.ty.is_ptr_sized_integral())
243     }
244 }
245
246 impl<'tcx, Prov: Provenance> OpTy<'tcx, Prov> {
247     pub fn len(&self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
248         if self.layout.is_unsized() {
249             // There are no unsized immediates.
250             self.assert_mem_place().len(cx)
251         } else {
252             match self.layout.fields {
253                 abi::FieldsShape::Array { count, .. } => Ok(count),
254                 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
255             }
256         }
257     }
258
259     pub fn offset_with_meta(
260         &self,
261         offset: Size,
262         meta: MemPlaceMeta<Prov>,
263         layout: TyAndLayout<'tcx>,
264         cx: &impl HasDataLayout,
265     ) -> InterpResult<'tcx, Self> {
266         match self.as_mplace_or_imm() {
267             Left(mplace) => Ok(mplace.offset_with_meta(offset, meta, layout, cx)?.into()),
268             Right(imm) => {
269                 assert!(
270                     matches!(*imm, Immediate::Uninit),
271                     "Scalar/ScalarPair cannot be offset into"
272                 );
273                 assert!(!meta.has_meta()); // no place to store metadata here
274                 // Every part of an uninit is uninit.
275                 Ok(ImmTy::uninit(layout).into())
276             }
277         }
278     }
279
280     pub fn offset(
281         &self,
282         offset: Size,
283         layout: TyAndLayout<'tcx>,
284         cx: &impl HasDataLayout,
285     ) -> InterpResult<'tcx, Self> {
286         assert!(layout.is_sized());
287         self.offset_with_meta(offset, MemPlaceMeta::None, layout, cx)
288     }
289 }
290
291 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
292     /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
293     /// Returns `None` if the layout does not permit loading this as a value.
294     ///
295     /// This is an internal function; call `read_immediate` instead.
296     fn read_immediate_from_mplace_raw(
297         &self,
298         mplace: &MPlaceTy<'tcx, M::Provenance>,
299     ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::Provenance>>> {
300         if mplace.layout.is_unsized() {
301             // Don't touch unsized
302             return Ok(None);
303         }
304
305         let Some(alloc) = self.get_place_alloc(mplace)? else {
306             // zero-sized type can be left uninit
307             return Ok(Some(ImmTy::uninit(mplace.layout)));
308         };
309
310         // It may seem like all types with `Scalar` or `ScalarPair` ABI are fair game at this point.
311         // However, `MaybeUninit<u64>` is considered a `Scalar` as far as its layout is concerned --
312         // and yet cannot be represented by an interpreter `Scalar`, since we have to handle the
313         // case where some of the bytes are initialized and others are not. So, we need an extra
314         // check that walks over the type of `mplace` to make sure it is truly correct to treat this
315         // like a `Scalar` (or `ScalarPair`).
316         Ok(match mplace.layout.abi {
317             Abi::Scalar(abi::Scalar::Initialized { value: s, .. }) => {
318                 let size = s.size(self);
319                 assert_eq!(size, mplace.layout.size, "abi::Scalar size does not match layout size");
320                 let scalar = alloc.read_scalar(
321                     alloc_range(Size::ZERO, size),
322                     /*read_provenance*/ s.is_ptr(),
323                 )?;
324                 Some(ImmTy { imm: scalar.into(), layout: mplace.layout })
325             }
326             Abi::ScalarPair(
327                 abi::Scalar::Initialized { value: a, .. },
328                 abi::Scalar::Initialized { value: b, .. },
329             ) => {
330                 // We checked `ptr_align` above, so all fields will have the alignment they need.
331                 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
332                 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
333                 let (a_size, b_size) = (a.size(self), b.size(self));
334                 let b_offset = a_size.align_to(b.align(self).abi);
335                 assert!(b_offset.bytes() > 0); // in `operand_field` we use the offset to tell apart the fields
336                 let a_val = alloc.read_scalar(
337                     alloc_range(Size::ZERO, a_size),
338                     /*read_provenance*/ a.is_ptr(),
339                 )?;
340                 let b_val = alloc.read_scalar(
341                     alloc_range(b_offset, b_size),
342                     /*read_provenance*/ b.is_ptr(),
343                 )?;
344                 Some(ImmTy {
345                     imm: Immediate::ScalarPair(a_val.into(), b_val.into()),
346                     layout: mplace.layout,
347                 })
348             }
349             _ => {
350                 // Neither a scalar nor scalar pair.
351                 None
352             }
353         })
354     }
355
356     /// Try returning an immediate for the operand. If the layout does not permit loading this as an
357     /// immediate, return where in memory we can find the data.
358     /// Note that for a given layout, this operation will either always return Left or Right!
359     /// succeed!  Whether it returns Left depends on whether the layout can be represented
360     /// in an `Immediate`, not on which data is stored there currently.
361     ///
362     /// This is an internal function that should not usually be used; call `read_immediate` instead.
363     /// ConstProp needs it, though.
364     pub fn read_immediate_raw(
365         &self,
366         src: &OpTy<'tcx, M::Provenance>,
367     ) -> InterpResult<'tcx, Either<MPlaceTy<'tcx, M::Provenance>, ImmTy<'tcx, M::Provenance>>> {
368         Ok(match src.as_mplace_or_imm() {
369             Left(ref mplace) => {
370                 if let Some(val) = self.read_immediate_from_mplace_raw(mplace)? {
371                     Right(val)
372                 } else {
373                     Left(*mplace)
374                 }
375             }
376             Right(val) => Right(val),
377         })
378     }
379
380     /// Read an immediate from a place, asserting that that is possible with the given layout.
381     ///
382     /// If this succeeds, the `ImmTy` is never `Uninit`.
383     #[inline(always)]
384     pub fn read_immediate(
385         &self,
386         op: &OpTy<'tcx, M::Provenance>,
387     ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
388         if !matches!(
389             op.layout.abi,
390             Abi::Scalar(abi::Scalar::Initialized { .. })
391                 | Abi::ScalarPair(abi::Scalar::Initialized { .. }, abi::Scalar::Initialized { .. })
392         ) {
393             span_bug!(self.cur_span(), "primitive read not possible for type: {:?}", op.layout.ty);
394         }
395         let imm = self.read_immediate_raw(op)?.right().unwrap();
396         if matches!(*imm, Immediate::Uninit) {
397             throw_ub!(InvalidUninitBytes(None));
398         }
399         Ok(imm)
400     }
401
402     /// Read a scalar from a place
403     pub fn read_scalar(
404         &self,
405         op: &OpTy<'tcx, M::Provenance>,
406     ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
407         Ok(self.read_immediate(op)?.to_scalar())
408     }
409
410     /// Read a pointer from a place.
411     pub fn read_pointer(
412         &self,
413         op: &OpTy<'tcx, M::Provenance>,
414     ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
415         self.read_scalar(op)?.to_pointer(self)
416     }
417
418     /// Turn the wide MPlace into a string (must already be dereferenced!)
419     pub fn read_str(&self, mplace: &MPlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx, &str> {
420         let len = mplace.len(self)?;
421         let bytes = self.read_bytes_ptr_strip_provenance(mplace.ptr, Size::from_bytes(len))?;
422         let str = std::str::from_utf8(bytes).map_err(|err| err_ub!(InvalidStr(err)))?;
423         Ok(str)
424     }
425
426     /// Converts a repr(simd) operand into an operand where `place_index` accesses the SIMD elements.
427     /// Also returns the number of elements.
428     ///
429     /// Can (but does not always) trigger UB if `op` is uninitialized.
430     pub fn operand_to_simd(
431         &self,
432         op: &OpTy<'tcx, M::Provenance>,
433     ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, u64)> {
434         // Basically we just transmute this place into an array following simd_size_and_type.
435         // This only works in memory, but repr(simd) types should never be immediates anyway.
436         assert!(op.layout.ty.is_simd());
437         match op.as_mplace_or_imm() {
438             Left(mplace) => self.mplace_to_simd(&mplace),
439             Right(imm) => match *imm {
440                 Immediate::Uninit => {
441                     throw_ub!(InvalidUninitBytes(None))
442                 }
443                 Immediate::Scalar(..) | Immediate::ScalarPair(..) => {
444                     bug!("arrays/slices can never have Scalar/ScalarPair layout")
445                 }
446             },
447         }
448     }
449
450     /// Read from a local.
451     /// Will not access memory, instead an indirect `Operand` is returned.
452     ///
453     /// This is public because it is used by [priroda](https://github.com/oli-obk/priroda) to get an
454     /// OpTy from a local.
455     pub fn local_to_op(
456         &self,
457         frame: &Frame<'mir, 'tcx, M::Provenance, M::FrameExtra>,
458         local: mir::Local,
459         layout: Option<TyAndLayout<'tcx>>,
460     ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
461         let layout = self.layout_of_local(frame, local, layout)?;
462         let op = *frame.locals[local].access()?;
463         Ok(OpTy { op, layout, align: Some(layout.align.abi) })
464     }
465
466     /// Every place can be read from, so we can turn them into an operand.
467     /// This will definitely return `Indirect` if the place is a `Ptr`, i.e., this
468     /// will never actually read from memory.
469     #[inline(always)]
470     pub fn place_to_op(
471         &self,
472         place: &PlaceTy<'tcx, M::Provenance>,
473     ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
474         let op = match **place {
475             Place::Ptr(mplace) => Operand::Indirect(mplace),
476             Place::Local { frame, local } => {
477                 *self.local_to_op(&self.stack()[frame], local, None)?
478             }
479         };
480         Ok(OpTy { op, layout: place.layout, align: Some(place.align) })
481     }
482
483     /// Evaluate a place with the goal of reading from it.  This lets us sometimes
484     /// avoid allocations.
485     pub fn eval_place_to_op(
486         &self,
487         mir_place: mir::Place<'tcx>,
488         layout: Option<TyAndLayout<'tcx>>,
489     ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
490         // Do not use the layout passed in as argument if the base we are looking at
491         // here is not the entire place.
492         let layout = if mir_place.projection.is_empty() { layout } else { None };
493
494         let mut op = self.local_to_op(self.frame(), mir_place.local, layout)?;
495         // Using `try_fold` turned out to be bad for performance, hence the loop.
496         for elem in mir_place.projection.iter() {
497             op = self.operand_projection(&op, elem)?
498         }
499
500         trace!("eval_place_to_op: got {:?}", *op);
501         // Sanity-check the type we ended up with.
502         debug_assert!(
503             mir_assign_valid_types(
504                 *self.tcx,
505                 self.param_env,
506                 self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
507                     mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty
508                 )?)?,
509                 op.layout,
510             ),
511             "eval_place of a MIR place with type {:?} produced an interpreter operand with type {:?}",
512             mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty,
513             op.layout.ty,
514         );
515         Ok(op)
516     }
517
518     /// Evaluate the operand, returning a place where you can then find the data.
519     /// If you already know the layout, you can save two table lookups
520     /// by passing it in here.
521     #[inline]
522     pub fn eval_operand(
523         &self,
524         mir_op: &mir::Operand<'tcx>,
525         layout: Option<TyAndLayout<'tcx>>,
526     ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
527         use rustc_middle::mir::Operand::*;
528         let op = match *mir_op {
529             // FIXME: do some more logic on `move` to invalidate the old location
530             Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?,
531
532             Constant(ref constant) => {
533                 let c =
534                     self.subst_from_current_frame_and_normalize_erasing_regions(constant.literal)?;
535
536                 // This can still fail:
537                 // * During ConstProp, with `TooGeneric` or since the `required_consts` were not all
538                 //   checked yet.
539                 // * During CTFE, since promoteds in `const`/`static` initializer bodies can fail.
540                 self.eval_mir_constant(&c, Some(constant.span), layout)?
541             }
542         };
543         trace!("{:?}: {:?}", mir_op, *op);
544         Ok(op)
545     }
546
547     /// Evaluate a bunch of operands at once
548     pub(super) fn eval_operands(
549         &self,
550         ops: &[mir::Operand<'tcx>],
551     ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::Provenance>>> {
552         ops.iter().map(|op| self.eval_operand(op, None)).collect()
553     }
554
555     fn eval_ty_constant(
556         &self,
557         val: ty::Const<'tcx>,
558         span: Option<Span>,
559     ) -> InterpResult<'tcx, ValTree<'tcx>> {
560         Ok(match val.kind() {
561             ty::ConstKind::Param(_) | ty::ConstKind::Placeholder(..) => {
562                 throw_inval!(TooGeneric)
563             }
564             ty::ConstKind::Error(reported) => {
565                 throw_inval!(AlreadyReported(reported))
566             }
567             ty::ConstKind::Unevaluated(uv) => {
568                 let instance = self.resolve(uv.def, uv.substs)?;
569                 let cid = GlobalId { instance, promoted: None };
570                 self.ctfe_query(span, |tcx| tcx.eval_to_valtree(self.param_env.and(cid)))?
571                     .unwrap_or_else(|| bug!("unable to create ValTree for {uv:?}"))
572             }
573             ty::ConstKind::Bound(..) | ty::ConstKind::Infer(..) => {
574                 span_bug!(self.cur_span(), "unexpected ConstKind in ctfe: {val:?}")
575             }
576             ty::ConstKind::Value(valtree) => valtree,
577         })
578     }
579
580     pub fn eval_mir_constant(
581         &self,
582         val: &mir::ConstantKind<'tcx>,
583         span: Option<Span>,
584         layout: Option<TyAndLayout<'tcx>>,
585     ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
586         // FIXME(const_prop): normalization needed b/c const prop lint in
587         // `mir_drops_elaborated_and_const_checked`, which happens before
588         // optimized MIR. Only after optimizing the MIR can we guarantee
589         // that the `RevealAll` pass has happened and that the body's consts
590         // are normalized, so any call to resolve before that needs to be
591         // manually normalized.
592         let val = self.tcx.normalize_erasing_regions(self.param_env, *val);
593         match val {
594             mir::ConstantKind::Ty(ct) => {
595                 let ty = ct.ty();
596                 let valtree = self.eval_ty_constant(ct, span)?;
597                 let const_val = self.tcx.valtree_to_const_val((ty, valtree));
598                 self.const_val_to_op(const_val, ty, layout)
599             }
600             mir::ConstantKind::Val(val, ty) => self.const_val_to_op(val, ty, layout),
601             mir::ConstantKind::Unevaluated(uv, _) => {
602                 let instance = self.resolve(uv.def, uv.substs)?;
603                 Ok(self.eval_global(GlobalId { instance, promoted: uv.promoted }, span)?.into())
604             }
605         }
606     }
607
608     pub(super) fn const_val_to_op(
609         &self,
610         val_val: ConstValue<'tcx>,
611         ty: Ty<'tcx>,
612         layout: Option<TyAndLayout<'tcx>>,
613     ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
614         // Other cases need layout.
615         let adjust_scalar = |scalar| -> InterpResult<'tcx, _> {
616             Ok(match scalar {
617                 Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size),
618                 Scalar::Int(int) => Scalar::Int(int),
619             })
620         };
621         let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?;
622         let op = match val_val {
623             ConstValue::ByRef { alloc, offset } => {
624                 let id = self.tcx.create_memory_alloc(alloc);
625                 // We rely on mutability being set correctly in that allocation to prevent writes
626                 // where none should happen.
627                 let ptr = self.global_base_pointer(Pointer::new(id, offset))?;
628                 Operand::Indirect(MemPlace::from_ptr(ptr.into()))
629             }
630             ConstValue::Scalar(x) => Operand::Immediate(adjust_scalar(x)?.into()),
631             ConstValue::ZeroSized => Operand::Immediate(Immediate::Uninit),
632             ConstValue::Slice { data, start, end } => {
633                 // We rely on mutability being set correctly in `data` to prevent writes
634                 // where none should happen.
635                 let ptr = Pointer::new(
636                     self.tcx.create_memory_alloc(data),
637                     Size::from_bytes(start), // offset: `start`
638                 );
639                 Operand::Immediate(Immediate::new_slice(
640                     Scalar::from_pointer(self.global_base_pointer(ptr)?, &*self.tcx),
641                     u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start`
642                     self,
643                 ))
644             }
645         };
646         Ok(OpTy { op, layout, align: Some(layout.align.abi) })
647     }
648
649     /// Read discriminant, return the runtime value as well as the variant index.
650     /// Can also legally be called on non-enums (e.g. through the discriminant_value intrinsic)!
651     pub fn read_discriminant(
652         &self,
653         op: &OpTy<'tcx, M::Provenance>,
654     ) -> InterpResult<'tcx, (Scalar<M::Provenance>, VariantIdx)> {
655         trace!("read_discriminant_value {:#?}", op.layout);
656         // Get type and layout of the discriminant.
657         let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(*self.tcx))?;
658         trace!("discriminant type: {:?}", discr_layout.ty);
659
660         // We use "discriminant" to refer to the value associated with a particular enum variant.
661         // This is not to be confused with its "variant index", which is just determining its position in the
662         // declared list of variants -- they can differ with explicitly assigned discriminants.
663         // We use "tag" to refer to how the discriminant is encoded in memory, which can be either
664         // straight-forward (`TagEncoding::Direct`) or with a niche (`TagEncoding::Niche`).
665         let (tag_scalar_layout, tag_encoding, tag_field) = match op.layout.variants {
666             Variants::Single { index } => {
667                 let discr = match op.layout.ty.discriminant_for_variant(*self.tcx, index) {
668                     Some(discr) => {
669                         // This type actually has discriminants.
670                         assert_eq!(discr.ty, discr_layout.ty);
671                         Scalar::from_uint(discr.val, discr_layout.size)
672                     }
673                     None => {
674                         // On a type without actual discriminants, variant is 0.
675                         assert_eq!(index.as_u32(), 0);
676                         Scalar::from_uint(index.as_u32(), discr_layout.size)
677                     }
678                 };
679                 return Ok((discr, index));
680             }
681             Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => {
682                 (tag, tag_encoding, tag_field)
683             }
684         };
685
686         // There are *three* layouts that come into play here:
687         // - The discriminant has a type for typechecking. This is `discr_layout`, and is used for
688         //   the `Scalar` we return.
689         // - The tag (encoded discriminant) has layout `tag_layout`. This is always an integer type,
690         //   and used to interpret the value we read from the tag field.
691         //   For the return value, a cast to `discr_layout` is performed.
692         // - The field storing the tag has a layout, which is very similar to `tag_layout` but
693         //   may be a pointer. This is `tag_val.layout`; we just use it for sanity checks.
694
695         // Get layout for tag.
696         let tag_layout = self.layout_of(tag_scalar_layout.primitive().to_int_ty(*self.tcx))?;
697
698         // Read tag and sanity-check `tag_layout`.
699         let tag_val = self.read_immediate(&self.operand_field(op, tag_field)?)?;
700         assert_eq!(tag_layout.size, tag_val.layout.size);
701         assert_eq!(tag_layout.abi.is_signed(), tag_val.layout.abi.is_signed());
702         trace!("tag value: {}", tag_val);
703
704         // Figure out which discriminant and variant this corresponds to.
705         Ok(match *tag_encoding {
706             TagEncoding::Direct => {
707                 let scalar = tag_val.to_scalar();
708                 // Generate a specific error if `tag_val` is not an integer.
709                 // (`tag_bits` itself is only used for error messages below.)
710                 let tag_bits = scalar
711                     .try_to_int()
712                     .map_err(|dbg_val| err_ub!(InvalidTag(dbg_val)))?
713                     .assert_bits(tag_layout.size);
714                 // Cast bits from tag layout to discriminant layout.
715                 // After the checks we did above, this cannot fail, as
716                 // discriminants are int-like.
717                 let discr_val =
718                     self.cast_from_int_like(scalar, tag_val.layout, discr_layout.ty).unwrap();
719                 let discr_bits = discr_val.assert_bits(discr_layout.size);
720                 // Convert discriminant to variant index, and catch invalid discriminants.
721                 let index = match *op.layout.ty.kind() {
722                     ty::Adt(adt, _) => {
723                         adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits)
724                     }
725                     ty::Generator(def_id, substs, _) => {
726                         let substs = substs.as_generator();
727                         substs
728                             .discriminants(def_id, *self.tcx)
729                             .find(|(_, var)| var.val == discr_bits)
730                     }
731                     _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-generator"),
732                 }
733                 .ok_or_else(|| err_ub!(InvalidTag(Scalar::from_uint(tag_bits, tag_layout.size))))?;
734                 // Return the cast value, and the index.
735                 (discr_val, index.0)
736             }
737             TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => {
738                 let tag_val = tag_val.to_scalar();
739                 // Compute the variant this niche value/"tag" corresponds to. With niche layout,
740                 // discriminant (encoded in niche/tag) and variant index are the same.
741                 let variants_start = niche_variants.start().as_u32();
742                 let variants_end = niche_variants.end().as_u32();
743                 let variant = match tag_val.try_to_int() {
744                     Err(dbg_val) => {
745                         // So this is a pointer then, and casting to an int failed.
746                         // Can only happen during CTFE.
747                         // The niche must be just 0, and the ptr not null, then we know this is
748                         // okay. Everything else, we conservatively reject.
749                         let ptr_valid = niche_start == 0
750                             && variants_start == variants_end
751                             && !self.scalar_may_be_null(tag_val)?;
752                         if !ptr_valid {
753                             throw_ub!(InvalidTag(dbg_val))
754                         }
755                         untagged_variant
756                     }
757                     Ok(tag_bits) => {
758                         let tag_bits = tag_bits.assert_bits(tag_layout.size);
759                         // We need to use machine arithmetic to get the relative variant idx:
760                         // variant_index_relative = tag_val - niche_start_val
761                         let tag_val = ImmTy::from_uint(tag_bits, tag_layout);
762                         let niche_start_val = ImmTy::from_uint(niche_start, tag_layout);
763                         let variant_index_relative_val =
764                             self.binary_op(mir::BinOp::Sub, &tag_val, &niche_start_val)?;
765                         let variant_index_relative =
766                             variant_index_relative_val.to_scalar().assert_bits(tag_val.layout.size);
767                         // Check if this is in the range that indicates an actual discriminant.
768                         if variant_index_relative <= u128::from(variants_end - variants_start) {
769                             let variant_index_relative = u32::try_from(variant_index_relative)
770                                 .expect("we checked that this fits into a u32");
771                             // Then computing the absolute variant idx should not overflow any more.
772                             let variant_index = variants_start
773                                 .checked_add(variant_index_relative)
774                                 .expect("overflow computing absolute variant idx");
775                             let variants_len = op
776                                 .layout
777                                 .ty
778                                 .ty_adt_def()
779                                 .expect("tagged layout for non adt")
780                                 .variants()
781                                 .len();
782                             assert!(usize::try_from(variant_index).unwrap() < variants_len);
783                             VariantIdx::from_u32(variant_index)
784                         } else {
785                             untagged_variant
786                         }
787                     }
788                 };
789                 // Compute the size of the scalar we need to return.
790                 // No need to cast, because the variant index directly serves as discriminant and is
791                 // encoded in the tag.
792                 (Scalar::from_uint(variant.as_u32(), discr_layout.size), variant)
793             }
794         })
795     }
796 }
797
798 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
799 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
800 mod size_asserts {
801     use super::*;
802     use rustc_data_structures::static_assert_size;
803     // tidy-alphabetical-start
804     static_assert_size!(Immediate, 48);
805     static_assert_size!(ImmTy<'_>, 64);
806     static_assert_size!(Operand, 56);
807     static_assert_size!(OpTy<'_>, 80);
808     // tidy-alphabetical-end
809 }