]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/interpret/value.rs
Rollup merge of #61116 - scottmcm:vcpp-download-link, r=alexcrichton
[rust.git] / src / librustc / mir / interpret / value.rs
1 use std::fmt;
2 use rustc_macros::HashStable;
3
4 use crate::ty::{Ty, InferConst, ParamConst, layout::{HasDataLayout, Size}, subst::SubstsRef};
5 use crate::ty::PlaceholderConst;
6 use crate::hir::def_id::DefId;
7
8 use super::{EvalResult, Pointer, PointerArithmetic, Allocation, AllocId, sign_extend, truncate};
9
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,
16     pub ty: Ty<'tcx>,
17 }
18
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.
25     Param(ParamConst),
26
27     /// Infer the value of the const.
28     Infer(InferConst<'tcx>),
29
30     /// A placeholder const - universally quantified higher-ranked const.
31     Placeholder(PlaceholderConst),
32
33     /// Used only for types with `layout::abi::Scalar` ABI and ZSTs.
34     ///
35     /// Not using the enum `Value` to encode that this must not be `Undef`.
36     Scalar(Scalar),
37
38     /// Used only for slices and strings (`&[T]`, `&str`, `*const [T]`, `*mut str`, `Box<str>`,
39     /// etc.).
40     ///
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
44     /// it.
45     Slice(Scalar, u64),
46
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),
50
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>),
54 }
55
56 #[cfg(target_arch = "x86_64")]
57 static_assert_size!(ConstValue<'_>, 40);
58
59 impl<'tcx> ConstValue<'tcx> {
60     #[inline]
61     pub fn try_to_scalar(&self) -> Option<Scalar> {
62         match *self {
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),
70         }
71     }
72
73     #[inline]
74     pub fn try_to_bits(&self, size: Size) -> Option<u128> {
75         self.try_to_scalar()?.to_bits(size).ok()
76     }
77
78     #[inline]
79     pub fn try_to_ptr(&self) -> Option<Pointer> {
80         self.try_to_scalar()?.to_ptr().ok()
81     }
82
83     #[inline]
84     pub fn new_slice(
85         val: Scalar,
86         len: u64,
87     ) -> Self {
88         ConstValue::Slice(val, len)
89     }
90 }
91
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.
100     Bits {
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.
103         size: u8,
104         bits: u128,
105     },
106
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>),
111 }
112
113 #[cfg(target_arch = "x86_64")]
114 static_assert_size!(Scalar, 24);
115
116 impl<Tag> fmt::Display for Scalar<Tag> {
117     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118         match self {
119             Scalar::Ptr(_) => write!(f, "a pointer"),
120             Scalar::Bits { bits, .. } => write!(f, "{}", bits),
121         }
122     }
123 }
124
125 impl<'tcx> Scalar<()> {
126     #[inline]
127     pub fn with_tag<Tag>(self, new_tag: Tag) -> Scalar<Tag> {
128         match self {
129             Scalar::Ptr(ptr) => Scalar::Ptr(ptr.with_tag(new_tag)),
130             Scalar::Bits { bits, size } => Scalar::Bits { bits, size },
131         }
132     }
133
134     #[inline(always)]
135     pub fn with_default_tag<Tag>(self) -> Scalar<Tag>
136         where Tag: Default
137     {
138         self.with_tag(Tag::default())
139     }
140 }
141
142 impl<'tcx, Tag> Scalar<Tag> {
143     #[inline]
144     pub fn erase_tag(self) -> Scalar {
145         match self {
146             Scalar::Ptr(ptr) => Scalar::Ptr(ptr.erase_tag()),
147             Scalar::Bits { bits, size } => Scalar::Bits { bits, size },
148         }
149     }
150
151     #[inline]
152     pub fn ptr_null(cx: &impl HasDataLayout) -> Self {
153         Scalar::Bits {
154             bits: 0,
155             size: cx.data_layout().pointer_size.bytes() as u8,
156         }
157     }
158
159     #[inline]
160     pub fn zst() -> Self {
161         Scalar::Bits { bits: 0, size: 0 }
162     }
163
164     #[inline]
165     pub fn ptr_offset(self, i: Size, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
166         let dl = cx.data_layout();
167         match self {
168             Scalar::Bits { bits, size } => {
169                 assert_eq!(size as u64, dl.pointer_size.bytes());
170                 Ok(Scalar::Bits {
171                     bits: dl.offset(bits as u64, i.bytes())? as u128,
172                     size,
173                 })
174             }
175             Scalar::Ptr(ptr) => ptr.offset(i, dl).map(Scalar::Ptr),
176         }
177     }
178
179     #[inline]
180     pub fn ptr_wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
181         let dl = cx.data_layout();
182         match self {
183             Scalar::Bits { bits, size } => {
184                 assert_eq!(size as u64, dl.pointer_size.bytes());
185                 Scalar::Bits {
186                     bits: dl.overflowing_offset(bits as u64, i.bytes()).0 as u128,
187                     size,
188                 }
189             }
190             Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_offset(i, dl)),
191         }
192     }
193
194     #[inline]
195     pub fn ptr_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
196         let dl = cx.data_layout();
197         match self {
198             Scalar::Bits { bits, size } => {
199                 assert_eq!(size as u64, dl.pointer_size().bytes());
200                 Ok(Scalar::Bits {
201                     bits: dl.signed_offset(bits as u64, i)? as u128,
202                     size,
203                 })
204             }
205             Scalar::Ptr(ptr) => ptr.signed_offset(i, dl).map(Scalar::Ptr),
206         }
207     }
208
209     #[inline]
210     pub fn ptr_wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
211         let dl = cx.data_layout();
212         match self {
213             Scalar::Bits { bits, size } => {
214                 assert_eq!(size as u64, dl.pointer_size.bytes());
215                 Scalar::Bits {
216                     bits: dl.overflowing_signed_offset(bits as u64, i128::from(i)).0 as u128,
217                     size,
218                 }
219             }
220             Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_signed_offset(i, dl)),
221         }
222     }
223
224     /// Returns this pointers offset from the allocation base, or from NULL (for
225     /// integer pointers).
226     #[inline]
227     pub fn get_ptr_offset(self, cx: &impl HasDataLayout) -> Size {
228         match self {
229             Scalar::Bits { bits, size } => {
230                 assert_eq!(size as u64, cx.pointer_size().bytes());
231                 Size::from_bytes(bits as u64)
232             }
233             Scalar::Ptr(ptr) => ptr.offset,
234         }
235     }
236
237     #[inline]
238     pub fn is_null_ptr(self, cx: &impl HasDataLayout) -> bool {
239         match self {
240             Scalar::Bits { bits, size } => {
241                 assert_eq!(size as u64, cx.data_layout().pointer_size.bytes());
242                 bits == 0
243             },
244             Scalar::Ptr(_) => false,
245         }
246     }
247
248     #[inline]
249     pub fn from_bool(b: bool) -> Self {
250         Scalar::Bits { bits: b as u128, size: 1 }
251     }
252
253     #[inline]
254     pub fn from_char(c: char) -> Self {
255         Scalar::Bits { bits: c as u128, size: 4 }
256     }
257
258     #[inline]
259     pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
260         let i = i.into();
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 }
264     }
265
266     #[inline]
267     pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
268         let i = i.into();
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 }
274     }
275
276     #[inline]
277     pub fn from_f32(f: f32) -> Self {
278         Scalar::Bits { bits: f.to_bits() as u128, size: 4 }
279     }
280
281     #[inline]
282     pub fn from_f64(f: f64) -> Self {
283         Scalar::Bits { bits: f.to_bits() as u128, size: 8 }
284     }
285
286     #[inline]
287     pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
288         match self {
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");
292                 Ok(bits)
293             }
294             Scalar::Ptr(_) => err!(ReadPointerAsBytes),
295         }
296     }
297
298     #[inline]
299     pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
300         match self {
301             Scalar::Bits { bits: 0, .. } => err!(InvalidNullPointerUsage),
302             Scalar::Bits { .. } => err!(ReadBytesAsPointer),
303             Scalar::Ptr(p) => Ok(p),
304         }
305     }
306
307     #[inline]
308     pub fn is_bits(self) -> bool {
309         match self {
310             Scalar::Bits { .. } => true,
311             _ => false,
312         }
313     }
314
315     #[inline]
316     pub fn is_ptr(self) -> bool {
317         match self {
318             Scalar::Ptr(_) => true,
319             _ => false,
320         }
321     }
322
323     pub fn to_bool(self) -> EvalResult<'tcx, bool> {
324         match self {
325             Scalar::Bits { bits: 0, size: 1 } => Ok(false),
326             Scalar::Bits { bits: 1, size: 1 } => Ok(true),
327             _ => err!(InvalidBool),
328         }
329     }
330
331     pub fn to_char(self) -> EvalResult<'tcx, char> {
332         let val = self.to_u32()?;
333         match ::std::char::from_u32(val) {
334             Some(c) => Ok(c),
335             None => err!(InvalidChar(val as u128)),
336         }
337     }
338
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);
343         Ok(b as u8)
344     }
345
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);
350         Ok(b as u32)
351     }
352
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);
357         Ok(b as u64)
358     }
359
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);
363         Ok(b as u64)
364     }
365
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);
371         Ok(b as i8)
372     }
373
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);
379         Ok(b as i32)
380     }
381
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);
387         Ok(b as i64)
388     }
389
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);
394         Ok(b as i64)
395     }
396
397     #[inline]
398     pub fn to_f32(self) -> EvalResult<'static, f32> {
399         Ok(f32::from_bits(self.to_u32()?))
400     }
401
402     #[inline]
403     pub fn to_f64(self) -> EvalResult<'static, f64> {
404         Ok(f64::from_bits(self.to_u64()?))
405     }
406 }
407
408 impl<Tag> From<Pointer<Tag>> for Scalar<Tag> {
409     #[inline(always)]
410     fn from(ptr: Pointer<Tag>) -> Self {
411         Scalar::Ptr(ptr)
412     }
413 }
414
415 #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, RustcEncodable, RustcDecodable, Hash)]
416 pub enum ScalarMaybeUndef<Tag=(), Id=AllocId> {
417     Scalar(Scalar<Tag, Id>),
418     Undef,
419 }
420
421 impl<Tag> From<Scalar<Tag>> for ScalarMaybeUndef<Tag> {
422     #[inline(always)]
423     fn from(s: Scalar<Tag>) -> Self {
424         ScalarMaybeUndef::Scalar(s)
425     }
426 }
427
428 impl<Tag> fmt::Display for ScalarMaybeUndef<Tag> {
429     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430         match self {
431             ScalarMaybeUndef::Undef => write!(f, "uninitialized bytes"),
432             ScalarMaybeUndef::Scalar(s) => write!(f, "{}", s),
433         }
434     }
435 }
436
437 impl<'tcx> ScalarMaybeUndef<()> {
438     #[inline]
439     pub fn with_tag<Tag>(self, new_tag: Tag) -> ScalarMaybeUndef<Tag> {
440         match self {
441             ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.with_tag(new_tag)),
442             ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
443         }
444     }
445
446     #[inline(always)]
447     pub fn with_default_tag<Tag>(self) -> ScalarMaybeUndef<Tag>
448         where Tag: Default
449     {
450         self.with_tag(Tag::default())
451     }
452 }
453
454 impl<'tcx, Tag> ScalarMaybeUndef<Tag> {
455     #[inline]
456     pub fn erase_tag(self) -> ScalarMaybeUndef
457     {
458         match self {
459             ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.erase_tag()),
460             ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
461         }
462     }
463
464     #[inline]
465     pub fn not_undef(self) -> EvalResult<'static, Scalar<Tag>> {
466         match self {
467             ScalarMaybeUndef::Scalar(scalar) => Ok(scalar),
468             ScalarMaybeUndef::Undef => err!(ReadUndefBytes(Size::from_bytes(0))),
469         }
470     }
471
472     #[inline(always)]
473     pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
474         self.not_undef()?.to_ptr()
475     }
476
477     #[inline(always)]
478     pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
479         self.not_undef()?.to_bits(target_size)
480     }
481
482     #[inline(always)]
483     pub fn to_bool(self) -> EvalResult<'tcx, bool> {
484         self.not_undef()?.to_bool()
485     }
486
487     #[inline(always)]
488     pub fn to_char(self) -> EvalResult<'tcx, char> {
489         self.not_undef()?.to_char()
490     }
491
492     #[inline(always)]
493     pub fn to_f32(self) -> EvalResult<'tcx, f32> {
494         self.not_undef()?.to_f32()
495     }
496
497     #[inline(always)]
498     pub fn to_f64(self) -> EvalResult<'tcx, f64> {
499         self.not_undef()?.to_f64()
500     }
501
502     #[inline(always)]
503     pub fn to_u8(self) -> EvalResult<'tcx, u8> {
504         self.not_undef()?.to_u8()
505     }
506
507     #[inline(always)]
508     pub fn to_u32(self) -> EvalResult<'tcx, u32> {
509         self.not_undef()?.to_u32()
510     }
511
512     #[inline(always)]
513     pub fn to_u64(self) -> EvalResult<'tcx, u64> {
514         self.not_undef()?.to_u64()
515     }
516
517     #[inline(always)]
518     pub fn to_usize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, u64> {
519         self.not_undef()?.to_usize(cx)
520     }
521
522     #[inline(always)]
523     pub fn to_i8(self) -> EvalResult<'tcx, i8> {
524         self.not_undef()?.to_i8()
525     }
526
527     #[inline(always)]
528     pub fn to_i32(self) -> EvalResult<'tcx, i32> {
529         self.not_undef()?.to_i32()
530     }
531
532     #[inline(always)]
533     pub fn to_i64(self) -> EvalResult<'tcx, i64> {
534         self.not_undef()?.to_i64()
535     }
536
537     #[inline(always)]
538     pub fn to_isize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, i64> {
539         self.not_undef()?.to_isize(cx)
540     }
541 }
542
543 impl_stable_hash_for!(enum crate::mir::interpret::ScalarMaybeUndef {
544     Scalar(v),
545     Undef
546 });