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.
4 use std::convert::TryFrom;
7 use rustc_errors::ErrorReported;
8 use rustc_hir::def::Namespace;
9 use rustc_macros::HashStable;
10 use rustc_middle::ty::layout::{PrimitiveExt, TyAndLayout};
11 use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter, Printer};
12 use rustc_middle::ty::{ConstInt, Ty};
13 use rustc_middle::{mir, ty};
14 use rustc_target::abi::{Abi, HasDataLayout, LayoutOf, Size, TagEncoding};
15 use rustc_target::abi::{VariantIdx, Variants};
18 alloc_range, from_known_layout, mir_assign_valid_types, AllocId, ConstValue, GlobalId,
19 InterpCx, InterpResult, MPlaceTy, Machine, MemPlace, Place, PlaceTy, Pointer, Provenance,
20 Scalar, ScalarMaybeUninit,
23 /// An `Immediate` represents a single immediate self-contained Rust value.
25 /// For optimization of a few very common cases, there is also a representation for a pair of
26 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
27 /// operations and wide pointers. This idea was taken from rustc's codegen.
28 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
29 /// defined on `Immediate`, and do not have to work with a `Place`.
30 #[derive(Copy, Clone, PartialEq, Eq, HashStable, Hash, Debug)]
31 pub enum Immediate<Tag: Provenance = AllocId> {
32 Scalar(ScalarMaybeUninit<Tag>),
33 ScalarPair(ScalarMaybeUninit<Tag>, ScalarMaybeUninit<Tag>),
36 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
37 rustc_data_structures::static_assert_size!(Immediate, 56);
39 impl<Tag: Provenance> From<ScalarMaybeUninit<Tag>> for Immediate<Tag> {
41 fn from(val: ScalarMaybeUninit<Tag>) -> Self {
42 Immediate::Scalar(val)
46 impl<Tag: Provenance> From<Scalar<Tag>> for Immediate<Tag> {
48 fn from(val: Scalar<Tag>) -> Self {
49 Immediate::Scalar(val.into())
53 impl<'tcx, Tag: Provenance> Immediate<Tag> {
54 pub fn from_pointer(p: Pointer<Tag>, cx: &impl HasDataLayout) -> Self {
55 Immediate::Scalar(ScalarMaybeUninit::from_pointer(p, cx))
58 pub fn from_maybe_pointer(p: Pointer<Option<Tag>>, cx: &impl HasDataLayout) -> Self {
59 Immediate::Scalar(ScalarMaybeUninit::from_maybe_pointer(p, cx))
62 pub fn new_slice(val: Scalar<Tag>, len: u64, cx: &impl HasDataLayout) -> Self {
63 Immediate::ScalarPair(val.into(), Scalar::from_machine_usize(len, cx).into())
66 pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>, cx: &impl HasDataLayout) -> Self {
67 Immediate::ScalarPair(val.into(), ScalarMaybeUninit::from_pointer(vtable, cx))
71 pub fn to_scalar_or_uninit(self) -> ScalarMaybeUninit<Tag> {
73 Immediate::Scalar(val) => val,
74 Immediate::ScalarPair(..) => bug!("Got a wide pointer where a scalar was expected"),
79 pub fn to_scalar(self) -> InterpResult<'tcx, Scalar<Tag>> {
80 self.to_scalar_or_uninit().check_init()
84 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
85 // as input for binary and cast operations.
86 #[derive(Copy, Clone, Debug)]
87 pub struct ImmTy<'tcx, Tag: Provenance = AllocId> {
89 pub layout: TyAndLayout<'tcx>,
92 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
93 rustc_data_structures::static_assert_size!(ImmTy<'_>, 72);
95 impl<Tag: Provenance> std::fmt::Display for ImmTy<'tcx, Tag> {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 /// Helper function for printing a scalar to a FmtPrinter
98 fn p<'a, 'tcx, F: std::fmt::Write, Tag: Provenance>(
99 cx: FmtPrinter<'a, 'tcx, F>,
100 s: ScalarMaybeUninit<Tag>,
102 ) -> Result<FmtPrinter<'a, 'tcx, F>, std::fmt::Error> {
104 ScalarMaybeUninit::Scalar(Scalar::Int(int)) => {
105 cx.pretty_print_const_scalar_int(int, ty, true)
107 ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _sz)) => {
108 // Just print the ptr value. `pretty_print_const_scalar_ptr` would also try to
109 // print what is points to, which would fail since it has no access to the local
111 cx.pretty_print_const_pointer(ptr, ty, true)
113 ScalarMaybeUninit::Uninit => cx.typed_value(
115 this.write_str("uninit ")?;
118 |this| this.print_type(ty),
123 ty::tls::with(|tcx| {
125 Immediate::Scalar(s) => {
126 if let Some(ty) = tcx.lift(self.layout.ty) {
127 let cx = FmtPrinter::new(tcx, f, Namespace::ValueNS);
131 write!(f, "{}: {}", s, self.layout.ty)
133 Immediate::ScalarPair(a, b) => {
134 // FIXME(oli-obk): at least print tuples and slices nicely
135 write!(f, "({}, {}): {}", a, b, self.layout.ty,)
142 impl<'tcx, Tag: Provenance> std::ops::Deref for ImmTy<'tcx, Tag> {
143 type Target = Immediate<Tag>;
145 fn deref(&self) -> &Immediate<Tag> {
150 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
151 /// or still in memory. The latter is an optimization, to delay reading that chunk of
152 /// memory and to avoid having to store arbitrary-sized data here.
153 #[derive(Copy, Clone, PartialEq, Eq, HashStable, Hash, Debug)]
154 pub enum Operand<Tag: Provenance = AllocId> {
155 Immediate(Immediate<Tag>),
156 Indirect(MemPlace<Tag>),
159 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
160 pub struct OpTy<'tcx, Tag: Provenance = AllocId> {
161 op: Operand<Tag>, // Keep this private; it helps enforce invariants.
162 pub layout: TyAndLayout<'tcx>,
165 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
166 rustc_data_structures::static_assert_size!(OpTy<'_>, 80);
168 impl<'tcx, Tag: Provenance> std::ops::Deref for OpTy<'tcx, Tag> {
169 type Target = Operand<Tag>;
171 fn deref(&self) -> &Operand<Tag> {
176 impl<'tcx, Tag: Provenance> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
178 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
179 OpTy { op: Operand::Indirect(*mplace), layout: mplace.layout }
183 impl<'tcx, Tag: Provenance> From<&'_ MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
185 fn from(mplace: &MPlaceTy<'tcx, Tag>) -> Self {
186 OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout }
190 impl<'tcx, Tag: Provenance> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
192 fn from(val: ImmTy<'tcx, Tag>) -> Self {
193 OpTy { op: Operand::Immediate(val.imm), layout: val.layout }
197 impl<'tcx, Tag: Provenance> ImmTy<'tcx, Tag> {
199 pub fn from_scalar(val: Scalar<Tag>, layout: TyAndLayout<'tcx>) -> Self {
200 ImmTy { imm: val.into(), layout }
204 pub fn from_immediate(imm: Immediate<Tag>, layout: TyAndLayout<'tcx>) -> Self {
205 ImmTy { imm, layout }
209 pub fn try_from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
210 Some(Self::from_scalar(Scalar::try_from_uint(i, layout.size)?, layout))
213 pub fn from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Self {
214 Self::from_scalar(Scalar::from_uint(i, layout.size), layout)
218 pub fn try_from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
219 Some(Self::from_scalar(Scalar::try_from_int(i, layout.size)?, layout))
223 pub fn from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Self {
224 Self::from_scalar(Scalar::from_int(i, layout.size), layout)
228 pub fn to_const_int(self) -> ConstInt {
229 assert!(self.layout.ty.is_integral());
230 let int = self.to_scalar().expect("to_const_int doesn't work on scalar pairs").assert_int();
231 ConstInt::new(int, self.layout.ty.is_signed(), self.layout.ty.is_ptr_sized_integral())
235 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
236 /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
237 /// Returns `None` if the layout does not permit loading this as a value.
238 fn try_read_immediate_from_mplace(
240 mplace: &MPlaceTy<'tcx, M::PointerTag>,
241 ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::PointerTag>>> {
242 if mplace.layout.is_unsized() {
243 // Don't touch unsized
247 let alloc = match self.get_alloc(mplace)? {
250 return Ok(Some(ImmTy {
252 imm: Scalar::ZST.into(),
253 layout: mplace.layout,
258 match mplace.layout.abi {
260 let scalar = alloc.read_scalar(alloc_range(Size::ZERO, mplace.layout.size))?;
261 Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout }))
263 Abi::ScalarPair(ref a, ref b) => {
264 // We checked `ptr_align` above, so all fields will have the alignment they need.
265 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
266 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
267 let (a, b) = (&a.value, &b.value);
268 let (a_size, b_size) = (a.size(self), b.size(self));
269 let b_offset = a_size.align_to(b.align(self).abi);
270 assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields
271 let a_val = alloc.read_scalar(alloc_range(Size::ZERO, a_size))?;
272 let b_val = alloc.read_scalar(alloc_range(b_offset, b_size))?;
273 Ok(Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout }))
279 /// Try returning an immediate for the operand.
280 /// If the layout does not permit loading this as an immediate, return where in memory
281 /// we can find the data.
282 /// Note that for a given layout, this operation will either always fail or always
283 /// succeed! Whether it succeeds depends on whether the layout can be represented
284 /// in a `Immediate`, not on which data is stored there currently.
285 pub(crate) fn try_read_immediate(
287 src: &OpTy<'tcx, M::PointerTag>,
288 ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
289 Ok(match src.try_as_mplace() {
291 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
301 /// Read an immediate from a place, asserting that that is possible with the given layout.
303 pub fn read_immediate(
305 op: &OpTy<'tcx, M::PointerTag>,
306 ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
307 if let Ok(imm) = self.try_read_immediate(op)? {
310 span_bug!(self.cur_span(), "primitive read failed for type: {:?}", op.layout.ty);
314 /// Read a scalar from a place
317 op: &OpTy<'tcx, M::PointerTag>,
318 ) -> InterpResult<'tcx, ScalarMaybeUninit<M::PointerTag>> {
319 Ok(self.read_immediate(op)?.to_scalar_or_uninit())
322 /// Read a pointer from a place.
325 op: &OpTy<'tcx, M::PointerTag>,
326 ) -> InterpResult<'tcx, Pointer<Option<M::PointerTag>>> {
327 Ok(self.scalar_to_ptr(self.read_scalar(op)?.check_init()?))
330 // Turn the wide MPlace into a string (must already be dereferenced!)
331 pub fn read_str(&self, mplace: &MPlaceTy<'tcx, M::PointerTag>) -> InterpResult<'tcx, &str> {
332 let len = mplace.len(self)?;
333 let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len))?;
334 let str = std::str::from_utf8(bytes).map_err(|err| err_ub!(InvalidStr(err)))?;
338 /// Projection functions
339 pub fn operand_field(
341 op: &OpTy<'tcx, M::PointerTag>,
343 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
344 let base = match op.try_as_mplace() {
346 // We can reuse the mplace field computation logic for indirect operands.
347 let field = self.mplace_field(mplace, field)?;
348 return Ok(field.into());
353 let field_layout = op.layout.field(self, field)?;
354 if field_layout.is_zst() {
355 let immediate = Scalar::ZST.into();
356 return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
358 let offset = op.layout.fields.offset(field);
359 let immediate = match *base {
360 // the field covers the entire type
361 _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base,
362 // extract fields from types with `ScalarPair` ABI
363 Immediate::ScalarPair(a, b) => {
364 let val = if offset.bytes() == 0 { a } else { b };
367 Immediate::Scalar(val) => span_bug!(
369 "field access on non aggregate {:#?}, {:#?}",
374 Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
377 pub fn operand_index(
379 op: &OpTy<'tcx, M::PointerTag>,
381 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
382 if let Ok(index) = usize::try_from(index) {
383 // We can just treat this as a field.
384 self.operand_field(op, index)
386 // Indexing into a big array. This must be an mplace.
387 let mplace = op.assert_mem_place();
388 Ok(self.mplace_index(&mplace, index)?.into())
392 pub fn operand_downcast(
394 op: &OpTy<'tcx, M::PointerTag>,
396 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
397 // Downcasts only change the layout
398 Ok(match op.try_as_mplace() {
399 Ok(ref mplace) => self.mplace_downcast(mplace, variant)?.into(),
401 let layout = op.layout.for_variant(self, variant);
402 OpTy { layout, ..*op }
407 pub fn operand_projection(
409 base: &OpTy<'tcx, M::PointerTag>,
410 proj_elem: mir::PlaceElem<'tcx>,
411 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
412 use rustc_middle::mir::ProjectionElem::*;
414 Field(field, _) => self.operand_field(base, field.index())?,
415 Downcast(_, variant) => self.operand_downcast(base, variant)?,
416 Deref => self.deref_operand(base)?.into(),
417 Subslice { .. } | ConstantIndex { .. } | Index(_) => {
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()
426 /// Read from a local. Will not actually access the local if reading from a ZST.
427 /// Will not access memory, instead an indirect `Operand` is returned.
429 /// This is public because it is used by [priroda](https://github.com/oli-obk/priroda) to get an
430 /// OpTy from a local
433 frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
435 layout: Option<TyAndLayout<'tcx>>,
436 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
437 let layout = self.layout_of_local(frame, local, layout)?;
438 let op = if layout.is_zst() {
439 // Do not read from ZST, they might not be initialized
440 Operand::Immediate(Scalar::ZST.into())
442 M::access_local(&self, frame, local)?
444 Ok(OpTy { op, layout })
447 /// Every place can be read from, so we can turn them into an operand.
448 /// This will definitely return `Indirect` if the place is a `Ptr`, i.e., this
449 /// will never actually read from memory.
453 place: &PlaceTy<'tcx, M::PointerTag>,
454 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
455 let op = match **place {
456 Place::Ptr(mplace) => Operand::Indirect(mplace),
457 Place::Local { frame, local } => {
458 *self.access_local(&self.stack()[frame], local, None)?
461 Ok(OpTy { op, layout: place.layout })
464 // Evaluate a place with the goal of reading from it. This lets us sometimes
465 // avoid allocations.
466 pub fn eval_place_to_op(
468 place: mir::Place<'tcx>,
469 layout: Option<TyAndLayout<'tcx>>,
470 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
471 // Do not use the layout passed in as argument if the base we are looking at
472 // here is not the entire place.
473 let layout = if place.projection.is_empty() { layout } else { None };
475 let base_op = self.access_local(self.frame(), place.local, layout)?;
480 .try_fold(base_op, |op, elem| self.operand_projection(&op, elem))?;
482 trace!("eval_place_to_op: got {:?}", *op);
483 // Sanity-check the type we ended up with.
484 debug_assert!(mir_assign_valid_types(
487 self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
488 place.ty(&self.frame().body.local_decls, *self.tcx).ty
495 /// Evaluate the operand, returning a place where you can then find the data.
496 /// If you already know the layout, you can save two table lookups
497 /// by passing it in here.
501 mir_op: &mir::Operand<'tcx>,
502 layout: Option<TyAndLayout<'tcx>>,
503 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
504 use rustc_middle::mir::Operand::*;
505 let op = match *mir_op {
506 // FIXME: do some more logic on `move` to invalidate the old location
507 Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?,
509 Constant(ref constant) => {
511 self.subst_from_current_frame_and_normalize_erasing_regions(constant.literal);
512 // This can still fail:
513 // * During ConstProp, with `TooGeneric` or since the `requried_consts` were not all
515 // * During CTFE, since promoteds in `const`/`static` initializer bodies can fail.
517 self.mir_const_to_op(&val, layout)?
520 trace!("{:?}: {:?}", mir_op, *op);
524 /// Evaluate a bunch of operands at once
525 pub(super) fn eval_operands(
527 ops: &[mir::Operand<'tcx>],
528 ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
529 ops.iter().map(|op| self.eval_operand(op, None)).collect()
532 // Used when the miri-engine runs into a constant and for extracting information from constants
533 // in patterns via the `const_eval` module
534 /// The `val` and `layout` are assumed to already be in our interpreter
535 /// "universe" (param_env).
536 crate fn const_to_op(
538 val: &ty::Const<'tcx>,
539 layout: Option<TyAndLayout<'tcx>>,
540 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
542 ty::ConstKind::Param(_) | ty::ConstKind::Bound(..) => throw_inval!(TooGeneric),
543 ty::ConstKind::Error(_) => throw_inval!(AlreadyReported(ErrorReported)),
544 ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }) => {
545 let instance = self.resolve(def, substs)?;
546 Ok(self.eval_to_allocation(GlobalId { instance, promoted })?.into())
548 ty::ConstKind::Infer(..) | ty::ConstKind::Placeholder(..) => {
549 span_bug!(self.cur_span(), "const_to_op: Unexpected ConstKind {:?}", val)
551 ty::ConstKind::Value(val_val) => self.const_val_to_op(val_val, val.ty, layout),
555 crate fn mir_const_to_op(
557 val: &mir::ConstantKind<'tcx>,
558 layout: Option<TyAndLayout<'tcx>>,
559 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
561 mir::ConstantKind::Ty(ct) => self.const_to_op(ct, layout),
562 mir::ConstantKind::Val(val, ty) => self.const_val_to_op(*val, ty, layout),
566 crate fn const_val_to_op(
568 val_val: ConstValue<'tcx>,
570 layout: Option<TyAndLayout<'tcx>>,
571 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
572 // Other cases need layout.
573 let tag_scalar = |scalar| -> InterpResult<'tcx, _> {
575 Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size),
576 Scalar::Int(int) => Scalar::Int(int),
579 let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?;
580 let op = match val_val {
581 ConstValue::ByRef { alloc, offset } => {
582 let id = self.tcx.create_memory_alloc(alloc);
583 // We rely on mutability being set correctly in that allocation to prevent writes
584 // where none should happen.
585 let ptr = self.global_base_pointer(Pointer::new(id, offset))?;
586 Operand::Indirect(MemPlace::from_ptr(ptr.into(), layout.align.abi))
588 ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x.into())?.into()),
589 ConstValue::Slice { data, start, end } => {
590 // We rely on mutability being set correctly in `data` to prevent writes
591 // where none should happen.
592 let ptr = Pointer::new(
593 self.tcx.create_memory_alloc(data),
594 Size::from_bytes(start), // offset: `start`
596 Operand::Immediate(Immediate::new_slice(
597 Scalar::from_pointer(self.global_base_pointer(ptr)?, &*self.tcx),
598 u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start`
603 Ok(OpTy { op, layout })
606 /// Read discriminant, return the runtime value as well as the variant index.
607 pub fn read_discriminant(
609 op: &OpTy<'tcx, M::PointerTag>,
610 ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, VariantIdx)> {
611 trace!("read_discriminant_value {:#?}", op.layout);
612 // Get type and layout of the discriminant.
613 let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(*self.tcx))?;
614 trace!("discriminant type: {:?}", discr_layout.ty);
616 // We use "discriminant" to refer to the value associated with a particular enum variant.
617 // This is not to be confused with its "variant index", which is just determining its position in the
618 // declared list of variants -- they can differ with explicitly assigned discriminants.
619 // We use "tag" to refer to how the discriminant is encoded in memory, which can be either
620 // straight-forward (`TagEncoding::Direct`) or with a niche (`TagEncoding::Niche`).
621 let (tag_scalar_layout, tag_encoding, tag_field) = match op.layout.variants {
622 Variants::Single { index } => {
623 let discr = match op.layout.ty.discriminant_for_variant(*self.tcx, index) {
625 // This type actually has discriminants.
626 assert_eq!(discr.ty, discr_layout.ty);
627 Scalar::from_uint(discr.val, discr_layout.size)
630 // On a type without actual discriminants, variant is 0.
631 assert_eq!(index.as_u32(), 0);
632 Scalar::from_uint(index.as_u32(), discr_layout.size)
635 return Ok((discr, index));
637 Variants::Multiple { ref tag, ref tag_encoding, tag_field, .. } => {
638 (tag, tag_encoding, tag_field)
642 // There are *three* layouts that come into play here:
643 // - The discriminant has a type for typechecking. This is `discr_layout`, and is used for
644 // the `Scalar` we return.
645 // - The tag (encoded discriminant) has layout `tag_layout`. This is always an integer type,
646 // and used to interpret the value we read from the tag field.
647 // For the return value, a cast to `discr_layout` is performed.
648 // - The field storing the tag has a layout, which is very similar to `tag_layout` but
649 // may be a pointer. This is `tag_val.layout`; we just use it for sanity checks.
651 // Get layout for tag.
652 let tag_layout = self.layout_of(tag_scalar_layout.value.to_int_ty(*self.tcx))?;
654 // Read tag and sanity-check `tag_layout`.
655 let tag_val = self.read_immediate(&self.operand_field(op, tag_field)?)?;
656 assert_eq!(tag_layout.size, tag_val.layout.size);
657 assert_eq!(tag_layout.abi.is_signed(), tag_val.layout.abi.is_signed());
658 let tag_val = tag_val.to_scalar()?;
659 trace!("tag value: {:?}", tag_val);
661 // Figure out which discriminant and variant this corresponds to.
662 Ok(match *tag_encoding {
663 TagEncoding::Direct => {
664 let tag_bits = tag_val
666 .map_err(|dbg_val| err_ub!(InvalidTag(dbg_val)))?
667 .assert_bits(tag_layout.size);
668 // Cast bits from tag layout to discriminant layout.
669 let discr_val = self.cast_from_scalar(tag_bits, tag_layout, discr_layout.ty);
670 let discr_bits = discr_val.assert_bits(discr_layout.size);
671 // Convert discriminant to variant index, and catch invalid discriminants.
672 let index = match *op.layout.ty.kind() {
674 adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits)
676 ty::Generator(def_id, substs, _) => {
677 let substs = substs.as_generator();
679 .discriminants(def_id, *self.tcx)
680 .find(|(_, var)| var.val == discr_bits)
682 _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-generator"),
684 .ok_or_else(|| err_ub!(InvalidTag(Scalar::from_uint(tag_bits, tag_layout.size))))?;
685 // Return the cast value, and the index.
688 TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start } => {
689 // Compute the variant this niche value/"tag" corresponds to. With niche layout,
690 // discriminant (encoded in niche/tag) and variant index are the same.
691 let variants_start = niche_variants.start().as_u32();
692 let variants_end = niche_variants.end().as_u32();
693 let variant = match tag_val.try_to_int() {
695 // So this is a pointer then, and casting to an int failed.
696 // Can only happen during CTFE.
697 let ptr = self.scalar_to_ptr(tag_val);
698 // The niche must be just 0, and the ptr not null, then we know this is
699 // okay. Everything else, we conservatively reject.
700 let ptr_valid = niche_start == 0
701 && variants_start == variants_end
702 && !self.memory.ptr_may_be_null(ptr);
704 throw_ub!(InvalidTag(dbg_val))
709 let tag_bits = tag_bits.assert_bits(tag_layout.size);
710 // We need to use machine arithmetic to get the relative variant idx:
711 // variant_index_relative = tag_val - niche_start_val
712 let tag_val = ImmTy::from_uint(tag_bits, tag_layout);
713 let niche_start_val = ImmTy::from_uint(niche_start, tag_layout);
714 let variant_index_relative_val =
715 self.binary_op(mir::BinOp::Sub, &tag_val, &niche_start_val)?;
716 let variant_index_relative = variant_index_relative_val
718 .assert_bits(tag_val.layout.size);
719 // Check if this is in the range that indicates an actual discriminant.
720 if variant_index_relative <= u128::from(variants_end - variants_start) {
721 let variant_index_relative = u32::try_from(variant_index_relative)
722 .expect("we checked that this fits into a u32");
723 // Then computing the absolute variant idx should not overflow any more.
724 let variant_index = variants_start
725 .checked_add(variant_index_relative)
726 .expect("overflow computing absolute variant idx");
727 let variants_len = op
731 .expect("tagged layout for non adt")
734 assert!(usize::try_from(variant_index).unwrap() < variants_len);
735 VariantIdx::from_u32(variant_index)
741 // Compute the size of the scalar we need to return.
742 // No need to cast, because the variant index directly serves as discriminant and is
743 // encoded in the tag.
744 (Scalar::from_uint(variant.as_u32(), discr_layout.size), variant)