]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/operand.rs
81009fd7b98f73716be27632ef7853e4a0e2caeb
[rust.git] / src / librustc_mir / 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::{IntegerExt, PrimitiveExt, TyAndLayout};
11 use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter, Printer};
12 use rustc_middle::ty::Ty;
13 use rustc_middle::{mir, ty};
14 use rustc_target::abi::{Abi, DiscriminantKind, HasDataLayout, Integer, LayoutOf, Size};
15 use rustc_target::abi::{VariantIdx, Variants};
16
17 use super::{
18     from_known_layout, sign_extend, truncate, ConstValue, GlobalId, InterpCx, InterpResult,
19     MPlaceTy, Machine, MemPlace, Place, PlaceTy, Pointer, Scalar, ScalarMaybeUninit,
20 };
21
22 /// An `Immediate` represents a single immediate self-contained Rust value.
23 ///
24 /// For optimization of a few very common cases, there is also a representation for a pair of
25 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
26 /// operations and wide pointers. This idea was taken from rustc's codegen.
27 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
28 /// defined on `Immediate`, and do not have to work with a `Place`.
29 #[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable, Hash)]
30 pub enum Immediate<Tag = ()> {
31     Scalar(ScalarMaybeUninit<Tag>),
32     ScalarPair(ScalarMaybeUninit<Tag>, ScalarMaybeUninit<Tag>),
33 }
34
35 impl<Tag> From<ScalarMaybeUninit<Tag>> for Immediate<Tag> {
36     #[inline(always)]
37     fn from(val: ScalarMaybeUninit<Tag>) -> Self {
38         Immediate::Scalar(val)
39     }
40 }
41
42 impl<Tag> From<Scalar<Tag>> for Immediate<Tag> {
43     #[inline(always)]
44     fn from(val: Scalar<Tag>) -> Self {
45         Immediate::Scalar(val.into())
46     }
47 }
48
49 impl<Tag> From<Pointer<Tag>> for Immediate<Tag> {
50     #[inline(always)]
51     fn from(val: Pointer<Tag>) -> Self {
52         Immediate::Scalar(Scalar::from(val).into())
53     }
54 }
55
56 impl<'tcx, Tag> Immediate<Tag> {
57     pub fn new_slice(val: Scalar<Tag>, len: u64, cx: &impl HasDataLayout) -> Self {
58         Immediate::ScalarPair(val.into(), Scalar::from_machine_usize(len, cx).into())
59     }
60
61     pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>) -> Self {
62         Immediate::ScalarPair(val.into(), vtable.into())
63     }
64
65     #[inline]
66     pub fn to_scalar_or_undef(self) -> ScalarMaybeUninit<Tag> {
67         match self {
68             Immediate::Scalar(val) => val,
69             Immediate::ScalarPair(..) => bug!("Got a wide pointer where a scalar was expected"),
70         }
71     }
72
73     #[inline]
74     pub fn to_scalar(self) -> InterpResult<'tcx, Scalar<Tag>> {
75         self.to_scalar_or_undef().not_undef()
76     }
77
78     #[inline]
79     pub fn to_scalar_pair(self) -> InterpResult<'tcx, (Scalar<Tag>, Scalar<Tag>)> {
80         match self {
81             Immediate::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"),
82             Immediate::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?)),
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(Copy, Clone, Debug)]
90 pub struct ImmTy<'tcx, Tag = ()> {
91     imm: Immediate<Tag>,
92     pub layout: TyAndLayout<'tcx>,
93 }
94
95 impl<Tag: Copy> 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>(
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(s) => {
105                     cx.pretty_print_const_scalar(s.erase_tag(), ty, true)
106                 }
107                 ScalarMaybeUninit::Uninit => cx.typed_value(
108                     |mut this| {
109                         this.write_str("{undef ")?;
110                         Ok(this)
111                     },
112                     |this| this.print_type(ty),
113                     " ",
114                 ),
115             }
116         }
117         ty::tls::with(|tcx| {
118             match self.imm {
119                 Immediate::Scalar(s) => {
120                     if let Some(ty) = tcx.lift(&self.layout.ty) {
121                         let cx = FmtPrinter::new(tcx, f, Namespace::ValueNS);
122                         p(cx, s, ty)?;
123                         return Ok(());
124                     }
125                     write!(f, "{}: {}", s.erase_tag(), self.layout.ty)
126                 }
127                 Immediate::ScalarPair(a, b) => {
128                     // FIXME(oli-obk): at least print tuples and slices nicely
129                     write!(f, "({}, {}): {}", a.erase_tag(), b.erase_tag(), self.layout.ty,)
130                 }
131             }
132         })
133     }
134 }
135
136 impl<'tcx, Tag> ::std::ops::Deref for ImmTy<'tcx, Tag> {
137     type Target = Immediate<Tag>;
138     #[inline(always)]
139     fn deref(&self) -> &Immediate<Tag> {
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, PartialEq, Eq, HashStable, Hash)]
148 pub enum Operand<Tag = ()> {
149     Immediate(Immediate<Tag>),
150     Indirect(MemPlace<Tag>),
151 }
152
153 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
154 pub struct OpTy<'tcx, Tag = ()> {
155     op: Operand<Tag>, // Keep this private; it helps enforce invariants.
156     pub layout: TyAndLayout<'tcx>,
157 }
158
159 impl<'tcx, Tag> ::std::ops::Deref for OpTy<'tcx, Tag> {
160     type Target = Operand<Tag>;
161     #[inline(always)]
162     fn deref(&self) -> &Operand<Tag> {
163         &self.op
164     }
165 }
166
167 impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
168     #[inline(always)]
169     fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
170         OpTy { op: Operand::Indirect(*mplace), layout: mplace.layout }
171     }
172 }
173
174 impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
175     #[inline(always)]
176     fn from(val: ImmTy<'tcx, Tag>) -> Self {
177         OpTy { op: Operand::Immediate(val.imm), layout: val.layout }
178     }
179 }
180
181 impl<'tcx, Tag: Copy> ImmTy<'tcx, Tag> {
182     #[inline]
183     pub fn from_scalar(val: Scalar<Tag>, layout: TyAndLayout<'tcx>) -> Self {
184         ImmTy { imm: val.into(), layout }
185     }
186
187     #[inline]
188     pub fn from_immediate(imm: Immediate<Tag>, layout: TyAndLayout<'tcx>) -> Self {
189         ImmTy { imm, layout }
190     }
191
192     #[inline]
193     pub fn try_from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
194         Some(Self::from_scalar(Scalar::try_from_uint(i, layout.size)?, layout))
195     }
196     #[inline]
197     pub fn from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Self {
198         Self::from_scalar(Scalar::from_uint(i, layout.size), layout)
199     }
200
201     #[inline]
202     pub fn try_from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
203         Some(Self::from_scalar(Scalar::try_from_int(i, layout.size)?, layout))
204     }
205
206     #[inline]
207     pub fn from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Self {
208         Self::from_scalar(Scalar::from_int(i, layout.size), layout)
209     }
210 }
211
212 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
213     /// Normalice `place.ptr` to a `Pointer` if this is a place and not a ZST.
214     /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
215     #[inline]
216     pub fn force_op_ptr(
217         &self,
218         op: OpTy<'tcx, M::PointerTag>,
219     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
220         match op.try_as_mplace(self) {
221             Ok(mplace) => Ok(self.force_mplace_ptr(mplace)?.into()),
222             Err(imm) => Ok(imm.into()), // Nothing to cast/force
223         }
224     }
225
226     /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
227     /// Returns `None` if the layout does not permit loading this as a value.
228     fn try_read_immediate_from_mplace(
229         &self,
230         mplace: MPlaceTy<'tcx, M::PointerTag>,
231     ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::PointerTag>>> {
232         if mplace.layout.is_unsized() {
233             // Don't touch unsized
234             return Ok(None);
235         }
236
237         let ptr = match self
238             .check_mplace_access(mplace, None)
239             .expect("places should be checked on creation")
240         {
241             Some(ptr) => ptr,
242             None => {
243                 if let Scalar::Ptr(ptr) = mplace.ptr {
244                     // We may be reading from a static.
245                     // In order to ensure that `static FOO: Type = FOO;` causes a cycle error
246                     // instead of magically pulling *any* ZST value from the ether, we need to
247                     // actually access the referenced allocation.
248                     self.memory.get_raw(ptr.alloc_id)?;
249                 }
250                 return Ok(Some(ImmTy {
251                     // zero-sized type
252                     imm: Scalar::zst().into(),
253                     layout: mplace.layout,
254                 }));
255             }
256         };
257
258         let alloc = self.memory.get_raw(ptr.alloc_id)?;
259
260         match mplace.layout.abi {
261             Abi::Scalar(..) => {
262                 let scalar = alloc.read_scalar(self, ptr, mplace.layout.size)?;
263                 Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout }))
264             }
265             Abi::ScalarPair(ref a, ref b) => {
266                 // We checked `ptr_align` above, so all fields will have the alignment they need.
267                 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
268                 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
269                 let (a, b) = (&a.value, &b.value);
270                 let (a_size, b_size) = (a.size(self), b.size(self));
271                 let a_ptr = ptr;
272                 let b_offset = a_size.align_to(b.align(self).abi);
273                 assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields
274                 let b_ptr = ptr.offset(b_offset, self)?;
275                 let a_val = alloc.read_scalar(self, a_ptr, a_size)?;
276                 let b_val = alloc.read_scalar(self, b_ptr, b_size)?;
277                 Ok(Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout }))
278             }
279             _ => Ok(None),
280         }
281     }
282
283     /// Try returning an immediate for the operand.
284     /// If the layout does not permit loading this as an immediate, return where in memory
285     /// we can find the data.
286     /// Note that for a given layout, this operation will either always fail or always
287     /// succeed!  Whether it succeeds depends on whether the layout can be represented
288     /// in a `Immediate`, not on which data is stored there currently.
289     pub(crate) fn try_read_immediate(
290         &self,
291         src: OpTy<'tcx, M::PointerTag>,
292     ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
293         Ok(match src.try_as_mplace(self) {
294             Ok(mplace) => {
295                 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
296                     Ok(val)
297                 } else {
298                     Err(mplace)
299                 }
300             }
301             Err(val) => Ok(val),
302         })
303     }
304
305     /// Read an immediate from a place, asserting that that is possible with the given layout.
306     #[inline(always)]
307     pub fn read_immediate(
308         &self,
309         op: OpTy<'tcx, M::PointerTag>,
310     ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
311         if let Ok(imm) = self.try_read_immediate(op)? {
312             Ok(imm)
313         } else {
314             bug!("primitive read failed for type: {:?}", op.layout.ty);
315         }
316     }
317
318     /// Read a scalar from a place
319     pub fn read_scalar(
320         &self,
321         op: OpTy<'tcx, M::PointerTag>,
322     ) -> InterpResult<'tcx, ScalarMaybeUninit<M::PointerTag>> {
323         Ok(self.read_immediate(op)?.to_scalar_or_undef())
324     }
325
326     // Turn the wide MPlace into a string (must already be dereferenced!)
327     pub fn read_str(&self, mplace: MPlaceTy<'tcx, M::PointerTag>) -> InterpResult<'tcx, &str> {
328         let len = mplace.len(self)?;
329         let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len))?;
330         let str = ::std::str::from_utf8(bytes).map_err(|err| err_ub!(InvalidStr(err)))?;
331         Ok(str)
332     }
333
334     /// Projection functions
335     pub fn operand_field(
336         &self,
337         op: OpTy<'tcx, M::PointerTag>,
338         field: usize,
339     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
340         let base = match op.try_as_mplace(self) {
341             Ok(mplace) => {
342                 // We can reuse the mplace field computation logic for indirect operands.
343                 let field = self.mplace_field(mplace, field)?;
344                 return Ok(field.into());
345             }
346             Err(value) => value,
347         };
348
349         let field_layout = op.layout.field(self, field)?;
350         if field_layout.is_zst() {
351             let immediate = Scalar::zst().into();
352             return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
353         }
354         let offset = op.layout.fields.offset(field);
355         let immediate = match *base {
356             // the field covers the entire type
357             _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base,
358             // extract fields from types with `ScalarPair` ABI
359             Immediate::ScalarPair(a, b) => {
360                 let val = if offset.bytes() == 0 { a } else { b };
361                 Immediate::from(val)
362             }
363             Immediate::Scalar(val) => {
364                 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout)
365             }
366         };
367         Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
368     }
369
370     pub fn operand_index(
371         &self,
372         op: OpTy<'tcx, M::PointerTag>,
373         index: u64,
374     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
375         if let Ok(index) = usize::try_from(index) {
376             // We can just treat this as a field.
377             self.operand_field(op, index)
378         } else {
379             // Indexing into a big array. This must be an mplace.
380             let mplace = op.assert_mem_place(self);
381             Ok(self.mplace_index(mplace, index)?.into())
382         }
383     }
384
385     pub fn operand_downcast(
386         &self,
387         op: OpTy<'tcx, M::PointerTag>,
388         variant: VariantIdx,
389     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
390         // Downcasts only change the layout
391         Ok(match op.try_as_mplace(self) {
392             Ok(mplace) => self.mplace_downcast(mplace, variant)?.into(),
393             Err(..) => {
394                 let layout = op.layout.for_variant(self, variant);
395                 OpTy { layout, ..op }
396             }
397         })
398     }
399
400     pub fn operand_projection(
401         &self,
402         base: OpTy<'tcx, M::PointerTag>,
403         proj_elem: &mir::PlaceElem<'tcx>,
404     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
405         use rustc_middle::mir::ProjectionElem::*;
406         Ok(match *proj_elem {
407             Field(field, _) => self.operand_field(base, field.index())?,
408             Downcast(_, variant) => self.operand_downcast(base, variant)?,
409             Deref => self.deref_operand(base)?.into(),
410             Subslice { .. } | ConstantIndex { .. } | Index(_) => {
411                 // The rest should only occur as mplace, we do not use Immediates for types
412                 // allowing such operations.  This matches place_projection forcing an allocation.
413                 let mplace = base.assert_mem_place(self);
414                 self.mplace_projection(mplace, proj_elem)?.into()
415             }
416         })
417     }
418
419     /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
420     pub fn access_local(
421         &self,
422         frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
423         local: mir::Local,
424         layout: Option<TyAndLayout<'tcx>>,
425     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
426         let layout = self.layout_of_local(frame, local, layout)?;
427         let op = if layout.is_zst() {
428             // Do not read from ZST, they might not be initialized
429             Operand::Immediate(Scalar::zst().into())
430         } else {
431             M::access_local(&self, frame, local)?
432         };
433         Ok(OpTy { op, layout })
434     }
435
436     /// Every place can be read from, so we can turn them into an operand.
437     /// This will definitely return `Indirect` if the place is a `Ptr`, i.e., this
438     /// will never actually read from memory.
439     #[inline(always)]
440     pub fn place_to_op(
441         &self,
442         place: PlaceTy<'tcx, M::PointerTag>,
443     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
444         let op = match *place {
445             Place::Ptr(mplace) => Operand::Indirect(mplace),
446             Place::Local { frame, local } => {
447                 *self.access_local(&self.stack()[frame], local, None)?
448             }
449         };
450         Ok(OpTy { op, layout: place.layout })
451     }
452
453     // Evaluate a place with the goal of reading from it.  This lets us sometimes
454     // avoid allocations.
455     pub fn eval_place_to_op(
456         &self,
457         place: mir::Place<'tcx>,
458         layout: Option<TyAndLayout<'tcx>>,
459     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
460         // Do not use the layout passed in as argument if the base we are looking at
461         // here is not the entire place.
462         let layout = if place.projection.is_empty() { layout } else { None };
463
464         let base_op = self.access_local(self.frame(), place.local, layout)?;
465
466         let op = place
467             .projection
468             .iter()
469             .try_fold(base_op, |op, elem| self.operand_projection(op, elem))?;
470
471         trace!("eval_place_to_op: got {:?}", *op);
472         Ok(op)
473     }
474
475     /// Evaluate the operand, returning a place where you can then find the data.
476     /// If you already know the layout, you can save two table lookups
477     /// by passing it in here.
478     pub fn eval_operand(
479         &self,
480         mir_op: &mir::Operand<'tcx>,
481         layout: Option<TyAndLayout<'tcx>>,
482     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
483         use rustc_middle::mir::Operand::*;
484         let op = match *mir_op {
485             // FIXME: do some more logic on `move` to invalidate the old location
486             Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?,
487
488             Constant(ref constant) => {
489                 let val =
490                     self.subst_from_current_frame_and_normalize_erasing_regions(constant.literal);
491                 self.eval_const_to_op(val, layout)?
492             }
493         };
494         trace!("{:?}: {:?}", mir_op, *op);
495         Ok(op)
496     }
497
498     /// Evaluate a bunch of operands at once
499     pub(super) fn eval_operands(
500         &self,
501         ops: &[mir::Operand<'tcx>],
502     ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
503         ops.iter().map(|op| self.eval_operand(op, None)).collect()
504     }
505
506     // Used when the miri-engine runs into a constant and for extracting information from constants
507     // in patterns via the `const_eval` module
508     /// The `val` and `layout` are assumed to already be in our interpreter
509     /// "universe" (param_env).
510     crate fn eval_const_to_op(
511         &self,
512         val: &ty::Const<'tcx>,
513         layout: Option<TyAndLayout<'tcx>>,
514     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
515         let tag_scalar = |scalar| match scalar {
516             Scalar::Ptr(ptr) => Scalar::Ptr(self.tag_global_base_pointer(ptr)),
517             Scalar::Raw { data, size } => Scalar::Raw { data, size },
518         };
519         // Early-return cases.
520         let val_val = match val.val {
521             ty::ConstKind::Param(_) => throw_inval!(TooGeneric),
522             ty::ConstKind::Error => throw_inval!(TypeckError(ErrorReported)),
523             ty::ConstKind::Unevaluated(def_id, substs, promoted) => {
524                 let instance = self.resolve(def_id, substs)?;
525                 // We use `const_eval` here and `const_eval_raw` elsewhere in mir interpretation.
526                 // The reason we use `const_eval_raw` everywhere else is to prevent cycles during
527                 // validation, because validation automatically reads through any references, thus
528                 // potentially requiring the current static to be evaluated again. This is not a
529                 // problem here, because we are building an operand which means an actual read is
530                 // happening.
531                 //
532                 // The machine callback `adjust_global_const` below is guaranteed to
533                 // be called for all constants because `const_eval` calls
534                 // `eval_const_to_op` recursively.
535                 return Ok(self.const_eval(GlobalId { instance, promoted }, val.ty)?);
536             }
537             ty::ConstKind::Infer(..)
538             | ty::ConstKind::Bound(..)
539             | ty::ConstKind::Placeholder(..) => {
540                 bug!("eval_const_to_op: Unexpected ConstKind {:?}", val)
541             }
542             ty::ConstKind::Value(val_val) => val_val,
543         };
544         // This call allows the machine to create fresh allocation ids for
545         // thread-local statics (see the `adjust_global_const` function
546         // documentation).
547         let val_val = M::adjust_global_const(self, val_val)?;
548         // Other cases need layout.
549         let layout = from_known_layout(self.tcx, layout, || self.layout_of(val.ty))?;
550         let op = match val_val {
551             ConstValue::ByRef { alloc, offset } => {
552                 let id = self.tcx.alloc_map.lock().create_memory_alloc(alloc);
553                 // We rely on mutability being set correctly in that allocation to prevent writes
554                 // where none should happen.
555                 let ptr = self.tag_global_base_pointer(Pointer::new(id, offset));
556                 Operand::Indirect(MemPlace::from_ptr(ptr, layout.align.abi))
557             }
558             ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x).into()),
559             ConstValue::Slice { data, start, end } => {
560                 // We rely on mutability being set correctly in `data` to prevent writes
561                 // where none should happen.
562                 let ptr = Pointer::new(
563                     self.tcx.alloc_map.lock().create_memory_alloc(data),
564                     Size::from_bytes(start), // offset: `start`
565                 );
566                 Operand::Immediate(Immediate::new_slice(
567                     self.tag_global_base_pointer(ptr).into(),
568                     u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start`
569                     self,
570                 ))
571             }
572         };
573         Ok(OpTy { op, layout })
574     }
575
576     /// Read discriminant, return the runtime value as well as the variant index.
577     pub fn read_discriminant(
578         &self,
579         rval: OpTy<'tcx, M::PointerTag>,
580     ) -> InterpResult<'tcx, (u128, VariantIdx)> {
581         trace!("read_discriminant_value {:#?}", rval.layout);
582
583         let (discr_layout, discr_kind, discr_index) = match rval.layout.variants {
584             Variants::Single { index } => {
585                 let discr_val = rval
586                     .layout
587                     .ty
588                     .discriminant_for_variant(*self.tcx, index)
589                     .map_or(u128::from(index.as_u32()), |discr| discr.val);
590                 return Ok((discr_val, index));
591             }
592             Variants::Multiple { discr: ref discr_layout, ref discr_kind, discr_index, .. } => {
593                 (discr_layout, discr_kind, discr_index)
594             }
595         };
596
597         // read raw discriminant value
598         let discr_op = self.operand_field(rval, discr_index)?;
599         let discr_val = self.read_immediate(discr_op)?;
600         let raw_discr = discr_val.to_scalar_or_undef();
601         trace!("discr value: {:?}", raw_discr);
602         // post-process
603         Ok(match *discr_kind {
604             DiscriminantKind::Tag => {
605                 let bits_discr = raw_discr
606                     .not_undef()
607                     .and_then(|raw_discr| self.force_bits(raw_discr, discr_val.layout.size))
608                     .map_err(|_| err_ub!(InvalidDiscriminant(raw_discr.erase_tag())))?;
609                 let real_discr = if discr_val.layout.abi.is_signed() {
610                     // going from layout tag type to typeck discriminant type
611                     // requires first sign extending with the discriminant layout
612                     let sexted = sign_extend(bits_discr, discr_val.layout.size);
613                     // and then zeroing with the typeck discriminant type
614                     let discr_ty = rval
615                         .layout
616                         .ty
617                         .ty_adt_def()
618                         .expect("tagged layout corresponds to adt")
619                         .repr
620                         .discr_type();
621                     let size = Integer::from_attr(self, discr_ty).size();
622                     truncate(sexted, size)
623                 } else {
624                     bits_discr
625                 };
626                 // Make sure we catch invalid discriminants
627                 let index = match rval.layout.ty.kind {
628                     ty::Adt(adt, _) => {
629                         adt.discriminants(self.tcx.tcx).find(|(_, var)| var.val == real_discr)
630                     }
631                     ty::Generator(def_id, substs, _) => {
632                         let substs = substs.as_generator();
633                         substs
634                             .discriminants(def_id, self.tcx.tcx)
635                             .find(|(_, var)| var.val == real_discr)
636                     }
637                     _ => bug!("tagged layout for non-adt non-generator"),
638                 }
639                 .ok_or_else(|| err_ub!(InvalidDiscriminant(raw_discr.erase_tag())))?;
640                 (real_discr, index.0)
641             }
642             DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start } => {
643                 let variants_start = niche_variants.start().as_u32();
644                 let variants_end = niche_variants.end().as_u32();
645                 let raw_discr = raw_discr
646                     .not_undef()
647                     .map_err(|_| err_ub!(InvalidDiscriminant(ScalarMaybeUninit::Uninit)))?;
648                 match raw_discr.to_bits_or_ptr(discr_val.layout.size, self) {
649                     Err(ptr) => {
650                         // The niche must be just 0 (which an inbounds pointer value never is)
651                         let ptr_valid = niche_start == 0
652                             && variants_start == variants_end
653                             && !self.memory.ptr_may_be_null(ptr);
654                         if !ptr_valid {
655                             throw_ub!(InvalidDiscriminant(raw_discr.erase_tag().into()))
656                         }
657                         (u128::from(dataful_variant.as_u32()), dataful_variant)
658                     }
659                     Ok(raw_discr) => {
660                         // We need to use machine arithmetic to get the relative variant idx:
661                         // variant_index_relative = discr_val - niche_start_val
662                         let discr_layout =
663                             self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?;
664                         let discr_val = ImmTy::from_uint(raw_discr, discr_layout);
665                         let niche_start_val = ImmTy::from_uint(niche_start, discr_layout);
666                         let variant_index_relative_val =
667                             self.binary_op(mir::BinOp::Sub, discr_val, niche_start_val)?;
668                         let variant_index_relative = variant_index_relative_val
669                             .to_scalar()?
670                             .assert_bits(discr_val.layout.size);
671                         // Check if this is in the range that indicates an actual discriminant.
672                         if variant_index_relative <= u128::from(variants_end - variants_start) {
673                             let variant_index_relative = u32::try_from(variant_index_relative)
674                                 .expect("we checked that this fits into a u32");
675                             // Then computing the absolute variant idx should not overflow any more.
676                             let variant_index = variants_start
677                                 .checked_add(variant_index_relative)
678                                 .expect("overflow computing absolute variant idx");
679                             let variants_len = rval
680                                 .layout
681                                 .ty
682                                 .ty_adt_def()
683                                 .expect("tagged layout for non adt")
684                                 .variants
685                                 .len();
686                             assert!(usize::try_from(variant_index).unwrap() < variants_len);
687                             (u128::from(variant_index), VariantIdx::from_u32(variant_index))
688                         } else {
689                             (u128::from(dataful_variant.as_u32()), dataful_variant)
690                         }
691                     }
692                 }
693             }
694         })
695     }
696 }