2 use rustc_macros::HashStable;
4 use crate::ty::{Ty, InferConst, ParamConst, layout::{HasDataLayout, Size}, subst::SubstsRef};
5 use crate::hir::def_id::DefId;
7 use super::{EvalResult, Pointer, PointerArithmetic, Allocation, AllocId, sign_extend, truncate};
9 /// Represents the result of a raw const operation, pre-validation.
10 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
11 pub struct RawConst<'tcx> {
12 // the value lives here, at offset 0, and that allocation definitely is a `AllocKind::Memory`
13 // (so you can use `AllocMap::unwrap_memory`).
14 pub alloc_id: AllocId,
18 /// Represents a constant value in Rust. `Scalar` and `ScalarPair` are optimizations that
19 /// match the `LocalState` optimizations for easy conversions between `Value` and `ConstValue`.
20 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord,
21 RustcEncodable, RustcDecodable, Hash, HashStable)]
22 pub enum ConstValue<'tcx> {
23 /// A const generic parameter.
26 /// Infer the value of the const.
27 Infer(InferConst<'tcx>),
29 /// Used only for types with `layout::abi::Scalar` ABI and ZSTs.
31 /// Not using the enum `Value` to encode that this must not be `Undef`.
34 /// Used only for slices and strings (`&[T]`, `&str`, `*const [T]`, `*mut str`, `Box<str>`,
37 /// Empty slices don't necessarily have an address backed by an `AllocId`, thus we also need to
38 /// enable integer pointers. The `Scalar` type covers exactly those two cases. While we could
39 /// create dummy-`AllocId`s, the additional code effort for the conversions doesn't seem worth
43 /// An allocation together with a pointer into the allocation.
44 /// Invariant: the pointer's `AllocId` resolves to the allocation.
45 ByRef(Pointer, &'tcx Allocation),
47 /// Used in the HIR by using `Unevaluated` everywhere and later normalizing to one of the other
48 /// variants when the code is monomorphic enough for that.
49 Unevaluated(DefId, SubstsRef<'tcx>),
52 #[cfg(target_arch = "x86_64")]
53 static_assert!(CONST_SIZE: ::std::mem::size_of::<ConstValue<'static>>() == 40);
55 impl<'tcx> ConstValue<'tcx> {
57 pub fn try_to_scalar(&self) -> Option<Scalar> {
59 ConstValue::Param(_) |
60 ConstValue::Infer(_) |
61 ConstValue::Placeholder(_) |
62 ConstValue::ByRef(..) |
63 ConstValue::Unevaluated(..) |
64 ConstValue::Slice(..) => None,
65 ConstValue::Scalar(val) => Some(val),
70 pub fn try_to_bits(&self, size: Size) -> Option<u128> {
71 self.try_to_scalar()?.to_bits(size).ok()
75 pub fn try_to_ptr(&self) -> Option<Pointer> {
76 self.try_to_scalar()?.to_ptr().ok()
84 ConstValue::Slice(val, len)
88 /// A `Scalar` represents an immediate, primitive value existing outside of a
89 /// `memory::Allocation`. It is in many ways like a small chunk of a `Allocation`, up to 8 bytes in
90 /// size. Like a range of bytes in an `Allocation`, a `Scalar` can either represent the raw bytes
91 /// of a simple value or a pointer into another `Allocation`
92 #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd,
93 RustcEncodable, RustcDecodable, Hash, HashStable)]
94 pub enum Scalar<Tag=(), Id=AllocId> {
95 /// The raw bytes of a simple value.
97 /// The first `size` bytes are the value.
98 /// Do not try to read less or more bytes than that. The remaining bytes must be 0.
103 /// A pointer into an `Allocation`. An `Allocation` in the `memory` module has a list of
104 /// relocations, but a `Scalar` is only large enough to contain one, so we just represent the
105 /// relocation and its associated offset together as a `Pointer` here.
106 Ptr(Pointer<Tag, Id>),
109 #[cfg(target_arch = "x86_64")]
110 static_assert!(SCALAR_SIZE: ::std::mem::size_of::<Scalar>() == 24);
112 impl<Tag> fmt::Display for Scalar<Tag> {
113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 Scalar::Ptr(_) => write!(f, "a pointer"),
116 Scalar::Bits { bits, .. } => write!(f, "{}", bits),
121 impl<'tcx> Scalar<()> {
123 pub fn with_tag<Tag>(self, new_tag: Tag) -> Scalar<Tag> {
125 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.with_tag(new_tag)),
126 Scalar::Bits { bits, size } => Scalar::Bits { bits, size },
131 pub fn with_default_tag<Tag>(self) -> Scalar<Tag>
134 self.with_tag(Tag::default())
138 impl<'tcx, Tag> Scalar<Tag> {
140 pub fn erase_tag(self) -> Scalar {
142 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.erase_tag()),
143 Scalar::Bits { bits, size } => Scalar::Bits { bits, size },
148 pub fn ptr_null(cx: &impl HasDataLayout) -> Self {
151 size: cx.data_layout().pointer_size.bytes() as u8,
156 pub fn zst() -> Self {
157 Scalar::Bits { bits: 0, size: 0 }
161 pub fn ptr_offset(self, i: Size, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
162 let dl = cx.data_layout();
164 Scalar::Bits { bits, size } => {
165 assert_eq!(size as u64, dl.pointer_size.bytes());
167 bits: dl.offset(bits as u64, i.bytes())? as u128,
171 Scalar::Ptr(ptr) => ptr.offset(i, dl).map(Scalar::Ptr),
176 pub fn ptr_wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
177 let dl = cx.data_layout();
179 Scalar::Bits { bits, size } => {
180 assert_eq!(size as u64, dl.pointer_size.bytes());
182 bits: dl.overflowing_offset(bits as u64, i.bytes()).0 as u128,
186 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_offset(i, dl)),
191 pub fn ptr_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
192 let dl = cx.data_layout();
194 Scalar::Bits { bits, size } => {
195 assert_eq!(size as u64, dl.pointer_size().bytes());
197 bits: dl.signed_offset(bits as u64, i)? as u128,
201 Scalar::Ptr(ptr) => ptr.signed_offset(i, dl).map(Scalar::Ptr),
206 pub fn ptr_wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
207 let dl = cx.data_layout();
209 Scalar::Bits { bits, size } => {
210 assert_eq!(size as u64, dl.pointer_size.bytes());
212 bits: dl.overflowing_signed_offset(bits as u64, i128::from(i)).0 as u128,
216 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_signed_offset(i, dl)),
220 /// Returns this pointers offset from the allocation base, or from NULL (for
221 /// integer pointers).
223 pub fn get_ptr_offset(self, cx: &impl HasDataLayout) -> Size {
225 Scalar::Bits { bits, size } => {
226 assert_eq!(size as u64, cx.pointer_size().bytes());
227 Size::from_bytes(bits as u64)
229 Scalar::Ptr(ptr) => ptr.offset,
234 pub fn is_null_ptr(self, cx: &impl HasDataLayout) -> bool {
236 Scalar::Bits { bits, size } => {
237 assert_eq!(size as u64, cx.data_layout().pointer_size.bytes());
240 Scalar::Ptr(_) => false,
245 pub fn from_bool(b: bool) -> Self {
246 Scalar::Bits { bits: b as u128, size: 1 }
250 pub fn from_char(c: char) -> Self {
251 Scalar::Bits { bits: c as u128, size: 4 }
255 pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
257 debug_assert_eq!(truncate(i, size), i,
258 "Unsigned value {} does not fit in {} bits", i, size.bits());
259 Scalar::Bits { bits: i, size: size.bytes() as u8 }
263 pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
265 // `into` performed sign extension, we have to truncate
266 let truncated = truncate(i as u128, size);
267 debug_assert_eq!(sign_extend(truncated, size) as i128, i,
268 "Signed value {} does not fit in {} bits", i, size.bits());
269 Scalar::Bits { bits: truncated, size: size.bytes() as u8 }
273 pub fn from_f32(f: f32) -> Self {
274 Scalar::Bits { bits: f.to_bits() as u128, size: 4 }
278 pub fn from_f64(f: f64) -> Self {
279 Scalar::Bits { bits: f.to_bits() as u128, size: 8 }
283 pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
285 Scalar::Bits { bits, size } => {
286 assert_eq!(target_size.bytes(), size as u64);
287 assert_ne!(size, 0, "to_bits cannot be used with zsts");
290 Scalar::Ptr(_) => err!(ReadPointerAsBytes),
295 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
297 Scalar::Bits { bits: 0, .. } => err!(InvalidNullPointerUsage),
298 Scalar::Bits { .. } => err!(ReadBytesAsPointer),
299 Scalar::Ptr(p) => Ok(p),
304 pub fn is_bits(self) -> bool {
306 Scalar::Bits { .. } => true,
312 pub fn is_ptr(self) -> bool {
314 Scalar::Ptr(_) => true,
319 pub fn to_bool(self) -> EvalResult<'tcx, bool> {
321 Scalar::Bits { bits: 0, size: 1 } => Ok(false),
322 Scalar::Bits { bits: 1, size: 1 } => Ok(true),
323 _ => err!(InvalidBool),
327 pub fn to_char(self) -> EvalResult<'tcx, char> {
328 let val = self.to_u32()?;
329 match ::std::char::from_u32(val) {
331 None => err!(InvalidChar(val as u128)),
335 pub fn to_u8(self) -> EvalResult<'static, u8> {
336 let sz = Size::from_bits(8);
337 let b = self.to_bits(sz)?;
338 assert_eq!(b as u8 as u128, b);
342 pub fn to_u32(self) -> EvalResult<'static, u32> {
343 let sz = Size::from_bits(32);
344 let b = self.to_bits(sz)?;
345 assert_eq!(b as u32 as u128, b);
349 pub fn to_u64(self) -> EvalResult<'static, u64> {
350 let sz = Size::from_bits(64);
351 let b = self.to_bits(sz)?;
352 assert_eq!(b as u64 as u128, b);
356 pub fn to_usize(self, cx: &impl HasDataLayout) -> EvalResult<'static, u64> {
357 let b = self.to_bits(cx.data_layout().pointer_size)?;
358 assert_eq!(b as u64 as u128, b);
362 pub fn to_i8(self) -> EvalResult<'static, i8> {
363 let sz = Size::from_bits(8);
364 let b = self.to_bits(sz)?;
365 let b = sign_extend(b, sz) as i128;
366 assert_eq!(b as i8 as i128, b);
370 pub fn to_i32(self) -> EvalResult<'static, i32> {
371 let sz = Size::from_bits(32);
372 let b = self.to_bits(sz)?;
373 let b = sign_extend(b, sz) as i128;
374 assert_eq!(b as i32 as i128, b);
378 pub fn to_i64(self) -> EvalResult<'static, i64> {
379 let sz = Size::from_bits(64);
380 let b = self.to_bits(sz)?;
381 let b = sign_extend(b, sz) as i128;
382 assert_eq!(b as i64 as i128, b);
386 pub fn to_isize(self, cx: &impl HasDataLayout) -> EvalResult<'static, i64> {
387 let b = self.to_bits(cx.data_layout().pointer_size)?;
388 let b = sign_extend(b, cx.data_layout().pointer_size) as i128;
389 assert_eq!(b as i64 as i128, b);
394 pub fn to_f32(self) -> EvalResult<'static, f32> {
395 Ok(f32::from_bits(self.to_u32()?))
399 pub fn to_f64(self) -> EvalResult<'static, f64> {
400 Ok(f64::from_bits(self.to_u64()?))
404 impl<Tag> From<Pointer<Tag>> for Scalar<Tag> {
406 fn from(ptr: Pointer<Tag>) -> Self {
411 #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, RustcEncodable, RustcDecodable, Hash)]
412 pub enum ScalarMaybeUndef<Tag=(), Id=AllocId> {
413 Scalar(Scalar<Tag, Id>),
417 impl<Tag> From<Scalar<Tag>> for ScalarMaybeUndef<Tag> {
419 fn from(s: Scalar<Tag>) -> Self {
420 ScalarMaybeUndef::Scalar(s)
424 impl<Tag> fmt::Display for ScalarMaybeUndef<Tag> {
425 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427 ScalarMaybeUndef::Undef => write!(f, "uninitialized bytes"),
428 ScalarMaybeUndef::Scalar(s) => write!(f, "{}", s),
433 impl<'tcx> ScalarMaybeUndef<()> {
435 pub fn with_tag<Tag>(self, new_tag: Tag) -> ScalarMaybeUndef<Tag> {
437 ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.with_tag(new_tag)),
438 ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
443 pub fn with_default_tag<Tag>(self) -> ScalarMaybeUndef<Tag>
446 self.with_tag(Tag::default())
450 impl<'tcx, Tag> ScalarMaybeUndef<Tag> {
452 pub fn erase_tag(self) -> ScalarMaybeUndef
455 ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.erase_tag()),
456 ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
461 pub fn not_undef(self) -> EvalResult<'static, Scalar<Tag>> {
463 ScalarMaybeUndef::Scalar(scalar) => Ok(scalar),
464 ScalarMaybeUndef::Undef => err!(ReadUndefBytes(Size::from_bytes(0))),
469 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
470 self.not_undef()?.to_ptr()
474 pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
475 self.not_undef()?.to_bits(target_size)
479 pub fn to_bool(self) -> EvalResult<'tcx, bool> {
480 self.not_undef()?.to_bool()
484 pub fn to_char(self) -> EvalResult<'tcx, char> {
485 self.not_undef()?.to_char()
489 pub fn to_f32(self) -> EvalResult<'tcx, f32> {
490 self.not_undef()?.to_f32()
494 pub fn to_f64(self) -> EvalResult<'tcx, f64> {
495 self.not_undef()?.to_f64()
499 pub fn to_u8(self) -> EvalResult<'tcx, u8> {
500 self.not_undef()?.to_u8()
504 pub fn to_u32(self) -> EvalResult<'tcx, u32> {
505 self.not_undef()?.to_u32()
509 pub fn to_u64(self) -> EvalResult<'tcx, u64> {
510 self.not_undef()?.to_u64()
514 pub fn to_usize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, u64> {
515 self.not_undef()?.to_usize(cx)
519 pub fn to_i8(self) -> EvalResult<'tcx, i8> {
520 self.not_undef()?.to_i8()
524 pub fn to_i32(self) -> EvalResult<'tcx, i32> {
525 self.not_undef()?.to_i32()
529 pub fn to_i64(self) -> EvalResult<'tcx, i64> {
530 self.not_undef()?.to_i64()
534 pub fn to_isize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, i64> {
535 self.not_undef()?.to_isize(cx)
539 impl_stable_hash_for!(enum crate::mir::interpret::ScalarMaybeUndef {