]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/interpret/operand.rs
get rid of incorrect erase_for_fmt
[rust.git] / compiler / rustc_mir / src / 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::TryFrom;
5 use std::fmt::Write;
6
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};
16
17 use super::{
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,
21 };
22
23 /// An `Immediate` represents a single immediate self-contained Rust value.
24 ///
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)]
31 pub enum Immediate<Tag = AllocId> {
32     Scalar(ScalarMaybeUninit<Tag>),
33     ScalarPair(ScalarMaybeUninit<Tag>, ScalarMaybeUninit<Tag>),
34 }
35
36 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
37 rustc_data_structures::static_assert_size!(Immediate, 56);
38
39 impl<Tag: Provenance> std::fmt::Debug for Immediate<Tag> {
40     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41         use Immediate::*;
42         match self {
43             Scalar(s) => f.debug_tuple("Scalar").field(s).finish(),
44             ScalarPair(s1, s2) => f.debug_tuple("ScalarPair").field(s1).field(s2).finish(),
45         }
46     }
47 }
48
49 impl<Tag> From<ScalarMaybeUninit<Tag>> for Immediate<Tag> {
50     #[inline(always)]
51     fn from(val: ScalarMaybeUninit<Tag>) -> Self {
52         Immediate::Scalar(val)
53     }
54 }
55
56 impl<Tag> From<Scalar<Tag>> for Immediate<Tag> {
57     #[inline(always)]
58     fn from(val: Scalar<Tag>) -> Self {
59         Immediate::Scalar(val.into())
60     }
61 }
62
63 impl<'tcx, Tag> Immediate<Tag> {
64     pub fn from_pointer(p: Pointer<Tag>, cx: &impl HasDataLayout) -> Self {
65         Immediate::Scalar(ScalarMaybeUninit::from_pointer(p, cx))
66     }
67
68     pub fn from_maybe_pointer(p: Pointer<Option<Tag>>, cx: &impl HasDataLayout) -> Self {
69         Immediate::Scalar(ScalarMaybeUninit::from_maybe_pointer(p, cx))
70     }
71
72     pub fn new_slice(val: Scalar<Tag>, len: u64, cx: &impl HasDataLayout) -> Self {
73         Immediate::ScalarPair(val.into(), Scalar::from_machine_usize(len, cx).into())
74     }
75
76     pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>, cx: &impl HasDataLayout) -> Self {
77         Immediate::ScalarPair(val.into(), ScalarMaybeUninit::from_pointer(vtable, cx))
78     }
79
80     #[inline]
81     pub fn to_scalar_or_uninit(self) -> ScalarMaybeUninit<Tag> {
82         match self {
83             Immediate::Scalar(val) => val,
84             Immediate::ScalarPair(..) => bug!("Got a wide pointer where a scalar was expected"),
85         }
86     }
87
88     #[inline]
89     pub fn to_scalar(self) -> InterpResult<'tcx, Scalar<Tag>> {
90         self.to_scalar_or_uninit().check_init()
91     }
92 }
93
94 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
95 // as input for binary and cast operations.
96 #[derive(Copy, Clone)]
97 pub struct ImmTy<'tcx, Tag = AllocId> {
98     imm: Immediate<Tag>,
99     pub layout: TyAndLayout<'tcx>,
100 }
101
102 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
103 rustc_data_structures::static_assert_size!(ImmTy<'_>, 72);
104
105 impl<'tcx, Tag: Provenance> std::fmt::Debug for ImmTy<'tcx, Tag> {
106     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107         let ImmTy { imm, layout } = self;
108         f.debug_struct("ImmTy").field("imm", imm).field("layout", layout).finish()
109     }
110 }
111
112 impl<Tag: Provenance> std::fmt::Display for ImmTy<'tcx, Tag> {
113     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114         /// Helper function for printing a scalar to a FmtPrinter
115         fn p<'a, 'tcx, F: std::fmt::Write, Tag: Provenance>(
116             cx: FmtPrinter<'a, 'tcx, F>,
117             s: ScalarMaybeUninit<Tag>,
118             ty: Ty<'tcx>,
119         ) -> Result<FmtPrinter<'a, 'tcx, F>, std::fmt::Error> {
120             match s {
121                 ScalarMaybeUninit::Scalar(Scalar::Int(int)) => {
122                     cx.pretty_print_const_scalar_int(int, ty, true)
123                 }
124                 ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _sz)) => {
125                     // Just print the ptr value. `pretty_print_const_scalar_ptr` would also try to
126                     // print what is points to, which would fail since it has no access to the local
127                     // memory.
128                     cx.pretty_print_const_pointer(ptr, ty, true)
129                 }
130                 ScalarMaybeUninit::Uninit => cx.typed_value(
131                     |mut this| {
132                         this.write_str("uninit ")?;
133                         Ok(this)
134                     },
135                     |this| this.print_type(ty),
136                     " ",
137                 ),
138             }
139         }
140         ty::tls::with(|tcx| {
141             match self.imm {
142                 Immediate::Scalar(s) => {
143                     if let Some(ty) = tcx.lift(self.layout.ty) {
144                         let cx = FmtPrinter::new(tcx, f, Namespace::ValueNS);
145                         p(cx, s, ty)?;
146                         return Ok(());
147                     }
148                     write!(f, "{}: {}", s, self.layout.ty)
149                 }
150                 Immediate::ScalarPair(a, b) => {
151                     // FIXME(oli-obk): at least print tuples and slices nicely
152                     write!(f, "({}, {}): {}", a, b, self.layout.ty,)
153                 }
154             }
155         })
156     }
157 }
158
159 impl<'tcx, Tag> std::ops::Deref for ImmTy<'tcx, Tag> {
160     type Target = Immediate<Tag>;
161     #[inline(always)]
162     fn deref(&self) -> &Immediate<Tag> {
163         &self.imm
164     }
165 }
166
167 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
168 /// or still in memory. The latter is an optimization, to delay reading that chunk of
169 /// memory and to avoid having to store arbitrary-sized data here.
170 #[derive(Copy, Clone, PartialEq, Eq, HashStable, Hash)]
171 pub enum Operand<Tag = AllocId> {
172     Immediate(Immediate<Tag>),
173     Indirect(MemPlace<Tag>),
174 }
175
176 impl<Tag: Provenance> std::fmt::Debug for Operand<Tag> {
177     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178         use Operand::*;
179         match self {
180             Immediate(i) => f.debug_tuple("Immediate").field(i).finish(),
181             Indirect(p) => f.debug_tuple("Indirect").field(p).finish(),
182         }
183     }
184 }
185
186 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
187 pub struct OpTy<'tcx, Tag = AllocId> {
188     op: Operand<Tag>, // Keep this private; it helps enforce invariants.
189     pub layout: TyAndLayout<'tcx>,
190 }
191
192 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
193 rustc_data_structures::static_assert_size!(OpTy<'_, ()>, 80);
194
195 impl<'tcx, Tag: Provenance> std::fmt::Debug for OpTy<'tcx, Tag> {
196     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197         let OpTy { op, layout } = self;
198         f.debug_struct("OpTy").field("op", op).field("layout", layout).finish()
199     }
200 }
201
202 impl<'tcx, Tag> std::ops::Deref for OpTy<'tcx, Tag> {
203     type Target = Operand<Tag>;
204     #[inline(always)]
205     fn deref(&self) -> &Operand<Tag> {
206         &self.op
207     }
208 }
209
210 impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
211     #[inline(always)]
212     fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
213         OpTy { op: Operand::Indirect(*mplace), layout: mplace.layout }
214     }
215 }
216
217 impl<'tcx, Tag: Copy> From<&'_ MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
218     #[inline(always)]
219     fn from(mplace: &MPlaceTy<'tcx, Tag>) -> Self {
220         OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout }
221     }
222 }
223
224 impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
225     #[inline(always)]
226     fn from(val: ImmTy<'tcx, Tag>) -> Self {
227         OpTy { op: Operand::Immediate(val.imm), layout: val.layout }
228     }
229 }
230
231 impl<'tcx, Tag: Copy> ImmTy<'tcx, Tag> {
232     #[inline]
233     pub fn from_scalar(val: Scalar<Tag>, layout: TyAndLayout<'tcx>) -> Self {
234         ImmTy { imm: val.into(), layout }
235     }
236
237     #[inline]
238     pub fn from_immediate(imm: Immediate<Tag>, layout: TyAndLayout<'tcx>) -> Self {
239         ImmTy { imm, layout }
240     }
241
242     #[inline]
243     pub fn try_from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
244         Some(Self::from_scalar(Scalar::try_from_uint(i, layout.size)?, layout))
245     }
246     #[inline]
247     pub fn from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Self {
248         Self::from_scalar(Scalar::from_uint(i, layout.size), layout)
249     }
250
251     #[inline]
252     pub fn try_from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
253         Some(Self::from_scalar(Scalar::try_from_int(i, layout.size)?, layout))
254     }
255
256     #[inline]
257     pub fn from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Self {
258         Self::from_scalar(Scalar::from_int(i, layout.size), layout)
259     }
260
261     #[inline]
262     pub fn to_const_int(self) -> ConstInt
263     where
264         Tag: Provenance,
265     {
266         assert!(self.layout.ty.is_integral());
267         let int = self.to_scalar().expect("to_const_int doesn't work on scalar pairs").assert_int();
268         ConstInt::new(int, self.layout.ty.is_signed(), self.layout.ty.is_ptr_sized_integral())
269     }
270 }
271
272 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
273     /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
274     /// Returns `None` if the layout does not permit loading this as a value.
275     fn try_read_immediate_from_mplace(
276         &self,
277         mplace: &MPlaceTy<'tcx, M::PointerTag>,
278     ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::PointerTag>>> {
279         if mplace.layout.is_unsized() {
280             // Don't touch unsized
281             return Ok(None);
282         }
283
284         let alloc = match self.get_alloc(mplace)? {
285             Some(ptr) => ptr,
286             None => {
287                 return Ok(Some(ImmTy {
288                     // zero-sized type
289                     imm: Scalar::ZST.into(),
290                     layout: mplace.layout,
291                 }));
292             }
293         };
294
295         match mplace.layout.abi {
296             Abi::Scalar(..) => {
297                 let scalar = alloc.read_scalar(alloc_range(Size::ZERO, mplace.layout.size))?;
298                 Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout }))
299             }
300             Abi::ScalarPair(ref a, ref b) => {
301                 // We checked `ptr_align` above, so all fields will have the alignment they need.
302                 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
303                 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
304                 let (a, b) = (&a.value, &b.value);
305                 let (a_size, b_size) = (a.size(self), b.size(self));
306                 let b_offset = a_size.align_to(b.align(self).abi);
307                 assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields
308                 let a_val = alloc.read_scalar(alloc_range(Size::ZERO, a_size))?;
309                 let b_val = alloc.read_scalar(alloc_range(b_offset, b_size))?;
310                 Ok(Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout }))
311             }
312             _ => Ok(None),
313         }
314     }
315
316     /// Try returning an immediate for the operand.
317     /// If the layout does not permit loading this as an immediate, return where in memory
318     /// we can find the data.
319     /// Note that for a given layout, this operation will either always fail or always
320     /// succeed!  Whether it succeeds depends on whether the layout can be represented
321     /// in a `Immediate`, not on which data is stored there currently.
322     pub(crate) fn try_read_immediate(
323         &self,
324         src: &OpTy<'tcx, M::PointerTag>,
325     ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
326         Ok(match src.try_as_mplace() {
327             Ok(ref mplace) => {
328                 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
329                     Ok(val)
330                 } else {
331                     Err(*mplace)
332                 }
333             }
334             Err(val) => Ok(val),
335         })
336     }
337
338     /// Read an immediate from a place, asserting that that is possible with the given layout.
339     #[inline(always)]
340     pub fn read_immediate(
341         &self,
342         op: &OpTy<'tcx, M::PointerTag>,
343     ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
344         if let Ok(imm) = self.try_read_immediate(op)? {
345             Ok(imm)
346         } else {
347             span_bug!(self.cur_span(), "primitive read failed for type: {:?}", op.layout.ty);
348         }
349     }
350
351     /// Read a scalar from a place
352     pub fn read_scalar(
353         &self,
354         op: &OpTy<'tcx, M::PointerTag>,
355     ) -> InterpResult<'tcx, ScalarMaybeUninit<M::PointerTag>> {
356         Ok(self.read_immediate(op)?.to_scalar_or_uninit())
357     }
358
359     /// Read a pointer from a place.
360     pub fn read_pointer(
361         &self,
362         op: &OpTy<'tcx, M::PointerTag>,
363     ) -> InterpResult<'tcx, Pointer<Option<M::PointerTag>>> {
364         Ok(self.scalar_to_ptr(self.read_scalar(op)?.check_init()?))
365     }
366
367     // Turn the wide MPlace into a string (must already be dereferenced!)
368     pub fn read_str(&self, mplace: &MPlaceTy<'tcx, M::PointerTag>) -> InterpResult<'tcx, &str> {
369         let len = mplace.len(self)?;
370         let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len))?;
371         let str = std::str::from_utf8(bytes).map_err(|err| err_ub!(InvalidStr(err)))?;
372         Ok(str)
373     }
374
375     /// Projection functions
376     pub fn operand_field(
377         &self,
378         op: &OpTy<'tcx, M::PointerTag>,
379         field: usize,
380     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
381         let base = match op.try_as_mplace() {
382             Ok(ref mplace) => {
383                 // We can reuse the mplace field computation logic for indirect operands.
384                 let field = self.mplace_field(mplace, field)?;
385                 return Ok(field.into());
386             }
387             Err(value) => value,
388         };
389
390         let field_layout = op.layout.field(self, field)?;
391         if field_layout.is_zst() {
392             let immediate = Scalar::ZST.into();
393             return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
394         }
395         let offset = op.layout.fields.offset(field);
396         let immediate = match *base {
397             // the field covers the entire type
398             _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base,
399             // extract fields from types with `ScalarPair` ABI
400             Immediate::ScalarPair(a, b) => {
401                 let val = if offset.bytes() == 0 { a } else { b };
402                 Immediate::from(val)
403             }
404             Immediate::Scalar(val) => span_bug!(
405                 self.cur_span(),
406                 "field access on non aggregate {:#?}, {:#?}",
407                 val,
408                 op.layout
409             ),
410         };
411         Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
412     }
413
414     pub fn operand_index(
415         &self,
416         op: &OpTy<'tcx, M::PointerTag>,
417         index: u64,
418     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
419         if let Ok(index) = usize::try_from(index) {
420             // We can just treat this as a field.
421             self.operand_field(op, index)
422         } else {
423             // Indexing into a big array. This must be an mplace.
424             let mplace = op.assert_mem_place();
425             Ok(self.mplace_index(&mplace, index)?.into())
426         }
427     }
428
429     pub fn operand_downcast(
430         &self,
431         op: &OpTy<'tcx, M::PointerTag>,
432         variant: VariantIdx,
433     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
434         // Downcasts only change the layout
435         Ok(match op.try_as_mplace() {
436             Ok(ref mplace) => self.mplace_downcast(mplace, variant)?.into(),
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     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
449         use rustc_middle::mir::ProjectionElem::*;
450         Ok(match proj_elem {
451             Field(field, _) => self.operand_field(base, field.index())?,
452             Downcast(_, variant) => self.operand_downcast(base, variant)?,
453             Deref => self.deref_operand(base)?.into(),
454             Subslice { .. } | ConstantIndex { .. } | Index(_) => {
455                 // The rest should only occur as mplace, we do not use Immediates for types
456                 // allowing such operations.  This matches place_projection forcing an allocation.
457                 let mplace = base.assert_mem_place();
458                 self.mplace_projection(&mplace, proj_elem)?.into()
459             }
460         })
461     }
462
463     /// Read from a local. Will not actually access the local if reading from a ZST.
464     /// Will not access memory, instead an indirect `Operand` is returned.
465     ///
466     /// This is public because it is used by [priroda](https://github.com/oli-obk/priroda) to get an
467     /// OpTy from a local
468     pub fn access_local(
469         &self,
470         frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
471         local: mir::Local,
472         layout: Option<TyAndLayout<'tcx>>,
473     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
474         let layout = self.layout_of_local(frame, local, layout)?;
475         let op = if layout.is_zst() {
476             // Do not read from ZST, they might not be initialized
477             Operand::Immediate(Scalar::ZST.into())
478         } else {
479             M::access_local(&self, frame, local)?
480         };
481         Ok(OpTy { op, layout })
482     }
483
484     /// Every place can be read from, so we can turn them into an operand.
485     /// This will definitely return `Indirect` if the place is a `Ptr`, i.e., this
486     /// will never actually read from memory.
487     #[inline(always)]
488     pub fn place_to_op(
489         &self,
490         place: &PlaceTy<'tcx, M::PointerTag>,
491     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
492         let op = match **place {
493             Place::Ptr(mplace) => Operand::Indirect(mplace),
494             Place::Local { frame, local } => {
495                 *self.access_local(&self.stack()[frame], local, None)?
496             }
497         };
498         Ok(OpTy { op, layout: place.layout })
499     }
500
501     // Evaluate a place with the goal of reading from it.  This lets us sometimes
502     // avoid allocations.
503     pub fn eval_place_to_op(
504         &self,
505         place: mir::Place<'tcx>,
506         layout: Option<TyAndLayout<'tcx>>,
507     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
508         // Do not use the layout passed in as argument if the base we are looking at
509         // here is not the entire place.
510         let layout = if place.projection.is_empty() { layout } else { None };
511
512         let base_op = self.access_local(self.frame(), place.local, layout)?;
513
514         let op = place
515             .projection
516             .iter()
517             .try_fold(base_op, |op, elem| self.operand_projection(&op, elem))?;
518
519         trace!("eval_place_to_op: got {:?}", *op);
520         // Sanity-check the type we ended up with.
521         debug_assert!(mir_assign_valid_types(
522             *self.tcx,
523             self.param_env,
524             self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
525                 place.ty(&self.frame().body.local_decls, *self.tcx).ty
526             ))?,
527             op.layout,
528         ));
529         Ok(op)
530     }
531
532     /// Evaluate the operand, returning a place where you can then find the data.
533     /// If you already know the layout, you can save two table lookups
534     /// by passing it in here.
535     #[inline]
536     pub fn eval_operand(
537         &self,
538         mir_op: &mir::Operand<'tcx>,
539         layout: Option<TyAndLayout<'tcx>>,
540     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
541         use rustc_middle::mir::Operand::*;
542         let op = match *mir_op {
543             // FIXME: do some more logic on `move` to invalidate the old location
544             Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?,
545
546             Constant(ref constant) => {
547                 let val =
548                     self.subst_from_current_frame_and_normalize_erasing_regions(constant.literal);
549                 // This can still fail:
550                 // * During ConstProp, with `TooGeneric` or since the `requried_consts` were not all
551                 //   checked yet.
552                 // * During CTFE, since promoteds in `const`/`static` initializer bodies can fail.
553
554                 self.mir_const_to_op(&val, layout)?
555             }
556         };
557         trace!("{:?}: {:?}", mir_op, *op);
558         Ok(op)
559     }
560
561     /// Evaluate a bunch of operands at once
562     pub(super) fn eval_operands(
563         &self,
564         ops: &[mir::Operand<'tcx>],
565     ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
566         ops.iter().map(|op| self.eval_operand(op, None)).collect()
567     }
568
569     // Used when the miri-engine runs into a constant and for extracting information from constants
570     // in patterns via the `const_eval` module
571     /// The `val` and `layout` are assumed to already be in our interpreter
572     /// "universe" (param_env).
573     crate fn const_to_op(
574         &self,
575         val: &ty::Const<'tcx>,
576         layout: Option<TyAndLayout<'tcx>>,
577     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
578         match val.val {
579             ty::ConstKind::Param(_) | ty::ConstKind::Bound(..) => throw_inval!(TooGeneric),
580             ty::ConstKind::Error(_) => throw_inval!(AlreadyReported(ErrorReported)),
581             ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }) => {
582                 let instance = self.resolve(def, substs)?;
583                 Ok(self.eval_to_allocation(GlobalId { instance, promoted })?.into())
584             }
585             ty::ConstKind::Infer(..) | ty::ConstKind::Placeholder(..) => {
586                 span_bug!(self.cur_span(), "const_to_op: Unexpected ConstKind {:?}", val)
587             }
588             ty::ConstKind::Value(val_val) => self.const_val_to_op(val_val, val.ty, layout),
589         }
590     }
591
592     crate fn mir_const_to_op(
593         &self,
594         val: &mir::ConstantKind<'tcx>,
595         layout: Option<TyAndLayout<'tcx>>,
596     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
597         match val {
598             mir::ConstantKind::Ty(ct) => self.const_to_op(ct, layout),
599             mir::ConstantKind::Val(val, ty) => self.const_val_to_op(*val, ty, layout),
600         }
601     }
602
603     crate fn const_val_to_op(
604         &self,
605         val_val: ConstValue<'tcx>,
606         ty: Ty<'tcx>,
607         layout: Option<TyAndLayout<'tcx>>,
608     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
609         // Other cases need layout.
610         let tag_scalar = |scalar| -> InterpResult<'tcx, _> {
611             Ok(match scalar {
612                 Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size),
613                 Scalar::Int(int) => Scalar::Int(int),
614             })
615         };
616         let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?;
617         let op = match val_val {
618             ConstValue::ByRef { alloc, offset } => {
619                 let id = self.tcx.create_memory_alloc(alloc);
620                 // We rely on mutability being set correctly in that allocation to prevent writes
621                 // where none should happen.
622                 let ptr = self.global_base_pointer(Pointer::new(id, offset))?;
623                 Operand::Indirect(MemPlace::from_ptr(ptr.into(), layout.align.abi))
624             }
625             ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x.into())?.into()),
626             ConstValue::Slice { data, start, end } => {
627                 // We rely on mutability being set correctly in `data` to prevent writes
628                 // where none should happen.
629                 let ptr = Pointer::new(
630                     self.tcx.create_memory_alloc(data),
631                     Size::from_bytes(start), // offset: `start`
632                 );
633                 Operand::Immediate(Immediate::new_slice(
634                     Scalar::from_pointer(self.global_base_pointer(ptr)?, &*self.tcx),
635                     u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start`
636                     self,
637                 ))
638             }
639         };
640         Ok(OpTy { op, layout })
641     }
642
643     /// Read discriminant, return the runtime value as well as the variant index.
644     pub fn read_discriminant(
645         &self,
646         op: &OpTy<'tcx, M::PointerTag>,
647     ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, VariantIdx)> {
648         trace!("read_discriminant_value {:#?}", op.layout);
649         // Get type and layout of the discriminant.
650         let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(*self.tcx))?;
651         trace!("discriminant type: {:?}", discr_layout.ty);
652
653         // We use "discriminant" to refer to the value associated with a particular enum variant.
654         // This is not to be confused with its "variant index", which is just determining its position in the
655         // declared list of variants -- they can differ with explicitly assigned discriminants.
656         // We use "tag" to refer to how the discriminant is encoded in memory, which can be either
657         // straight-forward (`TagEncoding::Direct`) or with a niche (`TagEncoding::Niche`).
658         let (tag_scalar_layout, tag_encoding, tag_field) = match op.layout.variants {
659             Variants::Single { index } => {
660                 let discr = match op.layout.ty.discriminant_for_variant(*self.tcx, index) {
661                     Some(discr) => {
662                         // This type actually has discriminants.
663                         assert_eq!(discr.ty, discr_layout.ty);
664                         Scalar::from_uint(discr.val, discr_layout.size)
665                     }
666                     None => {
667                         // On a type without actual discriminants, variant is 0.
668                         assert_eq!(index.as_u32(), 0);
669                         Scalar::from_uint(index.as_u32(), discr_layout.size)
670                     }
671                 };
672                 return Ok((discr, index));
673             }
674             Variants::Multiple { ref tag, ref tag_encoding, tag_field, .. } => {
675                 (tag, tag_encoding, tag_field)
676             }
677         };
678
679         // There are *three* layouts that come into play here:
680         // - The discriminant has a type for typechecking. This is `discr_layout`, and is used for
681         //   the `Scalar` we return.
682         // - The tag (encoded discriminant) has layout `tag_layout`. This is always an integer type,
683         //   and used to interpret the value we read from the tag field.
684         //   For the return value, a cast to `discr_layout` is performed.
685         // - The field storing the tag has a layout, which is very similar to `tag_layout` but
686         //   may be a pointer. This is `tag_val.layout`; we just use it for sanity checks.
687
688         // Get layout for tag.
689         let tag_layout = self.layout_of(tag_scalar_layout.value.to_int_ty(*self.tcx))?;
690
691         // Read tag and sanity-check `tag_layout`.
692         let tag_val = self.read_immediate(&self.operand_field(op, tag_field)?)?;
693         assert_eq!(tag_layout.size, tag_val.layout.size);
694         assert_eq!(tag_layout.abi.is_signed(), tag_val.layout.abi.is_signed());
695         let tag_val = tag_val.to_scalar()?;
696         trace!("tag value: {:?}", tag_val);
697
698         // Figure out which discriminant and variant this corresponds to.
699         Ok(match *tag_encoding {
700             TagEncoding::Direct => {
701                 let tag_bits = tag_val
702                     .try_to_int()
703                     .map_err(|dbg_val| err_ub!(InvalidTag(dbg_val)))?
704                     .assert_bits(tag_layout.size);
705                 // Cast bits from tag layout to discriminant layout.
706                 let discr_val = self.cast_from_scalar(tag_bits, tag_layout, discr_layout.ty);
707                 let discr_bits = discr_val.assert_bits(discr_layout.size);
708                 // Convert discriminant to variant index, and catch invalid discriminants.
709                 let index = match *op.layout.ty.kind() {
710                     ty::Adt(adt, _) => {
711                         adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits)
712                     }
713                     ty::Generator(def_id, substs, _) => {
714                         let substs = substs.as_generator();
715                         substs
716                             .discriminants(def_id, *self.tcx)
717                             .find(|(_, var)| var.val == discr_bits)
718                     }
719                     _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-generator"),
720                 }
721                 .ok_or_else(|| err_ub!(InvalidTag(Scalar::from_uint(tag_bits, tag_layout.size))))?;
722                 // Return the cast value, and the index.
723                 (discr_val, index.0)
724             }
725             TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start } => {
726                 // Compute the variant this niche value/"tag" corresponds to. With niche layout,
727                 // discriminant (encoded in niche/tag) and variant index are the same.
728                 let variants_start = niche_variants.start().as_u32();
729                 let variants_end = niche_variants.end().as_u32();
730                 let variant = match tag_val.try_to_int() {
731                     Err(dbg_val) => {
732                         // So this is a pointer then, and casting to an int failed.
733                         // Can only happen during CTFE.
734                         let ptr = self.scalar_to_ptr(tag_val);
735                         // The niche must be just 0, and the ptr not null, then we know this is
736                         // okay. Everything else, we conservatively reject.
737                         let ptr_valid = niche_start == 0
738                             && variants_start == variants_end
739                             && !self.memory.ptr_may_be_null(ptr);
740                         if !ptr_valid {
741                             throw_ub!(InvalidTag(dbg_val))
742                         }
743                         dataful_variant
744                     }
745                     Ok(tag_bits) => {
746                         let tag_bits = tag_bits.assert_bits(tag_layout.size);
747                         // We need to use machine arithmetic to get the relative variant idx:
748                         // variant_index_relative = tag_val - niche_start_val
749                         let tag_val = ImmTy::from_uint(tag_bits, tag_layout);
750                         let niche_start_val = ImmTy::from_uint(niche_start, tag_layout);
751                         let variant_index_relative_val =
752                             self.binary_op(mir::BinOp::Sub, &tag_val, &niche_start_val)?;
753                         let variant_index_relative = variant_index_relative_val
754                             .to_scalar()?
755                             .assert_bits(tag_val.layout.size);
756                         // Check if this is in the range that indicates an actual discriminant.
757                         if variant_index_relative <= u128::from(variants_end - variants_start) {
758                             let variant_index_relative = u32::try_from(variant_index_relative)
759                                 .expect("we checked that this fits into a u32");
760                             // Then computing the absolute variant idx should not overflow any more.
761                             let variant_index = variants_start
762                                 .checked_add(variant_index_relative)
763                                 .expect("overflow computing absolute variant idx");
764                             let variants_len = op
765                                 .layout
766                                 .ty
767                                 .ty_adt_def()
768                                 .expect("tagged layout for non adt")
769                                 .variants
770                                 .len();
771                             assert!(usize::try_from(variant_index).unwrap() < variants_len);
772                             VariantIdx::from_u32(variant_index)
773                         } else {
774                             dataful_variant
775                         }
776                     }
777                 };
778                 // Compute the size of the scalar we need to return.
779                 // No need to cast, because the variant index directly serves as discriminant and is
780                 // encoded in the tag.
781                 (Scalar::from_uint(variant.as_u32(), discr_layout.size), variant)
782             }
783         })
784     }
785 }