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