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