ethrex_levm/opcode_handlers/
bitwise_comparison.rs1use crate::{
20 errors::{OpcodeResult, VMError},
21 gas_cost,
22 opcode_handlers::OpcodeHandler,
23 vm::VM,
24};
25use ethrex_common::U256;
26
27pub struct OpLtHandler;
29impl OpcodeHandler for OpLtHandler {
30 #[inline(always)]
31 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
32 vm.current_call_frame.increase_consumed_gas(gas_cost::LT)?;
33
34 let (&lhs, rhs) = vm.current_call_frame.stack.pop1_and_top_mut()?;
35 #[expect(clippy::as_conversions, reason = "safe")]
36 let res = (lhs < *rhs) as u64;
37 store_u64(rhs, res);
38
39 Ok(OpcodeResult::Continue)
40 }
41}
42
43pub struct OpGtHandler;
45impl OpcodeHandler for OpGtHandler {
46 #[inline(always)]
47 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
48 vm.current_call_frame.increase_consumed_gas(gas_cost::GT)?;
49
50 let (&lhs, rhs) = vm.current_call_frame.stack.pop1_and_top_mut()?;
51 #[expect(clippy::as_conversions, reason = "safe")]
52 let res = (lhs > *rhs) as u64;
53 store_u64(rhs, res);
54
55 Ok(OpcodeResult::Continue)
56 }
57}
58
59pub struct OpSLtHandler;
61impl OpcodeHandler for OpSLtHandler {
62 #[inline(always)]
63 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
64 vm.current_call_frame.increase_consumed_gas(gas_cost::SLT)?;
65
66 let (&lhs, slot) = vm.current_call_frame.stack.pop1_and_top_mut()?;
67 let rhs = *slot;
68 let lhs_sign = lhs.bit(255);
69 let rhs_sign = rhs.bit(255);
70
71 let res: u64 = match (lhs_sign, rhs_sign) {
72 (false, true) => 0,
73 (true, false) => 1,
74 #[expect(clippy::as_conversions, reason = "safe")]
75 _ => (lhs < rhs) as u64,
76 };
77 store_u64(slot, res);
78
79 Ok(OpcodeResult::Continue)
80 }
81}
82
83pub struct OpSGtHandler;
85impl OpcodeHandler for OpSGtHandler {
86 #[inline(always)]
87 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
88 vm.current_call_frame.increase_consumed_gas(gas_cost::SGT)?;
89
90 let (&lhs, slot) = vm.current_call_frame.stack.pop1_and_top_mut()?;
91 let rhs = *slot;
92 let lhs_sign = lhs.bit(255);
93 let rhs_sign = rhs.bit(255);
94
95 let res: u64 = match (lhs_sign, rhs_sign) {
96 (false, true) => 1,
97 (true, false) => 0,
98 #[expect(clippy::as_conversions, reason = "safe")]
99 _ => (lhs > rhs) as u64,
100 };
101 store_u64(slot, res);
102
103 Ok(OpcodeResult::Continue)
104 }
105}
106
107pub struct OpEqHandler;
109impl OpcodeHandler for OpEqHandler {
110 #[inline(always)]
111 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
112 vm.current_call_frame.increase_consumed_gas(gas_cost::EQ)?;
113
114 let (&lhs, rhs) = vm.current_call_frame.stack.pop1_and_top_mut()?;
115 #[expect(clippy::as_conversions, reason = "safe")]
116 let res = (lhs == *rhs) as u64;
117 store_u64(rhs, res);
118
119 Ok(OpcodeResult::Continue)
120 }
121}
122
123pub struct OpIsZeroHandler;
125impl OpcodeHandler for OpIsZeroHandler {
126 #[inline(always)]
127 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
128 vm.current_call_frame
129 .increase_consumed_gas(gas_cost::ISZERO)?;
130
131 let slot = vm.current_call_frame.stack.top_mut()?;
133 #[expect(clippy::as_conversions, reason = "safe")]
134 let z = slot.is_zero() as u64;
135 *slot = z.into();
136
137 Ok(OpcodeResult::Continue)
138 }
139}
140
141pub struct OpAndHandler;
143impl OpcodeHandler for OpAndHandler {
144 #[inline(always)]
145 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
146 vm.current_call_frame.increase_consumed_gas(gas_cost::AND)?;
147
148 let (&lhs, rhs) = vm.current_call_frame.stack.pop1_and_top_mut()?;
149 *rhs = lhs & *rhs;
150
151 Ok(OpcodeResult::Continue)
152 }
153}
154
155pub struct OpOrHandler;
157impl OpcodeHandler for OpOrHandler {
158 #[inline(always)]
159 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
160 vm.current_call_frame.increase_consumed_gas(gas_cost::OR)?;
161
162 let (&lhs, rhs) = vm.current_call_frame.stack.pop1_and_top_mut()?;
163 *rhs = lhs | *rhs;
164
165 Ok(OpcodeResult::Continue)
166 }
167}
168
169pub struct OpXorHandler;
171impl OpcodeHandler for OpXorHandler {
172 #[inline(always)]
173 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
174 vm.current_call_frame.increase_consumed_gas(gas_cost::XOR)?;
175
176 let (&lhs, rhs) = vm.current_call_frame.stack.pop1_and_top_mut()?;
177 *rhs = lhs ^ *rhs;
178
179 Ok(OpcodeResult::Continue)
180 }
181}
182
183pub struct OpNotHandler;
185impl OpcodeHandler for OpNotHandler {
186 #[inline(always)]
187 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
188 vm.current_call_frame.increase_consumed_gas(gas_cost::NOT)?;
189
190 let slot = vm.current_call_frame.stack.top_mut()?;
192 *slot = !*slot;
193
194 Ok(OpcodeResult::Continue)
195 }
196}
197
198pub struct OpByteHandler;
200impl OpcodeHandler for OpByteHandler {
201 #[inline(always)]
202 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
203 vm.current_call_frame
204 .increase_consumed_gas(gas_cost::BYTE)?;
205
206 let (&index, slot) = vm.current_call_frame.stack.pop1_and_top_mut()?;
207 *slot = match u8::try_from(index) {
208 #[expect(
209 clippy::arithmetic_side_effects,
210 reason = "x < 32 guard prevents overflow"
211 )]
212 Ok(x) if x < 32 => U256::from(shift_right(slot, 8 * (31 - x), 0).0[0] & 0xff),
213 _ => U256::zero(),
214 };
215
216 Ok(OpcodeResult::Continue)
217 }
218}
219
220pub struct OpShlHandler;
222impl OpcodeHandler for OpShlHandler {
223 #[inline(always)]
224 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
225 vm.current_call_frame.increase_consumed_gas(gas_cost::SHL)?;
226
227 let (&shift_amount, slot) = vm.current_call_frame.stack.pop1_and_top_mut()?;
228 *slot = match u8::try_from(shift_amount) {
229 Ok(shift_amount) => shift_left(slot, shift_amount),
230 Err(_) => U256::zero(),
231 };
232
233 Ok(OpcodeResult::Continue)
234 }
235}
236
237pub struct OpShrHandler;
239impl OpcodeHandler for OpShrHandler {
240 #[inline(always)]
241 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
242 vm.current_call_frame.increase_consumed_gas(gas_cost::SHR)?;
243
244 let (&shift_amount, slot) = vm.current_call_frame.stack.pop1_and_top_mut()?;
245 *slot = match u8::try_from(shift_amount) {
246 Ok(shift_amount) => shift_right(slot, shift_amount, 0),
247 Err(_) => U256::zero(),
248 };
249
250 Ok(OpcodeResult::Continue)
251 }
252}
253
254pub struct OpSarHandler;
256impl OpcodeHandler for OpSarHandler {
257 #[inline(always)]
258 fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
259 vm.current_call_frame.increase_consumed_gas(gas_cost::SAR)?;
260
261 let (&shift_amount, slot) = vm.current_call_frame.stack.pop1_and_top_mut()?;
262 let fill = 0u64.wrapping_sub(slot.0[3] >> 63);
264 *slot = match u8::try_from(shift_amount) {
265 Ok(shift_amount) => shift_right(slot, shift_amount, fill),
266 Err(_) => U256([fill; 4]),
267 };
268
269 Ok(OpcodeResult::Continue)
270 }
271}
272
273#[inline(always)]
279fn store_u64(slot: &mut U256, value: u64) {
280 #[cfg(all(target_arch = "x86_64", target_feature = "avx"))]
281 #[expect(
282 unsafe_code,
283 reason = "a U256 is 32 bytes, so one unaligned 32-byte store covers exactly the slot"
284 )]
285 unsafe {
286 use std::arch::x86_64::{_mm256_set_epi64x, _mm256_storeu_si256};
287 const { assert!(size_of::<U256>() == 32) };
289 _mm256_storeu_si256(
290 std::ptr::from_mut(slot).cast(),
291 _mm256_set_epi64x(0, 0, 0, value.cast_signed()),
292 );
293 }
294 #[cfg(not(all(target_arch = "x86_64", target_feature = "avx")))]
295 {
296 *slot = U256::from(value);
297 }
298}
299
300#[inline(always)]
307fn shift_right(value: &U256, shift: u8, fill: u64) -> U256 {
308 let bits = u32::from(shift % 64);
309 match shift / 64 {
310 0 => shift_right_words::<0>(&value.0, bits, fill),
311 1 => shift_right_words::<1>(&value.0, bits, fill),
312 2 => shift_right_words::<2>(&value.0, bits, fill),
313 _ => shift_right_words::<3>(&value.0, bits, fill),
314 }
315}
316
317#[inline(always)]
319fn shift_left(value: &U256, shift: u8) -> U256 {
320 let bits = u32::from(shift % 64);
321 match shift / 64 {
322 0 => shift_left_words::<0>(&value.0, bits),
323 1 => shift_left_words::<1>(&value.0, bits),
324 2 => shift_left_words::<2>(&value.0, bits),
325 _ => shift_left_words::<3>(&value.0, bits),
326 }
327}
328
329#[inline(always)]
331#[expect(
332 clippy::arithmetic_side_effects,
333 reason = "limb indexes and bits < 64 are bounded"
334)]
335fn shift_right_words<const WORDS: usize>(limbs: &[u64; 4], bits: u32, fill: u64) -> U256 {
336 let word = |i: usize| limbs.get(i).copied().unwrap_or(fill);
337 let mut out = [fill; 4];
338 for (i, limb) in out.iter_mut().enumerate().take(4 - WORDS) {
339 *limb = funnel_right(word(i + WORDS + 1), word(i + WORDS), bits);
340 }
341 U256(out)
342}
343
344#[inline(always)]
346#[expect(
347 clippy::arithmetic_side_effects,
348 reason = "limb indexes and bits < 64 are bounded"
349)]
350fn shift_left_words<const WORDS: usize>(limbs: &[u64; 4], bits: u32) -> U256 {
351 let word = |i: usize| limbs.get(i).copied().unwrap_or(0);
352 let mut out = [0u64; 4];
353 for (i, limb) in out.iter_mut().enumerate().skip(WORDS) {
354 let low = if i > WORDS { word(i - WORDS - 1) } else { 0 };
355 *limb = (word(i - WORDS) << bits) | ((low >> 1) >> (63 - bits));
356 }
357 U256(out)
358}
359
360#[inline(always)]
362#[expect(clippy::arithmetic_side_effects, reason = "bits < 64")]
363fn funnel_right(high: u64, low: u64, bits: u32) -> u64 {
364 (low >> bits) | ((high << 1) << (63 - bits))
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370
371 #[expect(
372 clippy::arithmetic_side_effects,
373 reason = "test values: shifts and a wrapping LCG on U256"
374 )]
375 fn values() -> Vec<U256> {
376 let mut values = vec![
377 U256::zero(),
378 U256::one(),
379 U256::MAX,
380 U256::one() << 255,
381 U256::from_big_endian(&[0x80; 32]),
382 U256::from_big_endian(&[0x7f; 32]),
383 ];
384 let mut x = U256::from(0x9e37_79b9_7f4a_7c15u64);
385 for _ in 0..16 {
386 x = x.overflowing_mul(U256::from(0x5851_f42d_4c95_7f2du64)).0
387 ^ (x >> 7)
388 ^ U256::from(0x1405_7b7e_f767_814fu64);
389 values.push(x);
390 }
391 values
392 }
393
394 #[test]
395 fn shifts_match_u256() {
396 for value in values() {
397 let negative = value.bit(255);
398 for shift in 0u8..=255 {
399 assert_eq!(
400 shift_left(&value, shift),
401 value << shift,
402 "{value:x} << {shift}"
403 );
404 assert_eq!(
405 shift_right(&value, shift, 0),
406 value >> shift,
407 "{value:x} >> {shift}"
408 );
409 let sar = if negative {
410 !(!value >> shift)
411 } else {
412 value >> shift
413 };
414 let fill = if negative { u64::MAX } else { 0 };
415 assert_eq!(
416 shift_right(&value, shift, fill),
417 sar,
418 "{value:x} sar {shift}"
419 );
420 }
421 }
422 }
423
424 #[test]
425 fn byte_extraction_matches_u256() {
426 for value in values() {
427 for x in 0u8..32 {
428 let expected = U256::from(value.byte(usize::from(31 - x)));
429 let got = U256::from(shift_right(&value, 8 * (31 - x), 0).0[0] & 0xff);
430 assert_eq!(got, expected, "{value:x} byte {x}");
431 }
432 }
433 }
434}