2 use rustc_macros::HashStable;
4 use crate::ty::{Ty, InferConst, ParamConst, layout::{HasDataLayout, Size}, subst::SubstsRef};
5 use crate::ty::PlaceholderConst;
6 use crate::hir::def_id::DefId;
8 use super::{EvalResult, Pointer, PointerArithmetic, Allocation, AllocId, sign_extend, truncate};
10 /// Represents the result of a raw const operation, pre-validation.
11 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
12 pub struct RawConst<'tcx> {
13 // the value lives here, at offset 0, and that allocation definitely is a `AllocKind::Memory`
14 // (so you can use `AllocMap::unwrap_memory`).
15 pub alloc_id: AllocId,
19 /// Represents a constant value in Rust. `Scalar` and `ScalarPair` are optimizations that
20 /// match the `LocalState` optimizations for easy conversions between `Value` and `ConstValue`.
21 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord,
22 RustcEncodable, RustcDecodable, Hash, HashStable)]
23 pub enum ConstValue<'tcx> {
24 /// A const generic parameter.
27 /// Infer the value of the const.
28 Infer(InferConst<'tcx>),
30 /// A placeholder const - universally quantified higher-ranked const.
31 Placeholder(PlaceholderConst),
33 /// Used only for types with `layout::abi::Scalar` ABI and ZSTs.
35 /// Not using the enum `Value` to encode that this must not be `Undef`.
38 /// Used only for slices and strings (`&[T]`, `&str`, `*const [T]`, `*mut str`, `Box<str>`,
41 /// Empty slices don't necessarily have an address backed by an `AllocId`, thus we also need to
42 /// enable integer pointers. The `Scalar` type covers exactly those two cases. While we could
43 /// create dummy-`AllocId`s, the additional code effort for the conversions doesn't seem worth
47 /// An allocation together with a pointer into the allocation.
48 /// Invariant: the pointer's `AllocId` resolves to the allocation.
49 ByRef(Pointer, &'tcx Allocation),
51 /// Used in the HIR by using `Unevaluated` everywhere and later normalizing to one of the other
52 /// variants when the code is monomorphic enough for that.
53 Unevaluated(DefId, SubstsRef<'tcx>),
56 #[cfg(target_arch = "x86_64")]
57 static_assert_size!(ConstValue<'_>, 40);
59 impl<'tcx> ConstValue<'tcx> {
61 pub fn try_to_scalar(&self) -> Option<Scalar> {
63 ConstValue::Param(_) |
64 ConstValue::Infer(_) |
65 ConstValue::Placeholder(_) |
66 ConstValue::ByRef(..) |
67 ConstValue::Unevaluated(..) |
68 ConstValue::Slice(..) => None,
69 ConstValue::Scalar(val) => Some(val),
74 pub fn try_to_bits(&self, size: Size) -> Option<u128> {
75 self.try_to_scalar()?.to_bits(size).ok()
79 pub fn try_to_ptr(&self) -> Option<Pointer> {
80 self.try_to_scalar()?.to_ptr().ok()
88 ConstValue::Slice(val, len)
92 /// A `Scalar` represents an immediate, primitive value existing outside of a
93 /// `memory::Allocation`. It is in many ways like a small chunk of a `Allocation`, up to 8 bytes in
94 /// size. Like a range of bytes in an `Allocation`, a `Scalar` can either represent the raw bytes
95 /// of a simple value or a pointer into another `Allocation`
96 #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd,
97 RustcEncodable, RustcDecodable, Hash, HashStable)]
98 pub enum Scalar<Tag=(), Id=AllocId> {
99 /// The raw bytes of a simple value.
101 /// The first `size` bytes are the value.
102 /// Do not try to read less or more bytes than that. The remaining bytes must be 0.
107 /// A pointer into an `Allocation`. An `Allocation` in the `memory` module has a list of
108 /// relocations, but a `Scalar` is only large enough to contain one, so we just represent the
109 /// relocation and its associated offset together as a `Pointer` here.
110 Ptr(Pointer<Tag, Id>),
113 #[cfg(target_arch = "x86_64")]
114 static_assert_size!(Scalar, 24);
116 impl<Tag> fmt::Display for Scalar<Tag> {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 Scalar::Ptr(_) => write!(f, "a pointer"),
120 Scalar::Bits { bits, .. } => write!(f, "{}", bits),
125 impl<'tcx> Scalar<()> {
127 pub fn with_tag<Tag>(self, new_tag: Tag) -> Scalar<Tag> {
129 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.with_tag(new_tag)),
130 Scalar::Bits { bits, size } => Scalar::Bits { bits, size },
135 pub fn with_default_tag<Tag>(self) -> Scalar<Tag>
138 self.with_tag(Tag::default())
142 impl<'tcx, Tag> Scalar<Tag> {
144 pub fn erase_tag(self) -> Scalar {
146 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.erase_tag()),
147 Scalar::Bits { bits, size } => Scalar::Bits { bits, size },
152 pub fn ptr_null(cx: &impl HasDataLayout) -> Self {
155 size: cx.data_layout().pointer_size.bytes() as u8,
160 pub fn zst() -> Self {
161 Scalar::Bits { bits: 0, size: 0 }
165 pub fn ptr_offset(self, i: Size, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
166 let dl = cx.data_layout();
168 Scalar::Bits { bits, size } => {
169 assert_eq!(size as u64, dl.pointer_size.bytes());
171 bits: dl.offset(bits as u64, i.bytes())? as u128,
175 Scalar::Ptr(ptr) => ptr.offset(i, dl).map(Scalar::Ptr),
180 pub fn ptr_wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
181 let dl = cx.data_layout();
183 Scalar::Bits { bits, size } => {
184 assert_eq!(size as u64, dl.pointer_size.bytes());
186 bits: dl.overflowing_offset(bits as u64, i.bytes()).0 as u128,
190 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_offset(i, dl)),
195 pub fn ptr_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
196 let dl = cx.data_layout();
198 Scalar::Bits { bits, size } => {
199 assert_eq!(size as u64, dl.pointer_size().bytes());
201 bits: dl.signed_offset(bits as u64, i)? as u128,
205 Scalar::Ptr(ptr) => ptr.signed_offset(i, dl).map(Scalar::Ptr),
210 pub fn ptr_wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
211 let dl = cx.data_layout();
213 Scalar::Bits { bits, size } => {
214 assert_eq!(size as u64, dl.pointer_size.bytes());
216 bits: dl.overflowing_signed_offset(bits as u64, i128::from(i)).0 as u128,
220 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_signed_offset(i, dl)),
224 /// Returns this pointers offset from the allocation base, or from NULL (for
225 /// integer pointers).
227 pub fn get_ptr_offset(self, cx: &impl HasDataLayout) -> Size {
229 Scalar::Bits { bits, size } => {
230 assert_eq!(size as u64, cx.pointer_size().bytes());
231 Size::from_bytes(bits as u64)
233 Scalar::Ptr(ptr) => ptr.offset,
238 pub fn is_null_ptr(self, cx: &impl HasDataLayout) -> bool {
240 Scalar::Bits { bits, size } => {
241 assert_eq!(size as u64, cx.data_layout().pointer_size.bytes());
244 Scalar::Ptr(_) => false,
249 pub fn from_bool(b: bool) -> Self {
250 Scalar::Bits { bits: b as u128, size: 1 }
254 pub fn from_char(c: char) -> Self {
255 Scalar::Bits { bits: c as u128, size: 4 }
259 pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
261 debug_assert_eq!(truncate(i, size), i,
262 "Unsigned value {} does not fit in {} bits", i, size.bits());
263 Scalar::Bits { bits: i, size: size.bytes() as u8 }
267 pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
269 // `into` performed sign extension, we have to truncate
270 let truncated = truncate(i as u128, size);
271 debug_assert_eq!(sign_extend(truncated, size) as i128, i,
272 "Signed value {} does not fit in {} bits", i, size.bits());
273 Scalar::Bits { bits: truncated, size: size.bytes() as u8 }
277 pub fn from_f32(f: f32) -> Self {
278 Scalar::Bits { bits: f.to_bits() as u128, size: 4 }
282 pub fn from_f64(f: f64) -> Self {
283 Scalar::Bits { bits: f.to_bits() as u128, size: 8 }
287 pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
289 Scalar::Bits { bits, size } => {
290 assert_eq!(target_size.bytes(), size as u64);
291 assert_ne!(size, 0, "to_bits cannot be used with zsts");
294 Scalar::Ptr(_) => err!(ReadPointerAsBytes),
299 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
301 Scalar::Bits { bits: 0, .. } => err!(InvalidNullPointerUsage),
302 Scalar::Bits { .. } => err!(ReadBytesAsPointer),
303 Scalar::Ptr(p) => Ok(p),
308 pub fn is_bits(self) -> bool {
310 Scalar::Bits { .. } => true,
316 pub fn is_ptr(self) -> bool {
318 Scalar::Ptr(_) => true,
323 pub fn to_bool(self) -> EvalResult<'tcx, bool> {
325 Scalar::Bits { bits: 0, size: 1 } => Ok(false),
326 Scalar::Bits { bits: 1, size: 1 } => Ok(true),
327 _ => err!(InvalidBool),
331 pub fn to_char(self) -> EvalResult<'tcx, char> {
332 let val = self.to_u32()?;
333 match ::std::char::from_u32(val) {
335 None => err!(InvalidChar(val as u128)),
339 pub fn to_u8(self) -> EvalResult<'static, u8> {
340 let sz = Size::from_bits(8);
341 let b = self.to_bits(sz)?;
342 assert_eq!(b as u8 as u128, b);
346 pub fn to_u32(self) -> EvalResult<'static, u32> {
347 let sz = Size::from_bits(32);
348 let b = self.to_bits(sz)?;
349 assert_eq!(b as u32 as u128, b);
353 pub fn to_u64(self) -> EvalResult<'static, u64> {
354 let sz = Size::from_bits(64);
355 let b = self.to_bits(sz)?;
356 assert_eq!(b as u64 as u128, b);
360 pub fn to_usize(self, cx: &impl HasDataLayout) -> EvalResult<'static, u64> {
361 let b = self.to_bits(cx.data_layout().pointer_size)?;
362 assert_eq!(b as u64 as u128, b);
366 pub fn to_i8(self) -> EvalResult<'static, i8> {
367 let sz = Size::from_bits(8);
368 let b = self.to_bits(sz)?;
369 let b = sign_extend(b, sz) as i128;
370 assert_eq!(b as i8 as i128, b);
374 pub fn to_i32(self) -> EvalResult<'static, i32> {
375 let sz = Size::from_bits(32);
376 let b = self.to_bits(sz)?;
377 let b = sign_extend(b, sz) as i128;
378 assert_eq!(b as i32 as i128, b);
382 pub fn to_i64(self) -> EvalResult<'static, i64> {
383 let sz = Size::from_bits(64);
384 let b = self.to_bits(sz)?;
385 let b = sign_extend(b, sz) as i128;
386 assert_eq!(b as i64 as i128, b);
390 pub fn to_isize(self, cx: &impl HasDataLayout) -> EvalResult<'static, i64> {
391 let b = self.to_bits(cx.data_layout().pointer_size)?;
392 let b = sign_extend(b, cx.data_layout().pointer_size) as i128;
393 assert_eq!(b as i64 as i128, b);
398 pub fn to_f32(self) -> EvalResult<'static, f32> {
399 Ok(f32::from_bits(self.to_u32()?))
403 pub fn to_f64(self) -> EvalResult<'static, f64> {
404 Ok(f64::from_bits(self.to_u64()?))
408 impl<Tag> From<Pointer<Tag>> for Scalar<Tag> {
410 fn from(ptr: Pointer<Tag>) -> Self {
415 #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, RustcEncodable, RustcDecodable, Hash)]
416 pub enum ScalarMaybeUndef<Tag=(), Id=AllocId> {
417 Scalar(Scalar<Tag, Id>),
421 impl<Tag> From<Scalar<Tag>> for ScalarMaybeUndef<Tag> {
423 fn from(s: Scalar<Tag>) -> Self {
424 ScalarMaybeUndef::Scalar(s)
428 impl<Tag> fmt::Display for ScalarMaybeUndef<Tag> {
429 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431 ScalarMaybeUndef::Undef => write!(f, "uninitialized bytes"),
432 ScalarMaybeUndef::Scalar(s) => write!(f, "{}", s),
437 impl<'tcx> ScalarMaybeUndef<()> {
439 pub fn with_tag<Tag>(self, new_tag: Tag) -> ScalarMaybeUndef<Tag> {
441 ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.with_tag(new_tag)),
442 ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
447 pub fn with_default_tag<Tag>(self) -> ScalarMaybeUndef<Tag>
450 self.with_tag(Tag::default())
454 impl<'tcx, Tag> ScalarMaybeUndef<Tag> {
456 pub fn erase_tag(self) -> ScalarMaybeUndef
459 ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.erase_tag()),
460 ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
465 pub fn not_undef(self) -> EvalResult<'static, Scalar<Tag>> {
467 ScalarMaybeUndef::Scalar(scalar) => Ok(scalar),
468 ScalarMaybeUndef::Undef => err!(ReadUndefBytes(Size::from_bytes(0))),
473 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
474 self.not_undef()?.to_ptr()
478 pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
479 self.not_undef()?.to_bits(target_size)
483 pub fn to_bool(self) -> EvalResult<'tcx, bool> {
484 self.not_undef()?.to_bool()
488 pub fn to_char(self) -> EvalResult<'tcx, char> {
489 self.not_undef()?.to_char()
493 pub fn to_f32(self) -> EvalResult<'tcx, f32> {
494 self.not_undef()?.to_f32()
498 pub fn to_f64(self) -> EvalResult<'tcx, f64> {
499 self.not_undef()?.to_f64()
503 pub fn to_u8(self) -> EvalResult<'tcx, u8> {
504 self.not_undef()?.to_u8()
508 pub fn to_u32(self) -> EvalResult<'tcx, u32> {
509 self.not_undef()?.to_u32()
513 pub fn to_u64(self) -> EvalResult<'tcx, u64> {
514 self.not_undef()?.to_u64()
518 pub fn to_usize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, u64> {
519 self.not_undef()?.to_usize(cx)
523 pub fn to_i8(self) -> EvalResult<'tcx, i8> {
524 self.not_undef()?.to_i8()
528 pub fn to_i32(self) -> EvalResult<'tcx, i32> {
529 self.not_undef()?.to_i32()
533 pub fn to_i64(self) -> EvalResult<'tcx, i64> {
534 self.not_undef()?.to_i64()
538 pub fn to_isize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, i64> {
539 self.not_undef()?.to_isize(cx)
543 impl_stable_hash_for!(enum crate::mir::interpret::ScalarMaybeUndef {