]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/interpret/operand.rs
Re-use std::sealed::Sealed in os/linux/process.
[rust.git] / compiler / rustc_mir / 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 std::convert::TryFrom;
5 use std::fmt::Write;
6
7 use rustc_errors::ErrorReported;
8 use rustc_hir::def::Namespace;
9 use rustc_macros::HashStable;
10 use rustc_middle::ty::layout::{PrimitiveExt, TyAndLayout};
11 use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter, Printer};
12 use rustc_middle::ty::{ConstInt, Ty};
13 use rustc_middle::{mir, ty};
14 use rustc_target::abi::{Abi, HasDataLayout, LayoutOf, Size, TagEncoding};
15 use rustc_target::abi::{VariantIdx, Variants};
16
17 use super::{
18     alloc_range, from_known_layout, mir_assign_valid_types, AllocId, ConstValue, GlobalId,
19     InterpCx, InterpResult, MPlaceTy, Machine, MemPlace, Place, PlaceTy, Pointer, Provenance,
20     Scalar, ScalarMaybeUninit,
21 };
22
23 /// An `Immediate` represents a single immediate self-contained Rust value.
24 ///
25 /// For optimization of a few very common cases, there is also a representation for a pair of
26 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
27 /// operations and wide pointers. This idea was taken from rustc's codegen.
28 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
29 /// defined on `Immediate`, and do not have to work with a `Place`.
30 #[derive(Copy, Clone, PartialEq, Eq, HashStable, Hash, Debug)]
31 pub enum Immediate<Tag: Provenance = AllocId> {
32     Scalar(ScalarMaybeUninit<Tag>),
33     ScalarPair(ScalarMaybeUninit<Tag>, ScalarMaybeUninit<Tag>),
34 }
35
36 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
37 rustc_data_structures::static_assert_size!(Immediate, 56);
38
39 impl<Tag: Provenance> From<ScalarMaybeUninit<Tag>> for Immediate<Tag> {
40     #[inline(always)]
41     fn from(val: ScalarMaybeUninit<Tag>) -> Self {
42         Immediate::Scalar(val)
43     }
44 }
45
46 impl<Tag: Provenance> From<Scalar<Tag>> for Immediate<Tag> {
47     #[inline(always)]
48     fn from(val: Scalar<Tag>) -> Self {
49         Immediate::Scalar(val.into())
50     }
51 }
52
53 impl<'tcx, Tag: Provenance> Immediate<Tag> {
54     pub fn from_pointer(p: Pointer<Tag>, cx: &impl HasDataLayout) -> Self {
55         Immediate::Scalar(ScalarMaybeUninit::from_pointer(p, cx))
56     }
57
58     pub fn from_maybe_pointer(p: Pointer<Option<Tag>>, cx: &impl HasDataLayout) -> Self {
59         Immediate::Scalar(ScalarMaybeUninit::from_maybe_pointer(p, cx))
60     }
61
62     pub fn new_slice(val: Scalar<Tag>, len: u64, cx: &impl HasDataLayout) -> Self {
63         Immediate::ScalarPair(val.into(), Scalar::from_machine_usize(len, cx).into())
64     }
65
66     pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>, cx: &impl HasDataLayout) -> Self {
67         Immediate::ScalarPair(val.into(), ScalarMaybeUninit::from_pointer(vtable, cx))
68     }
69
70     #[inline]
71     pub fn to_scalar_or_uninit(self) -> ScalarMaybeUninit<Tag> {
72         match self {
73             Immediate::Scalar(val) => val,
74             Immediate::ScalarPair(..) => bug!("Got a wide pointer where a scalar was expected"),
75         }
76     }
77
78     #[inline]
79     pub fn to_scalar(self) -> InterpResult<'tcx, Scalar<Tag>> {
80         self.to_scalar_or_uninit().check_init()
81     }
82 }
83
84 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
85 // as input for binary and cast operations.
86 #[derive(Copy, Clone, Debug)]
87 pub struct ImmTy<'tcx, Tag: Provenance = AllocId> {
88     imm: Immediate<Tag>,
89     pub layout: TyAndLayout<'tcx>,
90 }
91
92 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
93 rustc_data_structures::static_assert_size!(ImmTy<'_>, 72);
94
95 impl<Tag: Provenance> std::fmt::Display for ImmTy<'tcx, Tag> {
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, F: std::fmt::Write, Tag: Provenance>(
99             cx: FmtPrinter<'a, 'tcx, F>,
100             s: ScalarMaybeUninit<Tag>,
101             ty: Ty<'tcx>,
102         ) -> Result<FmtPrinter<'a, 'tcx, F>, std::fmt::Error> {
103             match s {
104                 ScalarMaybeUninit::Scalar(Scalar::Int(int)) => {
105                     cx.pretty_print_const_scalar_int(int, ty, true)
106                 }
107                 ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _sz)) => {
108                     // Just print the ptr value. `pretty_print_const_scalar_ptr` would also try to
109                     // print what is points to, which would fail since it has no access to the local
110                     // memory.
111                     cx.pretty_print_const_pointer(ptr, ty, true)
112                 }
113                 ScalarMaybeUninit::Uninit => cx.typed_value(
114                     |mut this| {
115                         this.write_str("uninit ")?;
116                         Ok(this)
117                     },
118                     |this| this.print_type(ty),
119                     " ",
120                 ),
121             }
122         }
123         ty::tls::with(|tcx| {
124             match self.imm {
125                 Immediate::Scalar(s) => {
126                     if let Some(ty) = tcx.lift(self.layout.ty) {
127                         let cx = FmtPrinter::new(tcx, f, Namespace::ValueNS);
128                         p(cx, s, ty)?;
129                         return Ok(());
130                     }
131                     write!(f, "{}: {}", s, self.layout.ty)
132                 }
133                 Immediate::ScalarPair(a, b) => {
134                     // FIXME(oli-obk): at least print tuples and slices nicely
135                     write!(f, "({}, {}): {}", a, b, self.layout.ty,)
136                 }
137             }
138         })
139     }
140 }
141
142 impl<'tcx, Tag: Provenance> std::ops::Deref for ImmTy<'tcx, Tag> {
143     type Target = Immediate<Tag>;
144     #[inline(always)]
145     fn deref(&self) -> &Immediate<Tag> {
146         &self.imm
147     }
148 }
149
150 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
151 /// or still in memory. The latter is an optimization, to delay reading that chunk of
152 /// memory and to avoid having to store arbitrary-sized data here.
153 #[derive(Copy, Clone, PartialEq, Eq, HashStable, Hash, Debug)]
154 pub enum Operand<Tag: Provenance = AllocId> {
155     Immediate(Immediate<Tag>),
156     Indirect(MemPlace<Tag>),
157 }
158
159 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
160 pub struct OpTy<'tcx, Tag: Provenance = AllocId> {
161     op: Operand<Tag>, // Keep this private; it helps enforce invariants.
162     pub layout: TyAndLayout<'tcx>,
163 }
164
165 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
166 rustc_data_structures::static_assert_size!(OpTy<'_>, 80);
167
168 impl<'tcx, Tag: Provenance> std::ops::Deref for OpTy<'tcx, Tag> {
169     type Target = Operand<Tag>;
170     #[inline(always)]
171     fn deref(&self) -> &Operand<Tag> {
172         &self.op
173     }
174 }
175
176 impl<'tcx, Tag: Provenance> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
177     #[inline(always)]
178     fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
179         OpTy { op: Operand::Indirect(*mplace), layout: mplace.layout }
180     }
181 }
182
183 impl<'tcx, Tag: Provenance> From<&'_ MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
184     #[inline(always)]
185     fn from(mplace: &MPlaceTy<'tcx, Tag>) -> Self {
186         OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout }
187     }
188 }
189
190 impl<'tcx, Tag: Provenance> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
191     #[inline(always)]
192     fn from(val: ImmTy<'tcx, Tag>) -> Self {
193         OpTy { op: Operand::Immediate(val.imm), layout: val.layout }
194     }
195 }
196
197 impl<'tcx, Tag: Provenance> ImmTy<'tcx, Tag> {
198     #[inline]
199     pub fn from_scalar(val: Scalar<Tag>, layout: TyAndLayout<'tcx>) -> Self {
200         ImmTy { imm: val.into(), layout }
201     }
202
203     #[inline]
204     pub fn from_immediate(imm: Immediate<Tag>, layout: TyAndLayout<'tcx>) -> Self {
205         ImmTy { imm, layout }
206     }
207
208     #[inline]
209     pub fn try_from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
210         Some(Self::from_scalar(Scalar::try_from_uint(i, layout.size)?, layout))
211     }
212     #[inline]
213     pub fn from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Self {
214         Self::from_scalar(Scalar::from_uint(i, layout.size), layout)
215     }
216
217     #[inline]
218     pub fn try_from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
219         Some(Self::from_scalar(Scalar::try_from_int(i, layout.size)?, layout))
220     }
221
222     #[inline]
223     pub fn from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Self {
224         Self::from_scalar(Scalar::from_int(i, layout.size), layout)
225     }
226
227     #[inline]
228     pub fn to_const_int(self) -> ConstInt {
229         assert!(self.layout.ty.is_integral());
230         let int = self.to_scalar().expect("to_const_int doesn't work on scalar pairs").assert_int();
231         ConstInt::new(int, self.layout.ty.is_signed(), self.layout.ty.is_ptr_sized_integral())
232     }
233 }
234
235 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
236     /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
237     /// Returns `None` if the layout does not permit loading this as a value.
238     fn try_read_immediate_from_mplace(
239         &self,
240         mplace: &MPlaceTy<'tcx, M::PointerTag>,
241     ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::PointerTag>>> {
242         if mplace.layout.is_unsized() {
243             // Don't touch unsized
244             return Ok(None);
245         }
246
247         let alloc = match self.get_alloc(mplace)? {
248             Some(ptr) => ptr,
249             None => {
250                 return Ok(Some(ImmTy {
251                     // zero-sized type
252                     imm: Scalar::ZST.into(),
253                     layout: mplace.layout,
254                 }));
255             }
256         };
257
258         match mplace.layout.abi {
259             Abi::Scalar(..) => {
260                 let scalar = alloc.read_scalar(alloc_range(Size::ZERO, mplace.layout.size))?;
261                 Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout }))
262             }
263             Abi::ScalarPair(ref a, ref b) => {
264                 // We checked `ptr_align` above, so all fields will have the alignment they need.
265                 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
266                 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
267                 let (a, b) = (&a.value, &b.value);
268                 let (a_size, b_size) = (a.size(self), b.size(self));
269                 let b_offset = a_size.align_to(b.align(self).abi);
270                 assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields
271                 let a_val = alloc.read_scalar(alloc_range(Size::ZERO, a_size))?;
272                 let b_val = alloc.read_scalar(alloc_range(b_offset, b_size))?;
273                 Ok(Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout }))
274             }
275             _ => Ok(None),
276         }
277     }
278
279     /// Try returning an immediate for the operand.
280     /// If the layout does not permit loading this as an immediate, return where in memory
281     /// we can find the data.
282     /// Note that for a given layout, this operation will either always fail or always
283     /// succeed!  Whether it succeeds depends on whether the layout can be represented
284     /// in a `Immediate`, not on which data is stored there currently.
285     pub(crate) fn try_read_immediate(
286         &self,
287         src: &OpTy<'tcx, M::PointerTag>,
288     ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
289         Ok(match src.try_as_mplace() {
290             Ok(ref mplace) => {
291                 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
292                     Ok(val)
293                 } else {
294                     Err(*mplace)
295                 }
296             }
297             Err(val) => Ok(val),
298         })
299     }
300
301     /// Read an immediate from a place, asserting that that is possible with the given layout.
302     #[inline(always)]
303     pub fn read_immediate(
304         &self,
305         op: &OpTy<'tcx, M::PointerTag>,
306     ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
307         if let Ok(imm) = self.try_read_immediate(op)? {
308             Ok(imm)
309         } else {
310             span_bug!(self.cur_span(), "primitive read failed for type: {:?}", op.layout.ty);
311         }
312     }
313
314     /// Read a scalar from a place
315     pub fn read_scalar(
316         &self,
317         op: &OpTy<'tcx, M::PointerTag>,
318     ) -> InterpResult<'tcx, ScalarMaybeUninit<M::PointerTag>> {
319         Ok(self.read_immediate(op)?.to_scalar_or_uninit())
320     }
321
322     /// Read a pointer from a place.
323     pub fn read_pointer(
324         &self,
325         op: &OpTy<'tcx, M::PointerTag>,
326     ) -> InterpResult<'tcx, Pointer<Option<M::PointerTag>>> {
327         Ok(self.scalar_to_ptr(self.read_scalar(op)?.check_init()?))
328     }
329
330     // Turn the wide MPlace into a string (must already be dereferenced!)
331     pub fn read_str(&self, mplace: &MPlaceTy<'tcx, M::PointerTag>) -> InterpResult<'tcx, &str> {
332         let len = mplace.len(self)?;
333         let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len))?;
334         let str = std::str::from_utf8(bytes).map_err(|err| err_ub!(InvalidStr(err)))?;
335         Ok(str)
336     }
337
338     /// Projection functions
339     pub fn operand_field(
340         &self,
341         op: &OpTy<'tcx, M::PointerTag>,
342         field: usize,
343     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
344         let base = match op.try_as_mplace() {
345             Ok(ref mplace) => {
346                 // We can reuse the mplace field computation logic for indirect operands.
347                 let field = self.mplace_field(mplace, field)?;
348                 return Ok(field.into());
349             }
350             Err(value) => value,
351         };
352
353         let field_layout = op.layout.field(self, field)?;
354         if field_layout.is_zst() {
355             let immediate = Scalar::ZST.into();
356             return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
357         }
358         let offset = op.layout.fields.offset(field);
359         let immediate = match *base {
360             // the field covers the entire type
361             _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base,
362             // extract fields from types with `ScalarPair` ABI
363             Immediate::ScalarPair(a, b) => {
364                 let val = if offset.bytes() == 0 { a } else { b };
365                 Immediate::from(val)
366             }
367             Immediate::Scalar(val) => span_bug!(
368                 self.cur_span(),
369                 "field access on non aggregate {:#?}, {:#?}",
370                 val,
371                 op.layout
372             ),
373         };
374         Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
375     }
376
377     pub fn operand_index(
378         &self,
379         op: &OpTy<'tcx, M::PointerTag>,
380         index: u64,
381     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
382         if let Ok(index) = usize::try_from(index) {
383             // We can just treat this as a field.
384             self.operand_field(op, index)
385         } else {
386             // Indexing into a big array. This must be an mplace.
387             let mplace = op.assert_mem_place();
388             Ok(self.mplace_index(&mplace, index)?.into())
389         }
390     }
391
392     pub fn operand_downcast(
393         &self,
394         op: &OpTy<'tcx, M::PointerTag>,
395         variant: VariantIdx,
396     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
397         // Downcasts only change the layout
398         Ok(match op.try_as_mplace() {
399             Ok(ref mplace) => self.mplace_downcast(mplace, variant)?.into(),
400             Err(..) => {
401                 let layout = op.layout.for_variant(self, variant);
402                 OpTy { layout, ..*op }
403             }
404         })
405     }
406
407     pub fn operand_projection(
408         &self,
409         base: &OpTy<'tcx, M::PointerTag>,
410         proj_elem: mir::PlaceElem<'tcx>,
411     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
412         use rustc_middle::mir::ProjectionElem::*;
413         Ok(match proj_elem {
414             Field(field, _) => self.operand_field(base, field.index())?,
415             Downcast(_, variant) => self.operand_downcast(base, variant)?,
416             Deref => self.deref_operand(base)?.into(),
417             Subslice { .. } | ConstantIndex { .. } | Index(_) => {
418                 // The rest should only occur as mplace, we do not use Immediates for types
419                 // allowing such operations.  This matches place_projection forcing an allocation.
420                 let mplace = base.assert_mem_place();
421                 self.mplace_projection(&mplace, proj_elem)?.into()
422             }
423         })
424     }
425
426     /// Read from a local. Will not actually access the local if reading from a ZST.
427     /// Will not access memory, instead an indirect `Operand` is returned.
428     ///
429     /// This is public because it is used by [priroda](https://github.com/oli-obk/priroda) to get an
430     /// OpTy from a local
431     pub fn access_local(
432         &self,
433         frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
434         local: mir::Local,
435         layout: Option<TyAndLayout<'tcx>>,
436     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
437         let layout = self.layout_of_local(frame, local, layout)?;
438         let op = if layout.is_zst() {
439             // Do not read from ZST, they might not be initialized
440             Operand::Immediate(Scalar::ZST.into())
441         } else {
442             M::access_local(&self, frame, local)?
443         };
444         Ok(OpTy { op, layout })
445     }
446
447     /// Every place can be read from, so we can turn them into an operand.
448     /// This will definitely return `Indirect` if the place is a `Ptr`, i.e., this
449     /// will never actually read from memory.
450     #[inline(always)]
451     pub fn place_to_op(
452         &self,
453         place: &PlaceTy<'tcx, M::PointerTag>,
454     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
455         let op = match **place {
456             Place::Ptr(mplace) => Operand::Indirect(mplace),
457             Place::Local { frame, local } => {
458                 *self.access_local(&self.stack()[frame], local, None)?
459             }
460         };
461         Ok(OpTy { op, layout: place.layout })
462     }
463
464     // Evaluate a place with the goal of reading from it.  This lets us sometimes
465     // avoid allocations.
466     pub fn eval_place_to_op(
467         &self,
468         place: mir::Place<'tcx>,
469         layout: Option<TyAndLayout<'tcx>>,
470     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
471         // Do not use the layout passed in as argument if the base we are looking at
472         // here is not the entire place.
473         let layout = if place.projection.is_empty() { layout } else { None };
474
475         let base_op = self.access_local(self.frame(), place.local, layout)?;
476
477         let op = place
478             .projection
479             .iter()
480             .try_fold(base_op, |op, elem| self.operand_projection(&op, elem))?;
481
482         trace!("eval_place_to_op: got {:?}", *op);
483         // Sanity-check the type we ended up with.
484         debug_assert!(mir_assign_valid_types(
485             *self.tcx,
486             self.param_env,
487             self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
488                 place.ty(&self.frame().body.local_decls, *self.tcx).ty
489             ))?,
490             op.layout,
491         ));
492         Ok(op)
493     }
494
495     /// Evaluate the operand, returning a place where you can then find the data.
496     /// If you already know the layout, you can save two table lookups
497     /// by passing it in here.
498     #[inline]
499     pub fn eval_operand(
500         &self,
501         mir_op: &mir::Operand<'tcx>,
502         layout: Option<TyAndLayout<'tcx>>,
503     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
504         use rustc_middle::mir::Operand::*;
505         let op = match *mir_op {
506             // FIXME: do some more logic on `move` to invalidate the old location
507             Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?,
508
509             Constant(ref constant) => {
510                 let val =
511                     self.subst_from_current_frame_and_normalize_erasing_regions(constant.literal);
512                 // This can still fail:
513                 // * During ConstProp, with `TooGeneric` or since the `requried_consts` were not all
514                 //   checked yet.
515                 // * During CTFE, since promoteds in `const`/`static` initializer bodies can fail.
516
517                 self.mir_const_to_op(&val, layout)?
518             }
519         };
520         trace!("{:?}: {:?}", mir_op, *op);
521         Ok(op)
522     }
523
524     /// Evaluate a bunch of operands at once
525     pub(super) fn eval_operands(
526         &self,
527         ops: &[mir::Operand<'tcx>],
528     ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
529         ops.iter().map(|op| self.eval_operand(op, None)).collect()
530     }
531
532     // Used when the miri-engine runs into a constant and for extracting information from constants
533     // in patterns via the `const_eval` module
534     /// The `val` and `layout` are assumed to already be in our interpreter
535     /// "universe" (param_env).
536     crate fn const_to_op(
537         &self,
538         val: &ty::Const<'tcx>,
539         layout: Option<TyAndLayout<'tcx>>,
540     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
541         match val.val {
542             ty::ConstKind::Param(_) | ty::ConstKind::Bound(..) => throw_inval!(TooGeneric),
543             ty::ConstKind::Error(_) => throw_inval!(AlreadyReported(ErrorReported)),
544             ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }) => {
545                 let instance = self.resolve(def, substs)?;
546                 Ok(self.eval_to_allocation(GlobalId { instance, promoted })?.into())
547             }
548             ty::ConstKind::Infer(..) | ty::ConstKind::Placeholder(..) => {
549                 span_bug!(self.cur_span(), "const_to_op: Unexpected ConstKind {:?}", val)
550             }
551             ty::ConstKind::Value(val_val) => self.const_val_to_op(val_val, val.ty, layout),
552         }
553     }
554
555     crate fn mir_const_to_op(
556         &self,
557         val: &mir::ConstantKind<'tcx>,
558         layout: Option<TyAndLayout<'tcx>>,
559     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
560         match val {
561             mir::ConstantKind::Ty(ct) => self.const_to_op(ct, layout),
562             mir::ConstantKind::Val(val, ty) => self.const_val_to_op(*val, ty, layout),
563         }
564     }
565
566     crate fn const_val_to_op(
567         &self,
568         val_val: ConstValue<'tcx>,
569         ty: Ty<'tcx>,
570         layout: Option<TyAndLayout<'tcx>>,
571     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
572         // Other cases need layout.
573         let tag_scalar = |scalar| -> InterpResult<'tcx, _> {
574             Ok(match scalar {
575                 Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size),
576                 Scalar::Int(int) => Scalar::Int(int),
577             })
578         };
579         let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?;
580         let op = match val_val {
581             ConstValue::ByRef { alloc, offset } => {
582                 let id = self.tcx.create_memory_alloc(alloc);
583                 // We rely on mutability being set correctly in that allocation to prevent writes
584                 // where none should happen.
585                 let ptr = self.global_base_pointer(Pointer::new(id, offset))?;
586                 Operand::Indirect(MemPlace::from_ptr(ptr.into(), layout.align.abi))
587             }
588             ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x.into())?.into()),
589             ConstValue::Slice { data, start, end } => {
590                 // We rely on mutability being set correctly in `data` to prevent writes
591                 // where none should happen.
592                 let ptr = Pointer::new(
593                     self.tcx.create_memory_alloc(data),
594                     Size::from_bytes(start), // offset: `start`
595                 );
596                 Operand::Immediate(Immediate::new_slice(
597                     Scalar::from_pointer(self.global_base_pointer(ptr)?, &*self.tcx),
598                     u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start`
599                     self,
600                 ))
601             }
602         };
603         Ok(OpTy { op, layout })
604     }
605
606     /// Read discriminant, return the runtime value as well as the variant index.
607     pub fn read_discriminant(
608         &self,
609         op: &OpTy<'tcx, M::PointerTag>,
610     ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, VariantIdx)> {
611         trace!("read_discriminant_value {:#?}", op.layout);
612         // Get type and layout of the discriminant.
613         let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(*self.tcx))?;
614         trace!("discriminant type: {:?}", discr_layout.ty);
615
616         // We use "discriminant" to refer to the value associated with a particular enum variant.
617         // This is not to be confused with its "variant index", which is just determining its position in the
618         // declared list of variants -- they can differ with explicitly assigned discriminants.
619         // We use "tag" to refer to how the discriminant is encoded in memory, which can be either
620         // straight-forward (`TagEncoding::Direct`) or with a niche (`TagEncoding::Niche`).
621         let (tag_scalar_layout, tag_encoding, tag_field) = match op.layout.variants {
622             Variants::Single { index } => {
623                 let discr = match op.layout.ty.discriminant_for_variant(*self.tcx, index) {
624                     Some(discr) => {
625                         // This type actually has discriminants.
626                         assert_eq!(discr.ty, discr_layout.ty);
627                         Scalar::from_uint(discr.val, discr_layout.size)
628                     }
629                     None => {
630                         // On a type without actual discriminants, variant is 0.
631                         assert_eq!(index.as_u32(), 0);
632                         Scalar::from_uint(index.as_u32(), discr_layout.size)
633                     }
634                 };
635                 return Ok((discr, index));
636             }
637             Variants::Multiple { ref tag, ref tag_encoding, tag_field, .. } => {
638                 (tag, tag_encoding, tag_field)
639             }
640         };
641
642         // There are *three* layouts that come into play here:
643         // - The discriminant has a type for typechecking. This is `discr_layout`, and is used for
644         //   the `Scalar` we return.
645         // - The tag (encoded discriminant) has layout `tag_layout`. This is always an integer type,
646         //   and used to interpret the value we read from the tag field.
647         //   For the return value, a cast to `discr_layout` is performed.
648         // - The field storing the tag has a layout, which is very similar to `tag_layout` but
649         //   may be a pointer. This is `tag_val.layout`; we just use it for sanity checks.
650
651         // Get layout for tag.
652         let tag_layout = self.layout_of(tag_scalar_layout.value.to_int_ty(*self.tcx))?;
653
654         // Read tag and sanity-check `tag_layout`.
655         let tag_val = self.read_immediate(&self.operand_field(op, tag_field)?)?;
656         assert_eq!(tag_layout.size, tag_val.layout.size);
657         assert_eq!(tag_layout.abi.is_signed(), tag_val.layout.abi.is_signed());
658         let tag_val = tag_val.to_scalar()?;
659         trace!("tag value: {:?}", tag_val);
660
661         // Figure out which discriminant and variant this corresponds to.
662         Ok(match *tag_encoding {
663             TagEncoding::Direct => {
664                 let tag_bits = tag_val
665                     .try_to_int()
666                     .map_err(|dbg_val| err_ub!(InvalidTag(dbg_val)))?
667                     .assert_bits(tag_layout.size);
668                 // Cast bits from tag layout to discriminant layout.
669                 let discr_val = self.cast_from_scalar(tag_bits, tag_layout, discr_layout.ty);
670                 let discr_bits = discr_val.assert_bits(discr_layout.size);
671                 // Convert discriminant to variant index, and catch invalid discriminants.
672                 let index = match *op.layout.ty.kind() {
673                     ty::Adt(adt, _) => {
674                         adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits)
675                     }
676                     ty::Generator(def_id, substs, _) => {
677                         let substs = substs.as_generator();
678                         substs
679                             .discriminants(def_id, *self.tcx)
680                             .find(|(_, var)| var.val == discr_bits)
681                     }
682                     _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-generator"),
683                 }
684                 .ok_or_else(|| err_ub!(InvalidTag(Scalar::from_uint(tag_bits, tag_layout.size))))?;
685                 // Return the cast value, and the index.
686                 (discr_val, index.0)
687             }
688             TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start } => {
689                 // Compute the variant this niche value/"tag" corresponds to. With niche layout,
690                 // discriminant (encoded in niche/tag) and variant index are the same.
691                 let variants_start = niche_variants.start().as_u32();
692                 let variants_end = niche_variants.end().as_u32();
693                 let variant = match tag_val.try_to_int() {
694                     Err(dbg_val) => {
695                         // So this is a pointer then, and casting to an int failed.
696                         // Can only happen during CTFE.
697                         let ptr = self.scalar_to_ptr(tag_val);
698                         // The niche must be just 0, and the ptr not null, then we know this is
699                         // okay. Everything else, we conservatively reject.
700                         let ptr_valid = niche_start == 0
701                             && variants_start == variants_end
702                             && !self.memory.ptr_may_be_null(ptr);
703                         if !ptr_valid {
704                             throw_ub!(InvalidTag(dbg_val))
705                         }
706                         dataful_variant
707                     }
708                     Ok(tag_bits) => {
709                         let tag_bits = tag_bits.assert_bits(tag_layout.size);
710                         // We need to use machine arithmetic to get the relative variant idx:
711                         // variant_index_relative = tag_val - niche_start_val
712                         let tag_val = ImmTy::from_uint(tag_bits, tag_layout);
713                         let niche_start_val = ImmTy::from_uint(niche_start, tag_layout);
714                         let variant_index_relative_val =
715                             self.binary_op(mir::BinOp::Sub, &tag_val, &niche_start_val)?;
716                         let variant_index_relative = variant_index_relative_val
717                             .to_scalar()?
718                             .assert_bits(tag_val.layout.size);
719                         // Check if this is in the range that indicates an actual discriminant.
720                         if variant_index_relative <= u128::from(variants_end - variants_start) {
721                             let variant_index_relative = u32::try_from(variant_index_relative)
722                                 .expect("we checked that this fits into a u32");
723                             // Then computing the absolute variant idx should not overflow any more.
724                             let variant_index = variants_start
725                                 .checked_add(variant_index_relative)
726                                 .expect("overflow computing absolute variant idx");
727                             let variants_len = op
728                                 .layout
729                                 .ty
730                                 .ty_adt_def()
731                                 .expect("tagged layout for non adt")
732                                 .variants
733                                 .len();
734                             assert!(usize::try_from(variant_index).unwrap() < variants_len);
735                             VariantIdx::from_u32(variant_index)
736                         } else {
737                             dataful_variant
738                         }
739                     }
740                 };
741                 // Compute the size of the scalar we need to return.
742                 // No need to cast, because the variant index directly serves as discriminant and is
743                 // encoded in the tag.
744                 (Scalar::from_uint(variant.as_u32(), discr_layout.size), variant)
745             }
746         })
747     }
748 }