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