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