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