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::ByRef(..) |
62 ConstValue::Unevaluated(..) |
63 ConstValue::Slice(..) => None,
64 ConstValue::Scalar(val) => Some(val),
69 pub fn try_to_bits(&self, size: Size) -> Option<u128> {
70 self.try_to_scalar()?.to_bits(size).ok()
74 pub fn try_to_ptr(&self) -> Option<Pointer> {
75 self.try_to_scalar()?.to_ptr().ok()
83 ConstValue::Slice(val, len)
87 /// A `Scalar` represents an immediate, primitive value existing outside of a
88 /// `memory::Allocation`. It is in many ways like a small chunk of a `Allocation`, up to 8 bytes in
89 /// size. Like a range of bytes in an `Allocation`, a `Scalar` can either represent the raw bytes
90 /// of a simple value or a pointer into another `Allocation`
91 #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd,
92 RustcEncodable, RustcDecodable, Hash, HashStable)]
93 pub enum Scalar<Tag=(), Id=AllocId> {
94 /// The raw bytes of a simple value.
96 /// The first `size` bytes are the value.
97 /// Do not try to read less or more bytes than that. The remaining bytes must be 0.
102 /// A pointer into an `Allocation`. An `Allocation` in the `memory` module has a list of
103 /// relocations, but a `Scalar` is only large enough to contain one, so we just represent the
104 /// relocation and its associated offset together as a `Pointer` here.
105 Ptr(Pointer<Tag, Id>),
108 #[cfg(target_arch = "x86_64")]
109 static_assert!(SCALAR_SIZE: ::std::mem::size_of::<Scalar>() == 24);
111 impl<Tag> fmt::Display for Scalar<Tag> {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114 Scalar::Ptr(_) => write!(f, "a pointer"),
115 Scalar::Bits { bits, .. } => write!(f, "{}", bits),
120 impl<'tcx> Scalar<()> {
122 pub fn with_default_tag<Tag>(self) -> Scalar<Tag>
126 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.with_default_tag()),
127 Scalar::Bits { bits, size } => Scalar::Bits { bits, size },
132 impl<'tcx, Tag> Scalar<Tag> {
134 pub fn erase_tag(self) -> Scalar {
136 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.erase_tag()),
137 Scalar::Bits { bits, size } => Scalar::Bits { bits, size },
142 pub fn with_tag(self, new_tag: Tag) -> Self {
144 Scalar::Ptr(ptr) => Scalar::Ptr(Pointer { tag: new_tag, ..ptr }),
145 Scalar::Bits { bits, size } => Scalar::Bits { bits, size },
150 pub fn ptr_null(cx: &impl HasDataLayout) -> Self {
153 size: cx.data_layout().pointer_size.bytes() as u8,
158 pub fn zst() -> Self {
159 Scalar::Bits { bits: 0, size: 0 }
163 pub fn ptr_offset(self, i: Size, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
164 let dl = cx.data_layout();
166 Scalar::Bits { bits, size } => {
167 assert_eq!(size as u64, dl.pointer_size.bytes());
169 bits: dl.offset(bits as u64, i.bytes())? as u128,
173 Scalar::Ptr(ptr) => ptr.offset(i, dl).map(Scalar::Ptr),
178 pub fn ptr_wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
179 let dl = cx.data_layout();
181 Scalar::Bits { bits, size } => {
182 assert_eq!(size as u64, dl.pointer_size.bytes());
184 bits: dl.overflowing_offset(bits as u64, i.bytes()).0 as u128,
188 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_offset(i, dl)),
193 pub fn ptr_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
194 let dl = cx.data_layout();
196 Scalar::Bits { bits, size } => {
197 assert_eq!(size as u64, dl.pointer_size().bytes());
199 bits: dl.signed_offset(bits as u64, i)? as u128,
203 Scalar::Ptr(ptr) => ptr.signed_offset(i, dl).map(Scalar::Ptr),
208 pub fn ptr_wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
209 let dl = cx.data_layout();
211 Scalar::Bits { bits, size } => {
212 assert_eq!(size as u64, dl.pointer_size.bytes());
214 bits: dl.overflowing_signed_offset(bits as u64, i128::from(i)).0 as u128,
218 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_signed_offset(i, dl)),
222 /// Returns this pointers offset from the allocation base, or from NULL (for
223 /// integer pointers).
225 pub fn get_ptr_offset(self, cx: &impl HasDataLayout) -> Size {
227 Scalar::Bits { bits, size } => {
228 assert_eq!(size as u64, cx.pointer_size().bytes());
229 Size::from_bytes(bits as u64)
231 Scalar::Ptr(ptr) => ptr.offset,
236 pub fn is_null_ptr(self, cx: &impl HasDataLayout) -> bool {
238 Scalar::Bits { bits, size } => {
239 assert_eq!(size as u64, cx.data_layout().pointer_size.bytes());
242 Scalar::Ptr(_) => false,
247 pub fn from_bool(b: bool) -> Self {
248 Scalar::Bits { bits: b as u128, size: 1 }
252 pub fn from_char(c: char) -> Self {
253 Scalar::Bits { bits: c as u128, size: 4 }
257 pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
259 debug_assert_eq!(truncate(i, size), i,
260 "Unsigned value {} does not fit in {} bits", i, size.bits());
261 Scalar::Bits { bits: i, size: size.bytes() as u8 }
265 pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
267 // `into` performed sign extension, we have to truncate
268 let truncated = truncate(i as u128, size);
269 debug_assert_eq!(sign_extend(truncated, size) as i128, i,
270 "Signed value {} does not fit in {} bits", i, size.bits());
271 Scalar::Bits { bits: truncated, size: size.bytes() as u8 }
275 pub fn from_f32(f: f32) -> Self {
276 Scalar::Bits { bits: f.to_bits() as u128, size: 4 }
280 pub fn from_f64(f: f64) -> Self {
281 Scalar::Bits { bits: f.to_bits() as u128, size: 8 }
285 pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
287 Scalar::Bits { bits, size } => {
288 assert_eq!(target_size.bytes(), size as u64);
289 assert_ne!(size, 0, "to_bits cannot be used with zsts");
292 Scalar::Ptr(_) => err!(ReadPointerAsBytes),
297 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
299 Scalar::Bits { bits: 0, .. } => err!(InvalidNullPointerUsage),
300 Scalar::Bits { .. } => err!(ReadBytesAsPointer),
301 Scalar::Ptr(p) => Ok(p),
306 pub fn is_bits(self) -> bool {
308 Scalar::Bits { .. } => true,
314 pub fn is_ptr(self) -> bool {
316 Scalar::Ptr(_) => true,
321 pub fn to_bool(self) -> EvalResult<'tcx, bool> {
323 Scalar::Bits { bits: 0, size: 1 } => Ok(false),
324 Scalar::Bits { bits: 1, size: 1 } => Ok(true),
325 _ => err!(InvalidBool),
329 pub fn to_char(self) -> EvalResult<'tcx, char> {
330 let val = self.to_u32()?;
331 match ::std::char::from_u32(val) {
333 None => err!(InvalidChar(val as u128)),
337 pub fn to_u8(self) -> EvalResult<'static, u8> {
338 let sz = Size::from_bits(8);
339 let b = self.to_bits(sz)?;
340 assert_eq!(b as u8 as u128, b);
344 pub fn to_u32(self) -> EvalResult<'static, u32> {
345 let sz = Size::from_bits(32);
346 let b = self.to_bits(sz)?;
347 assert_eq!(b as u32 as u128, b);
351 pub fn to_u64(self) -> EvalResult<'static, u64> {
352 let sz = Size::from_bits(64);
353 let b = self.to_bits(sz)?;
354 assert_eq!(b as u64 as u128, b);
358 pub fn to_usize(self, cx: &impl HasDataLayout) -> EvalResult<'static, u64> {
359 let b = self.to_bits(cx.data_layout().pointer_size)?;
360 assert_eq!(b as u64 as u128, b);
364 pub fn to_i8(self) -> EvalResult<'static, i8> {
365 let sz = Size::from_bits(8);
366 let b = self.to_bits(sz)?;
367 let b = sign_extend(b, sz) as i128;
368 assert_eq!(b as i8 as i128, b);
372 pub fn to_i32(self) -> EvalResult<'static, i32> {
373 let sz = Size::from_bits(32);
374 let b = self.to_bits(sz)?;
375 let b = sign_extend(b, sz) as i128;
376 assert_eq!(b as i32 as i128, b);
380 pub fn to_i64(self) -> EvalResult<'static, i64> {
381 let sz = Size::from_bits(64);
382 let b = self.to_bits(sz)?;
383 let b = sign_extend(b, sz) as i128;
384 assert_eq!(b as i64 as i128, b);
388 pub fn to_isize(self, cx: &impl HasDataLayout) -> EvalResult<'static, i64> {
389 let b = self.to_bits(cx.data_layout().pointer_size)?;
390 let b = sign_extend(b, cx.data_layout().pointer_size) as i128;
391 assert_eq!(b as i64 as i128, b);
396 pub fn to_f32(self) -> EvalResult<'static, f32> {
397 Ok(f32::from_bits(self.to_u32()?))
401 pub fn to_f64(self) -> EvalResult<'static, f64> {
402 Ok(f64::from_bits(self.to_u64()?))
406 impl<Tag> From<Pointer<Tag>> for Scalar<Tag> {
408 fn from(ptr: Pointer<Tag>) -> Self {
413 #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, RustcEncodable, RustcDecodable, Hash)]
414 pub enum ScalarMaybeUndef<Tag=(), Id=AllocId> {
415 Scalar(Scalar<Tag, Id>),
419 impl<Tag> From<Scalar<Tag>> for ScalarMaybeUndef<Tag> {
421 fn from(s: Scalar<Tag>) -> Self {
422 ScalarMaybeUndef::Scalar(s)
426 impl<Tag> fmt::Display for ScalarMaybeUndef<Tag> {
427 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
429 ScalarMaybeUndef::Undef => write!(f, "uninitialized bytes"),
430 ScalarMaybeUndef::Scalar(s) => write!(f, "{}", s),
435 impl<'tcx> ScalarMaybeUndef<()> {
437 pub fn with_default_tag<Tag>(self) -> ScalarMaybeUndef<Tag>
441 ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.with_default_tag()),
442 ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
447 impl<'tcx, Tag> ScalarMaybeUndef<Tag> {
449 pub fn erase_tag(self) -> ScalarMaybeUndef
452 ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.erase_tag()),
453 ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
458 pub fn not_undef(self) -> EvalResult<'static, Scalar<Tag>> {
460 ScalarMaybeUndef::Scalar(scalar) => Ok(scalar),
461 ScalarMaybeUndef::Undef => err!(ReadUndefBytes(Size::from_bytes(0))),
466 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
467 self.not_undef()?.to_ptr()
471 pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
472 self.not_undef()?.to_bits(target_size)
476 pub fn to_bool(self) -> EvalResult<'tcx, bool> {
477 self.not_undef()?.to_bool()
481 pub fn to_char(self) -> EvalResult<'tcx, char> {
482 self.not_undef()?.to_char()
486 pub fn to_f32(self) -> EvalResult<'tcx, f32> {
487 self.not_undef()?.to_f32()
491 pub fn to_f64(self) -> EvalResult<'tcx, f64> {
492 self.not_undef()?.to_f64()
496 pub fn to_u8(self) -> EvalResult<'tcx, u8> {
497 self.not_undef()?.to_u8()
501 pub fn to_u32(self) -> EvalResult<'tcx, u32> {
502 self.not_undef()?.to_u32()
506 pub fn to_u64(self) -> EvalResult<'tcx, u64> {
507 self.not_undef()?.to_u64()
511 pub fn to_usize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, u64> {
512 self.not_undef()?.to_usize(cx)
516 pub fn to_i8(self) -> EvalResult<'tcx, i8> {
517 self.not_undef()?.to_i8()
521 pub fn to_i32(self) -> EvalResult<'tcx, i32> {
522 self.not_undef()?.to_i32()
526 pub fn to_i64(self) -> EvalResult<'tcx, i64> {
527 self.not_undef()?.to_i64()
531 pub fn to_isize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, i64> {
532 self.not_undef()?.to_isize(cx)
536 impl_stable_hash_for!(enum crate::mir::interpret::ScalarMaybeUndef {