Skip to main content

ab_riscv_primitives/instructions/rv64/zk/zkn/
zkne.rs

1//! RV64 Zkne extension
2
3#[cfg(test)]
4mod tests;
5
6use crate::instructions::Instruction;
7use crate::instructions::rv64::zk::zkn::zknd::{Rv64ZkndInstruction, Rv64ZkndKsRnum};
8use crate::registers::general_purpose::Register;
9use ab_riscv_macros::instruction;
10use core::fmt;
11
12/// RISC-V RV64 Zkne instructions
13#[instruction(
14    reorder = [Aes64Es, Aes64Esm, Aes64Ks1i, Aes64Ks2],
15    ignore = [Rv64ZkndInstruction],
16    inherit = [Rv64ZkndInstruction],
17)]
18#[derive(Debug, Clone, Copy)]
19#[derive_const(PartialEq, Eq)]
20pub enum Rv64ZkneInstruction<Reg> {
21    /// AES final round encryption: ShiftRows + SubBytes, no MixColumns
22    Aes64Es { rd: Reg, rs1: Reg, rs2: Reg },
23    /// AES middle round encryption: ShiftRows + SubBytes + MixColumns
24    Aes64Esm { rd: Reg, rs1: Reg, rs2: Reg },
25}
26
27#[instruction]
28const impl<Reg> Instruction for Rv64ZkneInstruction<Reg>
29where
30    Reg: [const] Register<Type = u64>,
31{
32    const ALIGNMENT: u8 = align_of::<u32>() as u8;
33
34    type Reg = Reg;
35
36    #[inline(always)]
37    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic(const))]
38    fn try_decode(instruction: u32) -> Option<Self> {
39        let opcode = (instruction & 0b111_1111) as u8;
40        let rd_bits = ((instruction >> 7) & 0x1f) as u8;
41        let funct3 = ((instruction >> 12) & 0b111) as u8;
42        let rs1_bits = ((instruction >> 15) & 0x1f) as u8;
43        let rs2_bits = ((instruction >> 20) & 0x1f) as u8;
44        let funct7 = ((instruction >> 25) & 0b111_1111) as u8;
45
46        // R-type: OP opcode (0x33)
47        //   aes64es:  funct7=0b001_1001, funct3=0 -> MATCH=0x3200_0033
48        //   aes64esm: funct7=0b001_1011, funct3=0 -> MATCH=0x3600_0033
49        match opcode {
50            0b011_0011 => {
51                if funct3 != 0b000 {
52                    None?;
53                }
54                let rd = Reg::from_bits(rd_bits)?;
55                let rs1 = Reg::from_bits(rs1_bits)?;
56                let rs2 = Reg::from_bits(rs2_bits)?;
57                match funct7 {
58                    0b001_1001 => Some(Self::Aes64Es { rd, rs1, rs2 }),
59                    0b001_1011 => Some(Self::Aes64Esm { rd, rs1, rs2 }),
60                    _ => None,
61                }
62            }
63            _ => None,
64        }
65    }
66
67    #[inline(always)]
68    fn size(&self) -> u8 {
69        size_of::<u32>() as u8
70    }
71}
72
73#[instruction]
74impl<Reg> fmt::Display for Rv64ZkneInstruction<Reg>
75where
76    Reg: fmt::Display + Copy,
77{
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        match self {
80            Self::Aes64Es { rd: rd1, rs1, rs2 } => write!(f, "aes64es {rd1}, {rs1}, {rs2}"),
81            Self::Aes64Esm { rd, rs1, rs2 } => write!(f, "aes64esm {rd}, {rs1}, {rs2}"),
82        }
83    }
84}