1#![expect(trivial_numeric_casts, reason = "macro-generated code")]
5
6use core::fmt::{self, Display, Formatter};
7use core::ops::Neg;
8use cranelift_codegen::data_value::{DataValue, DataValueCastFailure};
9use cranelift_codegen::ir::immediates::{Ieee16, Ieee32, Ieee64, Ieee128};
10use cranelift_codegen::ir::{Type, types};
11use thiserror::Error;
12
13use crate::step::{SimdVec, extractlanes};
14
15pub type ValueResult<T> = Result<T, ValueError>;
16
17pub trait DataValueExt: Sized {
18 fn int(n: i128, ty: Type) -> ValueResult<Self>;
20 fn into_int_signed(self) -> ValueResult<i128>;
21 fn into_int_unsigned(self) -> ValueResult<u128>;
22 fn float(n: u64, ty: Type) -> ValueResult<Self>;
23 fn into_float(self) -> ValueResult<f64>;
24 fn is_float(&self) -> bool;
25 fn is_nan(&self) -> ValueResult<bool>;
26 fn bool(b: bool, vec_elem: bool, ty: Type) -> ValueResult<Self>;
27 fn into_bool(self) -> ValueResult<bool>;
28 fn vector(v: [u8; 16], ty: Type) -> ValueResult<Self>;
29 fn into_array(&self) -> ValueResult<[u8; 16]>;
30 fn convert(self, kind: ValueConversionKind) -> ValueResult<Self>;
31 fn concat(self, other: Self) -> ValueResult<Self>;
32
33 fn is_negative(&self) -> ValueResult<bool>;
34 fn is_zero(&self) -> ValueResult<bool>;
35
36 fn umax(self, other: Self) -> ValueResult<Self>;
37 fn smax(self, other: Self) -> ValueResult<Self>;
38 fn umin(self, other: Self) -> ValueResult<Self>;
39 fn smin(self, other: Self) -> ValueResult<Self>;
40
41 fn uno(&self, other: &Self) -> ValueResult<bool>;
43
44 fn add(self, other: Self) -> ValueResult<Self>;
46 fn sub(self, other: Self) -> ValueResult<Self>;
47 fn mul(self, other: Self) -> ValueResult<Self>;
48 fn udiv(self, other: Self) -> ValueResult<Self>;
49 fn sdiv(self, other: Self) -> ValueResult<Self>;
50 fn urem(self, other: Self) -> ValueResult<Self>;
51 fn srem(self, other: Self) -> ValueResult<Self>;
52 fn sqrt(self) -> ValueResult<Self>;
53 fn fma(self, a: Self, b: Self) -> ValueResult<Self>;
54 fn abs(self) -> ValueResult<Self>;
55 fn uadd_checked(self, other: Self) -> ValueResult<Option<Self>>;
56 fn sadd_checked(self, other: Self) -> ValueResult<Option<Self>>;
57 fn uadd_overflow(self, other: Self) -> ValueResult<(Self, bool)>;
58 fn sadd_overflow(self, other: Self) -> ValueResult<(Self, bool)>;
59 fn usub_overflow(self, other: Self) -> ValueResult<(Self, bool)>;
60 fn ssub_overflow(self, other: Self) -> ValueResult<(Self, bool)>;
61 fn umul_overflow(self, other: Self) -> ValueResult<(Self, bool)>;
62 fn smul_overflow(self, other: Self) -> ValueResult<(Self, bool)>;
63
64 fn neg(self) -> ValueResult<Self>;
66 fn copysign(self, sign: Self) -> ValueResult<Self>;
67 fn ceil(self) -> ValueResult<Self>;
68 fn floor(self) -> ValueResult<Self>;
69 fn trunc(self) -> ValueResult<Self>;
70 fn nearest(self) -> ValueResult<Self>;
71
72 fn uadd_sat(self, other: Self) -> ValueResult<Self>;
74 fn sadd_sat(self, other: Self) -> ValueResult<Self>;
75 fn usub_sat(self, other: Self) -> ValueResult<Self>;
76 fn ssub_sat(self, other: Self) -> ValueResult<Self>;
77
78 fn shl(self, other: Self) -> ValueResult<Self>;
80 fn ushr(self, other: Self) -> ValueResult<Self>;
81 fn sshr(self, other: Self) -> ValueResult<Self>;
82 fn rotl(self, other: Self) -> ValueResult<Self>;
83 fn rotr(self, other: Self) -> ValueResult<Self>;
84 fn and(self, other: Self) -> ValueResult<Self>;
85 fn or(self, other: Self) -> ValueResult<Self>;
86 fn xor(self, other: Self) -> ValueResult<Self>;
87 fn not(self) -> ValueResult<Self>;
88
89 fn count_ones(self) -> ValueResult<Self>;
91 fn leading_ones(self) -> ValueResult<Self>;
92 fn leading_zeros(self) -> ValueResult<Self>;
93 fn trailing_zeros(self) -> ValueResult<Self>;
94 fn reverse_bits(self) -> ValueResult<Self>;
95 fn swap_bytes(self) -> ValueResult<Self>;
96
97 fn iter_lanes(&self, ty: Type) -> ValueResult<DataValueIterator>;
99}
100
101#[derive(Error, Debug, PartialEq)]
102pub enum ValueError {
103 #[error("unable to convert type {1} into class {0}")]
104 InvalidType(ValueTypeClass, Type),
105 #[error("unable to convert value into type {0}")]
106 InvalidValue(Type),
107 #[error("unable to convert to primitive integer")]
108 InvalidInteger(#[from] std::num::TryFromIntError),
109 #[error("unable to cast data value")]
110 InvalidDataValueCast(#[from] DataValueCastFailure),
111 #[error("performed a division by zero")]
112 IntegerDivisionByZero,
113 #[error("performed a operation that overflowed this integer type")]
114 IntegerOverflow,
115}
116
117#[derive(Debug, PartialEq)]
118pub enum ValueTypeClass {
119 Integer,
120 Boolean,
121 Float,
122 Vector,
123}
124
125impl Display for ValueTypeClass {
126 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
127 match self {
128 ValueTypeClass::Integer => write!(f, "integer"),
129 ValueTypeClass::Boolean => write!(f, "boolean"),
130 ValueTypeClass::Float => write!(f, "float"),
131 ValueTypeClass::Vector => write!(f, "vector"),
132 }
133 }
134}
135
136#[derive(Debug, Clone)]
137pub enum ValueConversionKind {
138 Exact(Type),
141 Truncate(Type),
144 ExtractUpper(Type),
147 SignExtend(Type),
150 ZeroExtend(Type),
153 RoundNearestEven(Type),
156 ToBoolean,
159 Mask(Type),
161}
162
163macro_rules! unary_match {
165 ( $op:ident($arg1:expr); [ $( $data_value_ty:ident ),* ]; [ $( $return_value_ty:ident ),* ] ) => {
166 match $arg1 {
167 $( DataValue::$data_value_ty(a) => {
168 Ok(DataValue::$data_value_ty($return_value_ty::try_from(a.$op()).unwrap()))
169 } )*
170 _ => unimplemented!()
171 }
172 };
173 ( $op:ident($arg1:expr); [ $( $data_value_ty:ident ),* ] ) => {
174 match $arg1 {
175 $( DataValue::$data_value_ty(a) => { Ok(DataValue::$data_value_ty(a.$op())) } )*
176 _ => unimplemented!()
177 }
178 };
179}
180macro_rules! binary_match {
181 ( $op:ident($arg1:expr, $arg2:expr); [ $( $data_value_ty:ident ),* ] ) => {
182 match ($arg1, $arg2) {
183 $( (DataValue::$data_value_ty(a), DataValue::$data_value_ty(b)) => { Ok(DataValue::$data_value_ty(a.$op(*b))) } )*
184 _ => unimplemented!()
185 }
186 };
187 ( $op:ident($arg1:expr, $arg2:expr); [ $( $data_value_ty:ident ),* ]; [ $( $op_type:ty ),* ] ) => {
188 match ($arg1, $arg2) {
189 $( (DataValue::$data_value_ty(a), DataValue::$data_value_ty(b)) => { Ok(DataValue::$data_value_ty((*a as $op_type).$op(*b as $op_type) as _)) } )*
190 _ => unimplemented!()
191 }
192 };
193 ( option $op:ident($arg1:expr, $arg2:expr); [ $( $data_value_ty:ident ),* ]; [ $( $op_type:ty ),* ] ) => {
194 match ($arg1, $arg2) {
195 $( (DataValue::$data_value_ty(a), DataValue::$data_value_ty(b)) => { Ok((*a as $op_type).$op(*b as $op_type).map(|v| DataValue::$data_value_ty(v as _))) } )*
196 _ => unimplemented!()
197 }
198 };
199 ( pair $op:ident($arg1:expr, $arg2:expr); [ $( $data_value_ty:ident ),* ]; [ $( $op_type:ty ),* ] ) => {
200 match ($arg1, $arg2) {
201 $( (DataValue::$data_value_ty(a), DataValue::$data_value_ty(b)) => {
202 let (f, s) = (*a as $op_type).$op(*b as $op_type);
203 Ok((DataValue::$data_value_ty(f as _), s))
204 } )*
205 _ => unimplemented!()
206 }
207 };
208 ( $op:tt($arg1:expr, $arg2:expr); [ $( $data_value_ty:ident ),* ] ) => {
209 match ($arg1, $arg2) {
210 $( (DataValue::$data_value_ty(a), DataValue::$data_value_ty(b)) => { Ok(DataValue::$data_value_ty(a $op b)) } )*
211 _ => unimplemented!()
212 }
213 };
214 ( $op:tt($arg1:expr, $arg2:expr); [ $( $data_value_ty:ident ),* ]; [ $( $op_type:ty ),* ] ) => {
215 match ($arg1, $arg2) {
216 $( (DataValue::$data_value_ty(a), DataValue::$data_value_ty(b)) => { Ok(DataValue::$data_value_ty(((*a as $op_type) $op (*b as $op_type)) as _)) } )*
217 _ => unimplemented!()
218 }
219 };
220 ( $op:tt($arg1:expr, $arg2:expr); [ $( $data_value_ty:ident ),* ]; [ $( $a_type:ty ),* ]; rhs: $rhs:tt,$rhs_type:ty ) => {
221 match ($arg1, $arg2) {
222 $( (DataValue::$data_value_ty(a), DataValue::$rhs(b)) => { Ok(DataValue::$data_value_ty((*a as $a_type).$op(*b as $rhs_type) as _)) } )*
223 _ => unimplemented!()
224 }
225 };
226}
227
228macro_rules! bitop {
229 ( $op:tt($arg1:expr, $arg2:expr) ) => {
230 Ok(match ($arg1, $arg2) {
231 (DataValue::I8(a), DataValue::I8(b)) => DataValue::I8(a $op b),
232 (DataValue::I16(a), DataValue::I16(b)) => DataValue::I16(a $op b),
233 (DataValue::I32(a), DataValue::I32(b)) => DataValue::I32(a $op b),
234 (DataValue::I64(a), DataValue::I64(b)) => DataValue::I64(a $op b),
235 (DataValue::I128(a), DataValue::I128(b)) => DataValue::I128(a $op b),
236 (DataValue::F32(a), DataValue::F32(b)) => DataValue::F32(a $op b),
237 (DataValue::F64(a), DataValue::F64(b)) => DataValue::F64(a $op b),
238 (DataValue::V128(a), DataValue::V128(b)) => {
239 let mut a2 = a.clone();
240 for (a, b) in a2.iter_mut().zip(b.iter()) {
241 *a = *a $op *b;
242 }
243 DataValue::V128(a2)
244 }
245 _ => unimplemented!(),
246 })
247 };
248}
249
250impl DataValueExt for DataValue {
251 fn int(n: i128, ty: Type) -> ValueResult<Self> {
252 if ty.is_vector() {
253 match ty.bytes() {
256 8 | 16 => Ok(DataValue::read_from_slice_ne(&n.to_ne_bytes(), ty)),
257 _ => Err(ValueError::InvalidType(ValueTypeClass::Vector, ty)),
258 }
259 } else if ty.is_int() {
260 DataValue::from_integer(n, ty).map_err(|_| ValueError::InvalidValue(ty))
261 } else {
262 Err(ValueError::InvalidType(ValueTypeClass::Integer, ty))
263 }
264 }
265
266 fn into_int_signed(self) -> ValueResult<i128> {
267 match self {
268 DataValue::I8(n) => Ok(n as i128),
269 DataValue::I16(n) => Ok(n as i128),
270 DataValue::I32(n) => Ok(n as i128),
271 DataValue::I64(n) => Ok(n as i128),
272 DataValue::I128(n) => Ok(n),
273 _ => Err(ValueError::InvalidType(ValueTypeClass::Integer, self.ty())),
274 }
275 }
276
277 fn into_int_unsigned(self) -> ValueResult<u128> {
278 match self {
279 DataValue::I8(n) => Ok(n as u8 as u128),
280 DataValue::I16(n) => Ok(n as u16 as u128),
281 DataValue::I32(n) => Ok(n as u32 as u128),
282 DataValue::I64(n) => Ok(n as u64 as u128),
283 DataValue::I128(n) => Ok(n as u128),
284 _ => Err(ValueError::InvalidType(ValueTypeClass::Integer, self.ty())),
285 }
286 }
287
288 fn float(bits: u64, ty: Type) -> ValueResult<Self> {
289 match ty {
290 types::F32 => Ok(DataValue::F32(Ieee32::with_bits(u32::try_from(bits)?))),
291 types::F64 => Ok(DataValue::F64(Ieee64::with_bits(bits))),
292 _ => Err(ValueError::InvalidType(ValueTypeClass::Float, ty)),
293 }
294 }
295
296 fn into_float(self) -> ValueResult<f64> {
297 match self {
298 DataValue::F32(n) => Ok(n.as_f32() as f64),
299 DataValue::F64(n) => Ok(n.as_f64()),
300 _ => Err(ValueError::InvalidType(ValueTypeClass::Float, self.ty())),
301 }
302 }
303
304 fn is_float(&self) -> bool {
305 match self {
306 DataValue::F16(_) | DataValue::F32(_) | DataValue::F64(_) | DataValue::F128(_) => true,
307 _ => false,
308 }
309 }
310
311 fn is_nan(&self) -> ValueResult<bool> {
312 match self {
313 DataValue::F32(f) => Ok(f.is_nan()),
314 DataValue::F64(f) => Ok(f.is_nan()),
315 _ => Err(ValueError::InvalidType(ValueTypeClass::Float, self.ty())),
316 }
317 }
318
319 fn bool(b: bool, vec_elem: bool, ty: Type) -> ValueResult<Self> {
320 assert!(ty.is_int());
321 macro_rules! make_bool {
322 ($ty:ident) => {
323 Ok(DataValue::$ty(if b {
324 if vec_elem { -1 } else { 1 }
325 } else {
326 0
327 }))
328 };
329 }
330
331 match ty {
332 types::I8 => make_bool!(I8),
333 types::I16 => make_bool!(I16),
334 types::I32 => make_bool!(I32),
335 types::I64 => make_bool!(I64),
336 types::I128 => make_bool!(I128),
337 _ => Err(ValueError::InvalidType(ValueTypeClass::Integer, ty)),
338 }
339 }
340
341 fn into_bool(self) -> ValueResult<bool> {
342 match self {
343 DataValue::I8(b) => Ok(b != 0),
344 DataValue::I16(b) => Ok(b != 0),
345 DataValue::I32(b) => Ok(b != 0),
346 DataValue::I64(b) => Ok(b != 0),
347 DataValue::I128(b) => Ok(b != 0),
348 _ => Err(ValueError::InvalidType(ValueTypeClass::Boolean, self.ty())),
349 }
350 }
351
352 fn vector(v: [u8; 16], ty: Type) -> ValueResult<Self> {
353 assert!(ty.is_vector() && [2, 4, 8, 16].contains(&ty.bytes()));
354 match ty.bytes() {
355 16 => Ok(DataValue::V128(v)),
356 8 => Ok(DataValue::V64(v[..8].try_into().unwrap())),
357 4 => Ok(DataValue::V32(v[..4].try_into().unwrap())),
358 2 => Ok(DataValue::V16(v[..2].try_into().unwrap())),
359 _ => unreachable!(),
360 }
361 }
362
363 fn into_array(&self) -> ValueResult<[u8; 16]> {
364 match *self {
365 DataValue::V128(v) => Ok(v),
366 DataValue::V64(v) => {
367 let mut v128 = [0; 16];
368 v128[..8].clone_from_slice(&v);
369 Ok(v128)
370 }
371 DataValue::V32(v) => {
372 let mut v128 = [0; 16];
373 v128[..4].clone_from_slice(&v);
374 Ok(v128)
375 }
376 DataValue::V16(v) => {
377 let mut v128 = [0; 16];
378 v128[..2].clone_from_slice(&v);
379 Ok(v128)
380 }
381 _ => Err(ValueError::InvalidType(ValueTypeClass::Vector, self.ty())),
382 }
383 }
384
385 fn convert(self, kind: ValueConversionKind) -> ValueResult<Self> {
386 Ok(match kind {
387 ValueConversionKind::Exact(ty) => match (self, ty) {
388 (val, ty) if val.ty().is_int() && ty.is_int() => {
390 DataValue::from_integer(val.into_int_signed()?, ty)?
391 }
392 (DataValue::I16(n), types::F16) => DataValue::F16(Ieee16::with_bits(n as u16)),
393 (DataValue::I32(n), types::F32) => DataValue::F32(f32::from_bits(n as u32).into()),
394 (DataValue::I64(n), types::F64) => DataValue::F64(f64::from_bits(n as u64).into()),
395 (DataValue::I128(n), types::F128) => DataValue::F128(Ieee128::with_bits(n as u128)),
396 (DataValue::F16(n), types::I16) => DataValue::I16(n.bits() as i16),
397 (DataValue::F32(n), types::I32) => DataValue::I32(n.bits() as i32),
398 (DataValue::F64(n), types::I64) => DataValue::I64(n.bits() as i64),
399 (DataValue::F128(n), types::I128) => DataValue::I128(n.bits() as i128),
400 (DataValue::F32(n), types::F64) => DataValue::F64((n.as_f32() as f64).into()),
401 (dv, t) if (t.is_int() || t.is_float()) && dv.ty() == t => dv,
402 (dv, _) => unimplemented!("conversion: {} -> {:?}", dv.ty(), kind),
403 },
404 ValueConversionKind::Truncate(ty) => {
405 assert!(
406 ty.is_int(),
407 "unimplemented conversion: {} -> {:?}",
408 self.ty(),
409 kind
410 );
411
412 let mask = (1 << (ty.bytes() * 8)) - 1i128;
413 let truncated = self.into_int_signed()? & mask;
414 Self::from_integer(truncated, ty)?
415 }
416 ValueConversionKind::ExtractUpper(ty) => {
417 assert!(
418 ty.is_int(),
419 "unimplemented conversion: {} -> {:?}",
420 self.ty(),
421 kind
422 );
423
424 let shift_amt = (self.ty().bytes() * 8) - (ty.bytes() * 8);
425 let mask = (1 << (ty.bytes() * 8)) - 1i128;
426 let shifted_mask = mask << shift_amt;
427
428 let extracted = (self.into_int_signed()? & shifted_mask) >> shift_amt;
429 Self::from_integer(extracted, ty)?
430 }
431 ValueConversionKind::SignExtend(ty) => match (self, ty) {
432 (DataValue::I8(n), types::I16) => DataValue::I16(n as i16),
433 (DataValue::I8(n), types::I32) => DataValue::I32(n as i32),
434 (DataValue::I8(n), types::I64) => DataValue::I64(n as i64),
435 (DataValue::I8(n), types::I128) => DataValue::I128(n as i128),
436 (DataValue::I16(n), types::I32) => DataValue::I32(n as i32),
437 (DataValue::I16(n), types::I64) => DataValue::I64(n as i64),
438 (DataValue::I16(n), types::I128) => DataValue::I128(n as i128),
439 (DataValue::I32(n), types::I64) => DataValue::I64(n as i64),
440 (DataValue::I32(n), types::I128) => DataValue::I128(n as i128),
441 (DataValue::I64(n), types::I128) => DataValue::I128(n as i128),
442 (dv, _) => unimplemented!("conversion: {} -> {:?}", dv.ty(), kind),
443 },
444 ValueConversionKind::ZeroExtend(ty) => match (self, ty) {
445 (DataValue::I8(n), types::I16) => DataValue::I16(n as u8 as i16),
446 (DataValue::I8(n), types::I32) => DataValue::I32(n as u8 as i32),
447 (DataValue::I8(n), types::I64) => DataValue::I64(n as u8 as i64),
448 (DataValue::I8(n), types::I128) => DataValue::I128(n as u8 as i128),
449 (DataValue::I16(n), types::I32) => DataValue::I32(n as u16 as i32),
450 (DataValue::I16(n), types::I64) => DataValue::I64(n as u16 as i64),
451 (DataValue::I16(n), types::I128) => DataValue::I128(n as u16 as i128),
452 (DataValue::I32(n), types::I64) => DataValue::I64(n as u32 as i64),
453 (DataValue::I32(n), types::I128) => DataValue::I128(n as u32 as i128),
454 (DataValue::I64(n), types::I128) => DataValue::I128(n as u64 as i128),
455 (from, to) if from.ty() == to => from,
456 (dv, _) => unimplemented!("conversion: {} -> {:?}", dv.ty(), kind),
457 },
458 ValueConversionKind::RoundNearestEven(ty) => match (self, ty) {
459 (DataValue::F64(n), types::F32) => DataValue::F32(Ieee32::from(n.as_f64() as f32)),
460 (s, _) => unimplemented!("conversion: {} -> {:?}", s.ty(), kind),
461 },
462 ValueConversionKind::ToBoolean => match self.ty() {
463 ty if ty.is_int() => {
464 DataValue::I8(if self.into_int_signed()? != 0 { 1 } else { 0 })
465 }
466 ty => unimplemented!("conversion: {} -> {:?}", ty, kind),
467 },
468 ValueConversionKind::Mask(ty) => {
469 let b = self.into_bool()?;
470 Self::bool(b, true, ty).unwrap()
471 }
472 })
473 }
474
475 fn concat(self, other: Self) -> ValueResult<Self> {
476 match (self, other) {
477 (DataValue::I64(lhs), DataValue::I64(rhs)) => Ok(DataValue::I128(
478 (((lhs as u64) as u128) | (((rhs as u64) as u128) << 64)) as i128,
479 )),
480 (lhs, rhs) => unimplemented!("concat: {} -> {}", lhs.ty(), rhs.ty()),
481 }
482 }
483
484 fn is_negative(&self) -> ValueResult<bool> {
485 match self {
486 DataValue::F32(f) => Ok(f.is_negative()),
487 DataValue::F64(f) => Ok(f.is_negative()),
488 _ => Err(ValueError::InvalidType(ValueTypeClass::Float, self.ty())),
489 }
490 }
491
492 fn is_zero(&self) -> ValueResult<bool> {
493 match self {
494 DataValue::I8(f) => Ok(*f == 0),
495 DataValue::I16(f) => Ok(*f == 0),
496 DataValue::I32(f) => Ok(*f == 0),
497 DataValue::I64(f) => Ok(*f == 0),
498 DataValue::I128(f) => Ok(*f == 0),
499 DataValue::F16(f) => Ok(f.is_zero()),
500 DataValue::F32(f) => Ok(f.is_zero()),
501 DataValue::F64(f) => Ok(f.is_zero()),
502 DataValue::F128(f) => Ok(f.is_zero()),
503 DataValue::V16(_) | DataValue::V32(_) | DataValue::V64(_) | DataValue::V128(_) => {
504 Err(ValueError::InvalidType(ValueTypeClass::Float, self.ty()))
505 }
506 }
507 }
508
509 fn umax(self, other: Self) -> ValueResult<Self> {
510 let lhs = self.clone().into_int_unsigned()?;
511 let rhs = other.clone().into_int_unsigned()?;
512 if lhs > rhs { Ok(self) } else { Ok(other) }
513 }
514
515 fn smax(self, other: Self) -> ValueResult<Self> {
516 if self > other { Ok(self) } else { Ok(other) }
517 }
518
519 fn umin(self, other: Self) -> ValueResult<Self> {
520 let lhs = self.clone().into_int_unsigned()?;
521 let rhs = other.clone().into_int_unsigned()?;
522 if lhs < rhs { Ok(self) } else { Ok(other) }
523 }
524
525 fn smin(self, other: Self) -> ValueResult<Self> {
526 if self < other { Ok(self) } else { Ok(other) }
527 }
528
529 fn uno(&self, other: &Self) -> ValueResult<bool> {
530 Ok(self.is_nan()? || other.is_nan()?)
531 }
532
533 fn add(self, other: Self) -> ValueResult<Self> {
534 if self.is_float() {
535 binary_match!(+(self, other); [F32, F64])
536 } else {
537 binary_match!(wrapping_add(&self, &other); [I8, I16, I32, I64, I128])
538 }
539 }
540
541 fn sub(self, other: Self) -> ValueResult<Self> {
542 if self.is_float() {
543 binary_match!(-(self, other); [F32, F64])
544 } else {
545 binary_match!(wrapping_sub(&self, &other); [I8, I16, I32, I64, I128])
546 }
547 }
548
549 fn mul(self, other: Self) -> ValueResult<Self> {
550 if self.is_float() {
551 binary_match!(*(self, other); [F32, F64])
552 } else {
553 binary_match!(wrapping_mul(&self, &other); [I8, I16, I32, I64, I128])
554 }
555 }
556
557 fn sdiv(self, other: Self) -> ValueResult<Self> {
558 if self.is_float() {
559 return binary_match!(/(self, other); [F32, F64]);
560 }
561
562 let denominator = other.clone().into_int_signed()?;
563
564 let min = DataValueExt::int(1i128 << (self.ty().bits() - 1), self.ty())?;
566 if self == min && denominator == -1 {
567 return Err(ValueError::IntegerOverflow);
568 }
569
570 if denominator == 0 {
571 return Err(ValueError::IntegerDivisionByZero);
572 }
573
574 binary_match!(/(&self, &other); [I8, I16, I32, I64, I128])
575 }
576
577 fn udiv(self, other: Self) -> ValueResult<Self> {
578 if self.is_float() {
579 return binary_match!(/(self, other); [F32, F64]);
580 }
581
582 let denominator = other.clone().into_int_unsigned()?;
583
584 if denominator == 0 {
585 return Err(ValueError::IntegerDivisionByZero);
586 }
587
588 binary_match!(/(&self, &other); [I8, I16, I32, I64, I128]; [u8, u16, u32, u64, u128])
589 }
590
591 fn srem(self, other: Self) -> ValueResult<Self> {
592 let denominator = other.clone().into_int_signed()?;
593
594 let min = DataValueExt::int(1i128 << (self.ty().bits() - 1), self.ty())?;
596 if self == min && denominator == -1 {
597 return Err(ValueError::IntegerOverflow);
598 }
599
600 if denominator == 0 {
601 return Err(ValueError::IntegerDivisionByZero);
602 }
603
604 binary_match!(%(&self, &other); [I8, I16, I32, I64, I128])
605 }
606
607 fn urem(self, other: Self) -> ValueResult<Self> {
608 let denominator = other.clone().into_int_unsigned()?;
609
610 if denominator == 0 {
611 return Err(ValueError::IntegerDivisionByZero);
612 }
613
614 binary_match!(%(&self, &other); [I8, I16, I32, I64, I128]; [u8, u16, u32, u64, u128])
615 }
616
617 fn sqrt(self) -> ValueResult<Self> {
618 unary_match!(sqrt(&self); [F32, F64]; [Ieee32, Ieee64])
619 }
620
621 fn fma(self, b: Self, c: Self) -> ValueResult<Self> {
622 match (self, b, c) {
623 (DataValue::F32(a), DataValue::F32(b), DataValue::F32(c)) => {
624 #[cfg(all(target_arch = "x86_64", target_os = "windows", target_env = "gnu"))]
627 let res = libm::fmaf(a.as_f32(), b.as_f32(), c.as_f32());
628
629 #[cfg(not(all(
630 target_arch = "x86_64",
631 target_os = "windows",
632 target_env = "gnu"
633 )))]
634 let res = a.as_f32().mul_add(b.as_f32(), c.as_f32());
635
636 Ok(DataValue::F32(res.into()))
637 }
638 (DataValue::F64(a), DataValue::F64(b), DataValue::F64(c)) => {
639 #[cfg(all(target_arch = "x86_64", target_os = "windows", target_env = "gnu"))]
640 let res = libm::fma(a.as_f64(), b.as_f64(), c.as_f64());
641
642 #[cfg(not(all(
643 target_arch = "x86_64",
644 target_os = "windows",
645 target_env = "gnu"
646 )))]
647 let res = a.as_f64().mul_add(b.as_f64(), c.as_f64());
648
649 Ok(DataValue::F64(res.into()))
650 }
651 (a, _b, _c) => Err(ValueError::InvalidType(ValueTypeClass::Float, a.ty())),
652 }
653 }
654
655 fn abs(self) -> ValueResult<Self> {
656 unary_match!(abs(&self); [F32, F64])
657 }
658
659 fn sadd_checked(self, other: Self) -> ValueResult<Option<Self>> {
660 binary_match!(option checked_add(&self, &other); [I8, I16, I32, I64, I128]; [i8, i16, i32, i64, i128])
661 }
662
663 fn uadd_checked(self, other: Self) -> ValueResult<Option<Self>> {
664 binary_match!(option checked_add(&self, &other); [I8, I16, I32, I64, I128]; [u8, u16, u32, u64, u128])
665 }
666
667 fn sadd_overflow(self, other: Self) -> ValueResult<(Self, bool)> {
668 binary_match!(pair overflowing_add(&self, &other); [I8, I16, I32, I64, I128]; [i8, i16, i32, i64, i128])
669 }
670
671 fn uadd_overflow(self, other: Self) -> ValueResult<(Self, bool)> {
672 binary_match!(pair overflowing_add(&self, &other); [I8, I16, I32, I64, I128]; [u8, u16, u32, u64, u128])
673 }
674
675 fn ssub_overflow(self, other: Self) -> ValueResult<(Self, bool)> {
676 binary_match!(pair overflowing_sub(&self, &other); [I8, I16, I32, I64, I128]; [i8, i16, i32, i64, i128])
677 }
678
679 fn usub_overflow(self, other: Self) -> ValueResult<(Self, bool)> {
680 binary_match!(pair overflowing_sub(&self, &other); [I8, I16, I32, I64, I128]; [u8, u16, u32, u64, u128])
681 }
682
683 fn smul_overflow(self, other: Self) -> ValueResult<(Self, bool)> {
684 binary_match!(pair overflowing_mul(&self, &other); [I8, I16, I32, I64, I128]; [i8, i16, i32, i64, i128])
685 }
686
687 fn umul_overflow(self, other: Self) -> ValueResult<(Self, bool)> {
688 binary_match!(pair overflowing_mul(&self, &other); [I8, I16, I32, I64, I128]; [u8, u16, u32, u64, u128])
689 }
690
691 fn neg(self) -> ValueResult<Self> {
692 unary_match!(neg(&self); [F32, F64])
693 }
694
695 fn copysign(self, sign: Self) -> ValueResult<Self> {
696 binary_match!(copysign(&self, &sign); [F32, F64])
697 }
698
699 fn ceil(self) -> ValueResult<Self> {
700 unary_match!(ceil(&self); [F32, F64])
701 }
702
703 fn floor(self) -> ValueResult<Self> {
704 unary_match!(floor(&self); [F32, F64])
705 }
706
707 fn trunc(self) -> ValueResult<Self> {
708 unary_match!(trunc(&self); [F32, F64])
709 }
710
711 fn nearest(self) -> ValueResult<Self> {
712 unary_match!(round_ties_even(&self); [F32, F64])
713 }
714
715 fn sadd_sat(self, other: Self) -> ValueResult<Self> {
716 binary_match!(saturating_add(self, &other); [I8, I16, I32, I64, I128])
717 }
718
719 fn uadd_sat(self, other: Self) -> ValueResult<Self> {
720 binary_match!(saturating_add(&self, &other); [I8, I16, I32, I64, I128]; [u8, u16, u32, u64, u128])
721 }
722
723 fn ssub_sat(self, other: Self) -> ValueResult<Self> {
724 binary_match!(saturating_sub(self, &other); [I8, I16, I32, I64, I128])
725 }
726
727 fn usub_sat(self, other: Self) -> ValueResult<Self> {
728 binary_match!(saturating_sub(&self, &other); [I8, I16, I32, I64, I128]; [u8, u16, u32, u64, u128])
729 }
730
731 fn shl(self, other: Self) -> ValueResult<Self> {
732 let amt = other.convert(ValueConversionKind::Exact(types::I32))?;
733 binary_match!(wrapping_shl(&self, &amt); [I8, I16, I32, I64, I128]; [i8, i16, i32, i64, i128]; rhs: I32,u32)
734 }
735
736 fn ushr(self, other: Self) -> ValueResult<Self> {
737 let amt = other.convert(ValueConversionKind::Exact(types::I32))?;
738 binary_match!(wrapping_shr(&self, &amt); [I8, I16, I32, I64, I128]; [u8, u16, u32, u64, u128]; rhs: I32,u32)
739 }
740
741 fn sshr(self, other: Self) -> ValueResult<Self> {
742 let amt = other.convert(ValueConversionKind::Exact(types::I32))?;
743 binary_match!(wrapping_shr(&self, &amt); [I8, I16, I32, I64, I128]; [i8, i16, i32, i64, i128]; rhs: I32,u32)
744 }
745
746 fn rotl(self, other: Self) -> ValueResult<Self> {
747 let amt = other.convert(ValueConversionKind::Exact(types::I32))?;
748 binary_match!(rotate_left(&self, &amt); [I8, I16, I32, I64, I128]; [i8, i16, i32, i64, i128]; rhs: I32,u32)
749 }
750
751 fn rotr(self, other: Self) -> ValueResult<Self> {
752 let amt = other.convert(ValueConversionKind::Exact(types::I32))?;
753 binary_match!(rotate_right(&self, &amt); [I8, I16, I32, I64, I128]; [i8, i16, i32, i64, i128]; rhs: I32,u32)
754 }
755
756 fn and(self, other: Self) -> ValueResult<Self> {
757 bitop!(&(self, other))
758 }
759
760 fn or(self, other: Self) -> ValueResult<Self> {
761 bitop!(|(self, other))
762 }
763
764 fn xor(self, other: Self) -> ValueResult<Self> {
765 bitop!(^(self, other))
766 }
767
768 fn not(self) -> ValueResult<Self> {
769 Ok(match self {
770 DataValue::I8(a) => DataValue::I8(!a),
771 DataValue::I16(a) => DataValue::I16(!a),
772 DataValue::I32(a) => DataValue::I32(!a),
773 DataValue::I64(a) => DataValue::I64(!a),
774 DataValue::I128(a) => DataValue::I128(!a),
775 DataValue::F32(a) => DataValue::F32(!a),
776 DataValue::F64(a) => DataValue::F64(!a),
777 DataValue::V128(mut a) => {
778 for byte in a.iter_mut() {
779 *byte = !*byte;
780 }
781 DataValue::V128(a)
782 }
783 _ => unimplemented!(),
784 })
785 }
786
787 fn count_ones(self) -> ValueResult<Self> {
788 unary_match!(count_ones(&self); [I8, I16, I32, I64, I128]; [i8, i16, i32, i64, i128])
789 }
790
791 fn leading_ones(self) -> ValueResult<Self> {
792 unary_match!(leading_ones(&self); [I8, I16, I32, I64, I128]; [i8, i16, i32, i64, i128])
793 }
794
795 fn leading_zeros(self) -> ValueResult<Self> {
796 unary_match!(leading_zeros(&self); [I8, I16, I32, I64, I128]; [i8, i16, i32, i64, i128])
797 }
798
799 fn trailing_zeros(self) -> ValueResult<Self> {
800 unary_match!(trailing_zeros(&self); [I8, I16, I32, I64, I128]; [i8, i16, i32, i64, i128])
801 }
802
803 fn reverse_bits(self) -> ValueResult<Self> {
804 unary_match!(reverse_bits(&self); [I8, I16, I32, I64, I128])
805 }
806
807 fn swap_bytes(self) -> ValueResult<Self> {
808 unary_match!(swap_bytes(&self); [I16, I32, I64, I128])
809 }
810
811 fn iter_lanes(&self, ty: Type) -> ValueResult<DataValueIterator> {
812 DataValueIterator::new(self, ty)
813 }
814}
815
816pub struct DataValueIterator {
818 ty: Type,
819 v: SimdVec<DataValue>,
820 idx: usize,
821}
822
823impl DataValueIterator {
824 fn new(dv: &DataValue, ty: Type) -> Result<Self, ValueError> {
825 match extractlanes(dv, ty) {
826 Ok(v) => return Ok(Self { ty, v, idx: 0 }),
827 Err(err) => return Err(err),
828 }
829 }
830}
831
832impl Iterator for DataValueIterator {
833 type Item = DataValue;
834
835 fn next(&mut self) -> Option<Self::Item> {
836 if self.idx >= self.ty.lane_count() as usize {
837 return None;
838 }
839
840 let dv = self.v[self.idx].clone();
841 self.idx += 1;
842 Some(dv)
843 }
844}
845
846#[cfg(test)]
847mod test {
848 use super::*;
849
850 #[test]
851 fn test_iterator_v128() {
852 let dv = DataValue::V128([99, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
853 assert_eq!(simd_sum(dv, types::I8X16), 219);
854 }
855
856 #[test]
857 fn test_iterator_v128_empty() {
858 let dv = DataValue::V128([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
859 assert_eq!(simd_sum(dv, types::I8X16), 0);
860 }
861
862 #[test]
863 fn test_iterator_v128_ones() {
864 let dv = DataValue::V128([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
865 assert_eq!(simd_sum(dv, types::I8X16), 16);
866 }
867
868 #[test]
869 fn test_iterator_v64_empty() {
870 let dv = DataValue::V64([0, 0, 0, 0, 0, 0, 0, 0]);
871 assert_eq!(simd_sum(dv, types::I8X8), 0);
872 }
873 #[test]
874 fn test_iterator_v64_ones() {
875 let dv = DataValue::V64([1, 1, 1, 1, 1, 1, 1, 1]);
876 assert_eq!(simd_sum(dv, types::I8X8), 8);
877 }
878 #[test]
879 fn test_iterator_v64() {
880 let dv = DataValue::V64([10, 20, 30, 40, 50, 60, 70, 80]);
881 assert_eq!(simd_sum(dv, types::I8X8), 360);
882 }
883
884 fn simd_sum(dv: DataValue, ty: types::Type) -> i128 {
885 let itr = dv.iter_lanes(ty).unwrap();
886
887 itr.map(|e| {
888 if let Some(v) = e.into_int_signed().ok() {
889 v
890 } else {
891 0
892 }
893 })
894 .sum()
895 }
896}