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