]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/operand.rs
979595d6c00095b5b40631aad1c199bc02abac18
[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;
5
6 use rustc::{mir, ty};
7 use rustc::ty::layout::{self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt, VariantIdx};
8
9 use rustc::mir::interpret::{
10     GlobalId, AllocId, InboundsCheck,
11     ConstValue, Pointer, Scalar,
12     EvalResult, EvalErrorKind,
13     sign_extend, truncate,
14 };
15 use super::{
16     EvalContext, Machine,
17     MemPlace, MPlaceTy, PlaceTy, Place, MemoryKind,
18 };
19 pub use rustc::mir::interpret::ScalarMaybeUndef;
20
21 /// A `Value` represents a single immediate self-contained Rust value.
22 ///
23 /// For optimization of a few very common cases, there is also a representation for a pair of
24 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
25 /// operations and fat pointers. This idea was taken from rustc's codegen.
26 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
27 /// defined on `Immediate`, and do not have to work with a `Place`.
28 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
29 pub enum Immediate<Tag=(), Id=AllocId> {
30     Scalar(ScalarMaybeUndef<Tag, Id>),
31     ScalarPair(ScalarMaybeUndef<Tag, Id>, ScalarMaybeUndef<Tag, Id>),
32 }
33
34 impl Immediate {
35     #[inline]
36     pub fn with_default_tag<Tag>(self) -> Immediate<Tag>
37         where Tag: Default
38     {
39         match self {
40             Immediate::Scalar(x) => Immediate::Scalar(x.with_default_tag()),
41             Immediate::ScalarPair(x, y) =>
42                 Immediate::ScalarPair(x.with_default_tag(), y.with_default_tag()),
43         }
44     }
45 }
46
47 impl<'tcx, Tag> Immediate<Tag> {
48     #[inline]
49     pub fn from_scalar(val: Scalar<Tag>) -> Self {
50         Immediate::Scalar(ScalarMaybeUndef::Scalar(val))
51     }
52
53     #[inline]
54     pub fn erase_tag(self) -> Immediate
55     {
56         match self {
57             Immediate::Scalar(x) => Immediate::Scalar(x.erase_tag()),
58             Immediate::ScalarPair(x, y) =>
59                 Immediate::ScalarPair(x.erase_tag(), y.erase_tag()),
60         }
61     }
62
63     pub fn new_slice(
64         val: Scalar<Tag>,
65         len: u64,
66         cx: &impl HasDataLayout
67     ) -> Self {
68         Immediate::ScalarPair(
69             val.into(),
70             Scalar::from_uint(len, cx.data_layout().pointer_size).into(),
71         )
72     }
73
74     pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>) -> Self {
75         Immediate::ScalarPair(val.into(), Scalar::Ptr(vtable).into())
76     }
77
78     #[inline]
79     pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef<Tag> {
80         match self {
81             Immediate::Scalar(val) => val,
82             Immediate::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"),
83         }
84     }
85
86     #[inline]
87     pub fn to_scalar(self) -> EvalResult<'tcx, Scalar<Tag>> {
88         self.to_scalar_or_undef().not_undef()
89     }
90
91     #[inline]
92     pub fn to_scalar_pair(self) -> EvalResult<'tcx, (Scalar<Tag>, Scalar<Tag>)> {
93         match self {
94             Immediate::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"),
95             Immediate::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?))
96         }
97     }
98
99     /// Converts the immediate into a pointer (or a pointer-sized integer).
100     /// Throws away the second half of a ScalarPair!
101     #[inline]
102     pub fn to_scalar_ptr(self) -> EvalResult<'tcx, Scalar<Tag>> {
103         match self {
104             Immediate::Scalar(ptr) |
105             Immediate::ScalarPair(ptr, _) => ptr.not_undef(),
106         }
107     }
108
109     /// Converts the value into its metadata.
110     /// Throws away the first half of a ScalarPair!
111     #[inline]
112     pub fn to_meta(self) -> EvalResult<'tcx, Option<Scalar<Tag>>> {
113         Ok(match self {
114             Immediate::Scalar(_) => None,
115             Immediate::ScalarPair(_, meta) => Some(meta.not_undef()?),
116         })
117     }
118 }
119
120 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
121 // as input for binary and cast operations.
122 #[derive(Copy, Clone, Debug)]
123 pub struct ImmTy<'tcx, Tag=()> {
124     pub imm: Immediate<Tag>,
125     pub layout: TyLayout<'tcx>,
126 }
127
128 impl<'tcx, Tag> ::std::ops::Deref for ImmTy<'tcx, Tag> {
129     type Target = Immediate<Tag>;
130     #[inline(always)]
131     fn deref(&self) -> &Immediate<Tag> {
132         &self.imm
133     }
134 }
135
136 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
137 /// or still in memory. The latter is an optimization, to delay reading that chunk of
138 /// memory and to avoid having to store arbitrary-sized data here.
139 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
140 pub enum Operand<Tag=(), Id=AllocId> {
141     Immediate(Immediate<Tag, Id>),
142     Indirect(MemPlace<Tag, Id>),
143 }
144
145 impl Operand {
146     #[inline]
147     pub fn with_default_tag<Tag>(self) -> Operand<Tag>
148         where Tag: Default
149     {
150         match self {
151             Operand::Immediate(x) => Operand::Immediate(x.with_default_tag()),
152             Operand::Indirect(x) => Operand::Indirect(x.with_default_tag()),
153         }
154     }
155 }
156
157 impl<Tag> Operand<Tag> {
158     #[inline]
159     pub fn erase_tag(self) -> Operand
160     {
161         match self {
162             Operand::Immediate(x) => Operand::Immediate(x.erase_tag()),
163             Operand::Indirect(x) => Operand::Indirect(x.erase_tag()),
164         }
165     }
166
167     #[inline]
168     pub fn to_mem_place(self) -> MemPlace<Tag>
169         where Tag: ::std::fmt::Debug
170     {
171         match self {
172             Operand::Indirect(mplace) => mplace,
173             _ => bug!("to_mem_place: expected Operand::Indirect, got {:?}", self),
174
175         }
176     }
177
178     #[inline]
179     pub fn to_immediate(self) -> Immediate<Tag>
180         where Tag: ::std::fmt::Debug
181     {
182         match self {
183             Operand::Immediate(imm) => imm,
184             _ => bug!("to_immediate: expected Operand::Immediate, got {:?}", self),
185
186         }
187     }
188 }
189
190 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
191 pub struct OpTy<'tcx, Tag=()> {
192     op: Operand<Tag>,
193     pub layout: TyLayout<'tcx>,
194 }
195
196 impl<'tcx, Tag> ::std::ops::Deref for OpTy<'tcx, Tag> {
197     type Target = Operand<Tag>;
198     #[inline(always)]
199     fn deref(&self) -> &Operand<Tag> {
200         &self.op
201     }
202 }
203
204 impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
205     #[inline(always)]
206     fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
207         OpTy {
208             op: Operand::Indirect(*mplace),
209             layout: mplace.layout
210         }
211     }
212 }
213
214 impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
215     #[inline(always)]
216     fn from(val: ImmTy<'tcx, Tag>) -> Self {
217         OpTy {
218             op: Operand::Immediate(val.imm),
219             layout: val.layout
220         }
221     }
222 }
223
224 impl<'tcx, Tag: Copy> ImmTy<'tcx, Tag>
225 {
226     #[inline]
227     pub fn from_scalar(val: Scalar<Tag>, layout: TyLayout<'tcx>) -> Self {
228         ImmTy { imm: Immediate::from_scalar(val), layout }
229     }
230
231     #[inline]
232     pub fn to_bits(self) -> EvalResult<'tcx, u128> {
233         self.to_scalar()?.to_bits(self.layout.size)
234     }
235 }
236
237 impl<'tcx, Tag> OpTy<'tcx, Tag>
238 {
239     #[inline]
240     pub fn erase_tag(self) -> OpTy<'tcx>
241     {
242         OpTy {
243             op: self.op.erase_tag(),
244             layout: self.layout,
245         }
246     }
247 }
248
249 // Use the existing layout if given (but sanity check in debug mode),
250 // or compute the layout.
251 #[inline(always)]
252 pub(super) fn from_known_layout<'tcx>(
253     layout: Option<TyLayout<'tcx>>,
254     compute: impl FnOnce() -> EvalResult<'tcx, TyLayout<'tcx>>
255 ) -> EvalResult<'tcx, TyLayout<'tcx>> {
256     match layout {
257         None => compute(),
258         Some(layout) => {
259             if cfg!(debug_assertions) {
260                 let layout2 = compute()?;
261                 assert_eq!(layout.details, layout2.details,
262                     "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
263                     layout.ty, layout2.ty);
264             }
265             Ok(layout)
266         }
267     }
268 }
269
270 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
271     /// Try reading an immediate in memory; this is interesting particularly for ScalarPair.
272     /// Returns `None` if the layout does not permit loading this as a value.
273     fn try_read_immediate_from_mplace(
274         &self,
275         mplace: MPlaceTy<'tcx, M::PointerTag>,
276     ) -> EvalResult<'tcx, Option<Immediate<M::PointerTag>>> {
277         if mplace.layout.is_unsized() {
278             // Don't touch unsized
279             return Ok(None);
280         }
281         let (ptr, ptr_align) = mplace.to_scalar_ptr_align();
282
283         if mplace.layout.is_zst() {
284             // Not all ZSTs have a layout we would handle below, so just short-circuit them
285             // all here.
286             self.memory.check_align(ptr, ptr_align)?;
287             return Ok(Some(Immediate::Scalar(Scalar::zst().into())));
288         }
289
290         // check for integer pointers before alignment to report better errors
291         let ptr = ptr.to_ptr()?;
292         self.memory.check_align(ptr.into(), ptr_align)?;
293         match mplace.layout.abi {
294             layout::Abi::Scalar(..) => {
295                 let scalar = self.memory
296                     .get(ptr.alloc_id)?
297                     .read_scalar(self, ptr, mplace.layout.size)?;
298                 Ok(Some(Immediate::Scalar(scalar)))
299             }
300             layout::Abi::ScalarPair(ref a, ref b) => {
301                 let (a, b) = (&a.value, &b.value);
302                 let (a_size, b_size) = (a.size(self), b.size(self));
303                 let a_ptr = ptr;
304                 let b_offset = a_size.align_to(b.align(self).abi);
305                 assert!(b_offset.bytes() > 0); // we later use the offset to test which field to use
306                 let b_ptr = ptr.offset(b_offset, self)?;
307                 let a_val = self.memory
308                     .get(ptr.alloc_id)?
309                     .read_scalar(self, a_ptr, a_size)?;
310                 let b_align = ptr_align.restrict_for_offset(b_offset);
311                 self.memory.check_align(b_ptr.into(), b_align)?;
312                 let b_val = self.memory
313                     .get(ptr.alloc_id)?
314                     .read_scalar(self, b_ptr, b_size)?;
315                 Ok(Some(Immediate::ScalarPair(a_val, b_val)))
316             }
317             _ => Ok(None),
318         }
319     }
320
321     /// Try returning an immediate for the operand.
322     /// If the layout does not permit loading this as an immediate, return where in memory
323     /// we can find the data.
324     /// Note that for a given layout, this operation will either always fail or always
325     /// succeed!  Whether it succeeds depends on whether the layout can be represented
326     /// in a `Immediate`, not on which data is stored there currently.
327     pub(super) fn try_read_immediate(
328         &self,
329         src: OpTy<'tcx, M::PointerTag>,
330     ) -> EvalResult<'tcx, Result<Immediate<M::PointerTag>, MemPlace<M::PointerTag>>> {
331         Ok(match src.try_as_mplace() {
332             Ok(mplace) => {
333                 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
334                     Ok(val)
335                 } else {
336                     Err(*mplace)
337                 }
338             },
339             Err(val) => Ok(val),
340         })
341     }
342
343     /// Read an immediate from a place, asserting that that is possible with the given layout.
344     #[inline(always)]
345     pub fn read_immediate(
346         &self,
347         op: OpTy<'tcx, M::PointerTag>
348     ) -> EvalResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
349         if let Ok(imm) = self.try_read_immediate(op)? {
350             Ok(ImmTy { imm, layout: op.layout })
351         } else {
352             bug!("primitive read failed for type: {:?}", op.layout.ty);
353         }
354     }
355
356     /// Read a scalar from a place
357     pub fn read_scalar(
358         &self,
359         op: OpTy<'tcx, M::PointerTag>
360     ) -> EvalResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
361         Ok(self.read_immediate(op)?.to_scalar_or_undef())
362     }
363
364     // Turn the MPlace into a string (must already be dereferenced!)
365     pub fn read_str(
366         &self,
367         mplace: MPlaceTy<'tcx, M::PointerTag>,
368     ) -> EvalResult<'tcx, &str> {
369         let len = mplace.len(self)?;
370         let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
371         let str = ::std::str::from_utf8(bytes)
372             .map_err(|err| EvalErrorKind::ValidationFailure(err.to_string()))?;
373         Ok(str)
374     }
375
376     pub fn uninit_operand(
377         &mut self,
378         layout: TyLayout<'tcx>
379     ) -> EvalResult<'tcx, Operand<M::PointerTag>> {
380         // This decides which types we will use the Immediate optimization for, and hence should
381         // match what `try_read_immediate` and `eval_place_to_op` support.
382         if layout.is_zst() {
383             return Ok(Operand::Immediate(Immediate::Scalar(Scalar::zst().into())));
384         }
385
386         Ok(match layout.abi {
387             layout::Abi::Scalar(..) =>
388                 Operand::Immediate(Immediate::Scalar(ScalarMaybeUndef::Undef)),
389             layout::Abi::ScalarPair(..) =>
390                 Operand::Immediate(Immediate::ScalarPair(
391                     ScalarMaybeUndef::Undef,
392                     ScalarMaybeUndef::Undef,
393                 )),
394             _ => {
395                 trace!("Forcing allocation for local of type {:?}", layout.ty);
396                 Operand::Indirect(
397                     *self.allocate(layout, MemoryKind::Stack)
398                 )
399             }
400         })
401     }
402
403     /// Projection functions
404     pub fn operand_field(
405         &self,
406         op: OpTy<'tcx, M::PointerTag>,
407         field: u64,
408     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
409         let base = match op.try_as_mplace() {
410             Ok(mplace) => {
411                 // The easy case
412                 let field = self.mplace_field(mplace, field)?;
413                 return Ok(field.into());
414             },
415             Err(value) => value
416         };
417
418         let field = field.try_into().unwrap();
419         let field_layout = op.layout.field(self, field)?;
420         if field_layout.is_zst() {
421             let immediate = Immediate::Scalar(Scalar::zst().into());
422             return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
423         }
424         let offset = op.layout.fields.offset(field);
425         let immediate = match base {
426             // the field covers the entire type
427             _ if offset.bytes() == 0 && field_layout.size == op.layout.size => base,
428             // extract fields from types with `ScalarPair` ABI
429             Immediate::ScalarPair(a, b) => {
430                 let val = if offset.bytes() == 0 { a } else { b };
431                 Immediate::Scalar(val)
432             },
433             Immediate::Scalar(val) =>
434                 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
435         };
436         Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
437     }
438
439     pub fn operand_downcast(
440         &self,
441         op: OpTy<'tcx, M::PointerTag>,
442         variant: VariantIdx,
443     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
444         // Downcasts only change the layout
445         Ok(match op.try_as_mplace() {
446             Ok(mplace) => {
447                 self.mplace_downcast(mplace, variant)?.into()
448             },
449             Err(..) => {
450                 let layout = op.layout.for_variant(self, variant);
451                 OpTy { layout, ..op }
452             }
453         })
454     }
455
456     pub fn operand_projection(
457         &self,
458         base: OpTy<'tcx, M::PointerTag>,
459         proj_elem: &mir::PlaceElem<'tcx>,
460     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
461         use rustc::mir::ProjectionElem::*;
462         Ok(match *proj_elem {
463             Field(field, _) => self.operand_field(base, field.index() as u64)?,
464             Downcast(_, variant) => self.operand_downcast(base, variant)?,
465             Deref => self.deref_operand(base)?.into(),
466             Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
467                 OpTy {
468                     op: Operand::Immediate(Immediate::Scalar(Scalar::zst().into())),
469                     // the actual index doesn't matter, so we just pick a convenient one like 0
470                     layout: base.layout.field(self, 0)?,
471                 }
472             } else {
473                 // The rest should only occur as mplace, we do not use Immediates for types
474                 // allowing such operations.  This matches place_projection forcing an allocation.
475                 let mplace = base.to_mem_place();
476                 self.mplace_projection(mplace, proj_elem)?.into()
477             }
478         })
479     }
480
481     /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
482     pub fn access_local(
483         &self,
484         frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
485         local: mir::Local,
486         layout: Option<TyLayout<'tcx>>,
487     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
488         assert_ne!(local, mir::RETURN_PLACE);
489         let op = *frame.locals[local].access()?;
490         let layout = self.layout_of_local(frame, local, layout)?;
491         Ok(OpTy { op, layout })
492     }
493
494     /// Every place can be read from, so we can turm them into an operand
495     #[inline(always)]
496     pub fn place_to_op(
497         &self,
498         place: PlaceTy<'tcx, M::PointerTag>
499     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
500         let op = match *place {
501             Place::Ptr(mplace) => {
502                 Operand::Indirect(mplace)
503             }
504             Place::Local { frame, local } =>
505                 *self.stack[frame].locals[local].access()?
506         };
507         Ok(OpTy { op, layout: place.layout })
508     }
509
510     // Evaluate a place with the goal of reading from it.  This lets us sometimes
511     // avoid allocations.
512     pub(super) fn eval_place_to_op(
513         &self,
514         mir_place: &mir::Place<'tcx>,
515         layout: Option<TyLayout<'tcx>>,
516     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
517         use rustc::mir::Place::*;
518         use rustc::mir::PlaceBase;
519         let op = match *mir_place {
520             Base(PlaceBase::Local(mir::RETURN_PLACE)) => return err!(ReadFromReturnPointer),
521             Base(PlaceBase::Local(local)) => self.access_local(self.frame(), local, layout)?,
522
523             Projection(ref proj) => {
524                 let op = self.eval_place_to_op(&proj.base, None)?;
525                 self.operand_projection(op, &proj.elem)?
526             }
527
528             _ => self.eval_place_to_mplace(mir_place)?.into(),
529         };
530
531         trace!("eval_place_to_op: got {:?}", *op);
532         Ok(op)
533     }
534
535     /// Evaluate the operand, returning a place where you can then find the data.
536     /// if you already know the layout, you can save two some table lookups
537     /// by passing it in here.
538     pub fn eval_operand(
539         &self,
540         mir_op: &mir::Operand<'tcx>,
541         layout: Option<TyLayout<'tcx>>,
542     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
543         use rustc::mir::Operand::*;
544         let op = match *mir_op {
545             // FIXME: do some more logic on `move` to invalidate the old location
546             Copy(ref place) |
547             Move(ref place) =>
548                 self.eval_place_to_op(place, layout)?,
549
550             Constant(ref constant) => self.eval_lazy_const_to_op(*constant.literal, layout)?,
551         };
552         trace!("{:?}: {:?}", mir_op, *op);
553         Ok(op)
554     }
555
556     /// Evaluate a bunch of operands at once
557     pub(super) fn eval_operands(
558         &self,
559         ops: &[mir::Operand<'tcx>],
560     ) -> EvalResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
561         ops.into_iter()
562             .map(|op| self.eval_operand(op, None))
563             .collect()
564     }
565
566     // Used when Miri runs into a constant, and by const propagation.
567     crate fn eval_lazy_const_to_op(
568         &self,
569         val: ty::LazyConst<'tcx>,
570         layout: Option<TyLayout<'tcx>>,
571     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
572         trace!("const_to_op: {:?}", val);
573         match val {
574             ty::LazyConst::Unevaluated(def_id, substs) => {
575                 let instance = self.resolve(def_id, substs)?;
576                 return Ok(OpTy::from(self.const_eval_raw(GlobalId {
577                     instance,
578                     promoted: None,
579                 })?));
580             },
581             ty::LazyConst::Evaluated(c) => self.const_to_op(c, layout),
582         }
583     }
584
585     // Used when the miri-engine runs into a constant and for extracting information from constants
586     // in patterns via the `const_eval` module
587     crate fn const_to_op(
588         &self,
589         val: ty::Const<'tcx>,
590         layout: Option<TyLayout<'tcx>>,
591     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
592         let layout = from_known_layout(layout, || {
593             let ty = self.monomorphize(val.ty)?;
594             self.layout_of(ty)
595         })?;
596         let op = match val.val {
597             ConstValue::ByRef(ptr, alloc) => {
598                 // We rely on mutability being set correctly in that allocation to prevent writes
599                 // where none should happen -- and for `static mut`, we copy on demand anyway.
600                 Operand::Indirect(
601                     MemPlace::from_ptr(ptr, alloc.align)
602                 ).with_default_tag()
603             },
604             ConstValue::Slice(a, b) =>
605                 Operand::Immediate(Immediate::ScalarPair(
606                     a.into(),
607                     Scalar::from_uint(b, self.tcx.data_layout.pointer_size).into(),
608                 )).with_default_tag(),
609             ConstValue::Scalar(x) =>
610                 Operand::Immediate(Immediate::Scalar(x.into())).with_default_tag(),
611         };
612         Ok(OpTy {
613             op,
614             layout,
615         })
616     }
617
618     /// Read discriminant, return the runtime value as well as the variant index.
619     pub fn read_discriminant(
620         &self,
621         rval: OpTy<'tcx, M::PointerTag>,
622     ) -> EvalResult<'tcx, (u128, VariantIdx)> {
623         trace!("read_discriminant_value {:#?}", rval.layout);
624
625         match rval.layout.variants {
626             layout::Variants::Single { index } => {
627                 let discr_val = rval.layout.ty.ty_adt_def().map_or(
628                     index.as_u32() as u128,
629                     |def| def.discriminant_for_variant(*self.tcx, index).val);
630                 return Ok((discr_val, index));
631             }
632             layout::Variants::Tagged { .. } |
633             layout::Variants::NicheFilling { .. } => {},
634         }
635         // read raw discriminant value
636         let discr_op = self.operand_field(rval, 0)?;
637         let discr_val = self.read_immediate(discr_op)?;
638         let raw_discr = discr_val.to_scalar_or_undef();
639         trace!("discr value: {:?}", raw_discr);
640         // post-process
641         Ok(match rval.layout.variants {
642             layout::Variants::Single { .. } => bug!(),
643             layout::Variants::Tagged { .. } => {
644                 let bits_discr = match raw_discr.to_bits(discr_val.layout.size) {
645                     Ok(raw_discr) => raw_discr,
646                     Err(_) => return err!(InvalidDiscriminant(raw_discr.erase_tag())),
647                 };
648                 let real_discr = if discr_val.layout.ty.is_signed() {
649                     // going from layout tag type to typeck discriminant type
650                     // requires first sign extending with the layout discriminant
651                     let sexted = sign_extend(bits_discr, discr_val.layout.size) as i128;
652                     // and then zeroing with the typeck discriminant type
653                     let discr_ty = rval.layout.ty
654                         .ty_adt_def().expect("tagged layout corresponds to adt")
655                         .repr
656                         .discr_type();
657                     let size = layout::Integer::from_attr(self, discr_ty).size();
658                     let truncatee = sexted as u128;
659                     truncate(truncatee, size)
660                 } else {
661                     bits_discr
662                 };
663                 // Make sure we catch invalid discriminants
664                 let index = rval.layout.ty
665                     .ty_adt_def()
666                     .expect("tagged layout for non adt")
667                     .discriminants(self.tcx.tcx)
668                     .find(|(_, var)| var.val == real_discr)
669                     .ok_or_else(|| EvalErrorKind::InvalidDiscriminant(raw_discr.erase_tag()))?;
670                 (real_discr, index.0)
671             },
672             layout::Variants::NicheFilling {
673                 dataful_variant,
674                 ref niche_variants,
675                 niche_start,
676                 ..
677             } => {
678                 let variants_start = niche_variants.start().as_u32() as u128;
679                 let variants_end = niche_variants.end().as_u32() as u128;
680                 match raw_discr {
681                     ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) => {
682                         // The niche must be just 0 (which an inbounds pointer value never is)
683                         let ptr_valid = niche_start == 0 && variants_start == variants_end &&
684                             self.memory.check_bounds_ptr(ptr, InboundsCheck::MaybeDead).is_ok();
685                         if !ptr_valid {
686                             return err!(InvalidDiscriminant(raw_discr.erase_tag()));
687                         }
688                         (dataful_variant.as_u32() as u128, dataful_variant)
689                     },
690                     ScalarMaybeUndef::Scalar(Scalar::Bits { bits: raw_discr, size }) => {
691                         assert_eq!(size as u64, discr_val.layout.size.bytes());
692                         let adjusted_discr = raw_discr.wrapping_sub(niche_start)
693                             .wrapping_add(variants_start);
694                         if variants_start <= adjusted_discr && adjusted_discr <= variants_end {
695                             let index = adjusted_discr as usize;
696                             assert_eq!(index as u128, adjusted_discr);
697                             assert!(index < rval.layout.ty
698                                 .ty_adt_def()
699                                 .expect("tagged layout for non adt")
700                                 .variants.len());
701                             (adjusted_discr, VariantIdx::from_usize(index))
702                         } else {
703                             (dataful_variant.as_u32() as u128, dataful_variant)
704                         }
705                     },
706                     ScalarMaybeUndef::Undef =>
707                         return err!(InvalidDiscriminant(ScalarMaybeUndef::Undef)),
708                 }
709             }
710         })
711     }
712 }