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