1 //! This module gives users to instantiate values that Cranelift understands. These values are used,
2 //! for example, during interpretation and for wrapping immediates.
3 use crate::ir::immediates::{Ieee32, Ieee64, Offset32};
4 use crate::ir::{types, ConstantData, Type};
5 use core::convert::TryInto;
6 use core::fmt::{self, Display, Formatter};
7 use core::ptr;
8 use thiserror::Error;
9 
10 /// Represent a data value. Where [Value] is an SSA reference, [DataValue] is the type + value
11 /// that would be referred to by a [Value].
12 ///
13 /// [Value]: crate::ir::Value
14 #[allow(missing_docs)]
15 #[derive(Clone, Debug, PartialEq, PartialOrd)]
16 pub enum DataValue {
17     B(bool),
18     I8(i8),
19     I16(i16),
20     I32(i32),
21     I64(i64),
22     U8(u8),
23     U16(u16),
24     U32(u32),
25     U64(u64),
26     F32(Ieee32),
27     F64(Ieee64),
28     V128([u8; 16]),
29 }
30 
31 impl DataValue {
32     /// Try to cast an immediate integer (a wrapped `i64` on most Cranelift instructions) to the
33     /// given Cranelift [Type].
34     pub fn from_integer(imm: i64, ty: Type) -> Result<DataValue, DataValueCastFailure> {
35         match ty {
36             types::I8 => Ok(DataValue::I8(imm as i8)),
37             types::I16 => Ok(DataValue::I16(imm as i16)),
38             types::I32 => Ok(DataValue::I32(imm as i32)),
39             types::I64 => Ok(DataValue::I64(imm)),
40             _ => Err(DataValueCastFailure::FromInteger(imm, ty)),
41         }
42     }
43 
44     /// Return the Cranelift IR [Type] for this [DataValue].
45     pub fn ty(&self) -> Type {
46         match self {
47             DataValue::B(_) => types::B8, // A default type.
48             DataValue::I8(_) | DataValue::U8(_) => types::I8,
49             DataValue::I16(_) | DataValue::U16(_) => types::I16,
50             DataValue::I32(_) | DataValue::U32(_) => types::I32,
51             DataValue::I64(_) | DataValue::U64(_) => types::I64,
52             DataValue::F32(_) => types::F32,
53             DataValue::F64(_) => types::F64,
54             DataValue::V128(_) => types::I8X16, // A default type.
55         }
56     }
57 
58     /// Return true if the value is a vector (i.e. `DataValue::V128`).
59     pub fn is_vector(&self) -> bool {
60         match self {
61             DataValue::V128(_) => true,
62             _ => false,
63         }
64     }
65 
66     /// Write a [DataValue] to a memory location.
67     pub unsafe fn write_value_to(&self, p: *mut u128) {
68         match self {
69             DataValue::B(b) => ptr::write(p as *mut bool, *b),
70             DataValue::I8(i) => ptr::write(p as *mut i8, *i),
71             DataValue::I16(i) => ptr::write(p as *mut i16, *i),
72             DataValue::I32(i) => ptr::write(p as *mut i32, *i),
73             DataValue::I64(i) => ptr::write(p as *mut i64, *i),
74             DataValue::F32(f) => ptr::write(p as *mut Ieee32, *f),
75             DataValue::F64(f) => ptr::write(p as *mut Ieee64, *f),
76             DataValue::V128(b) => ptr::write(p as *mut [u8; 16], *b),
77             _ => unimplemented!(),
78         }
79     }
80 
81     /// Read a [DataValue] from a memory location using a given [Type].
82     pub unsafe fn read_value_from(p: *const u128, ty: Type) -> Self {
83         match ty {
84             types::I8 => DataValue::I8(ptr::read(p as *const i8)),
85             types::I16 => DataValue::I16(ptr::read(p as *const i16)),
86             types::I32 => DataValue::I32(ptr::read(p as *const i32)),
87             types::I64 => DataValue::I64(ptr::read(p as *const i64)),
88             types::F32 => DataValue::F32(ptr::read(p as *const Ieee32)),
89             types::F64 => DataValue::F64(ptr::read(p as *const Ieee64)),
90             _ if ty.is_bool() => DataValue::B(ptr::read(p as *const bool)),
91             _ if ty.is_vector() && ty.bytes() == 16 => {
92                 DataValue::V128(ptr::read(p as *const [u8; 16]))
93             }
94             _ => unimplemented!(),
95         }
96     }
97 }
98 
99 /// Record failures to cast [DataValue].
100 #[derive(Error, Debug, PartialEq)]
101 #[allow(missing_docs)]
102 pub enum DataValueCastFailure {
103     #[error("unable to cast data value of type {0} to type {1}")]
104     TryInto(Type, Type),
105     #[error("unable to cast i64({0}) to a data value of type {1}")]
106     FromInteger(i64, Type),
107 }
108 
109 /// Helper for creating conversion implementations for [DataValue].
110 macro_rules! build_conversion_impl {
111     ( $rust_ty:ty, $data_value_ty:ident, $cranelift_ty:ident ) => {
112         impl From<$rust_ty> for DataValue {
113             fn from(data: $rust_ty) -> Self {
114                 DataValue::$data_value_ty(data)
115             }
116         }
117 
118         impl TryInto<$rust_ty> for DataValue {
119             type Error = DataValueCastFailure;
120             fn try_into(self) -> Result<$rust_ty, Self::Error> {
121                 if let DataValue::$data_value_ty(v) = self {
122                     Ok(v)
123                 } else {
124                     Err(DataValueCastFailure::TryInto(
125                         self.ty(),
126                         types::$cranelift_ty,
127                     ))
128                 }
129             }
130         }
131     };
132 }
133 build_conversion_impl!(bool, B, B8);
134 build_conversion_impl!(i8, I8, I8);
135 build_conversion_impl!(i16, I16, I16);
136 build_conversion_impl!(i32, I32, I32);
137 build_conversion_impl!(i64, I64, I64);
138 build_conversion_impl!(u8, U8, I8);
139 build_conversion_impl!(u16, U16, I16);
140 build_conversion_impl!(u32, U32, I32);
141 build_conversion_impl!(u64, U64, I64);
142 build_conversion_impl!(Ieee32, F32, F32);
143 build_conversion_impl!(Ieee64, F64, F64);
144 build_conversion_impl!([u8; 16], V128, I8X16);
145 impl From<Offset32> for DataValue {
146     fn from(o: Offset32) -> Self {
147         DataValue::from(Into::<i32>::into(o))
148     }
149 }
150 
151 impl Display for DataValue {
152     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
153         match self {
154             DataValue::B(dv) => write!(f, "{}", dv),
155             DataValue::I8(dv) => write!(f, "{}", dv),
156             DataValue::I16(dv) => write!(f, "{}", dv),
157             DataValue::I32(dv) => write!(f, "{}", dv),
158             DataValue::I64(dv) => write!(f, "{}", dv),
159             DataValue::U8(dv) => write!(f, "{}", dv),
160             DataValue::U16(dv) => write!(f, "{}", dv),
161             DataValue::U32(dv) => write!(f, "{}", dv),
162             DataValue::U64(dv) => write!(f, "{}", dv),
163             // The Ieee* wrappers here print the expected syntax.
164             DataValue::F32(dv) => write!(f, "{}", dv),
165             DataValue::F64(dv) => write!(f, "{}", dv),
166             // Again, for syntax consistency, use ConstantData, which in this case displays as hex.
167             DataValue::V128(dv) => write!(f, "{}", ConstantData::from(&dv[..])),
168         }
169     }
170 }
171 
172 /// Helper structure for printing bracket-enclosed vectors of [DataValue]s.
173 /// - for empty vectors, display `[]`
174 /// - for single item vectors, display `42`, e.g.
175 /// - for multiple item vectors, display `[42, 43, 44]`, e.g.
176 pub struct DisplayDataValues<'a>(pub &'a [DataValue]);
177 
178 impl<'a> Display for DisplayDataValues<'a> {
179     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
180         if self.0.len() == 1 {
181             write!(f, "{}", self.0[0])
182         } else {
183             write!(f, "[")?;
184             write_data_value_list(f, &self.0)?;
185             write!(f, "]")
186         }
187     }
188 }
189 
190 /// Helper function for displaying `Vec<DataValue>`.
191 pub fn write_data_value_list(f: &mut Formatter<'_>, list: &[DataValue]) -> fmt::Result {
192     match list.len() {
193         0 => Ok(()),
194         1 => write!(f, "{}", list[0]),
195         _ => {
196             write!(f, "{}", list[0])?;
197             for dv in list.iter().skip(1) {
198                 write!(f, ", {}", dv)?;
199             }
200             Ok(())
201         }
202     }
203 }
204 
205 #[cfg(test)]
206 mod test {
207     use super::*;
208 
209     #[test]
210     fn type_conversions() {
211         assert_eq!(DataValue::B(true).ty(), types::B8);
212         assert_eq!(
213             TryInto::<bool>::try_into(DataValue::B(false)).unwrap(),
214             false
215         );
216         assert_eq!(
217             TryInto::<i32>::try_into(DataValue::B(false)).unwrap_err(),
218             DataValueCastFailure::TryInto(types::B8, types::I32)
219         );
220 
221         assert_eq!(DataValue::V128([0; 16]).ty(), types::I8X16);
222         assert_eq!(
223             TryInto::<[u8; 16]>::try_into(DataValue::V128([0; 16])).unwrap(),
224             [0; 16]
225         );
226         assert_eq!(
227             TryInto::<i32>::try_into(DataValue::V128([0; 16])).unwrap_err(),
228             DataValueCastFailure::TryInto(types::I8X16, types::I32)
229         );
230     }
231 }
232