Skip to main content

ab_riscv_primitives/instructions/rv32/b/
zbc.rs

1//! RV32 Zbc extension
2
3#[cfg(test)]
4mod tests;
5
6use crate::instructions::Instruction;
7use crate::registers::general_purpose::Register;
8use ab_riscv_macros::instruction;
9use core::fmt;
10
11/// RISC-V RV32 Zbc instruction (Carryless multiplication)
12#[instruction]
13#[derive(Debug, Clone, Copy)]
14#[derive_const(PartialEq, Eq)]
15pub enum Rv32ZbcInstruction<Reg> {
16    Clmul { rd: Reg, rs1: Reg, rs2: Reg },
17    Clmulh { rd: Reg, rs1: Reg, rs2: Reg },
18    Clmulr { rd: Reg, rs1: Reg, rs2: Reg },
19}
20
21#[instruction]
22const impl<Reg> Instruction for Rv32ZbcInstruction<Reg>
23where
24    Reg: [const] Register<Type = u32>,
25{
26    type Reg = Reg;
27
28    #[inline(always)]
29    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic(const))]
30    fn try_decode(instruction: u32) -> Option<Self> {
31        let opcode = (instruction & 0b111_1111) as u8;
32        let rd_bits = ((instruction >> 7) & 0x1f) as u8;
33        let funct3 = ((instruction >> 12) & 0b111) as u8;
34        let rs1_bits = ((instruction >> 15) & 0x1f) as u8;
35        let rs2_bits = ((instruction >> 20) & 0x1f) as u8;
36        let funct7 = ((instruction >> 25) & 0b111_1111) as u8;
37
38        match opcode {
39            // R-type
40            0b011_0011 => {
41                let rd = Reg::from_bits(rd_bits)?;
42                let rs1 = Reg::from_bits(rs1_bits)?;
43                let rs2 = Reg::from_bits(rs2_bits)?;
44                match (funct3, funct7) {
45                    (0b001, 0b000_0101) => Some(Self::Clmul { rd, rs1, rs2 }),
46                    (0b011, 0b000_0101) => Some(Self::Clmulh { rd, rs1, rs2 }),
47                    (0b010, 0b000_0101) => Some(Self::Clmulr { rd, rs1, rs2 }),
48                    _ => None,
49                }
50            }
51            _ => None,
52        }
53    }
54
55    #[inline(always)]
56    fn alignment() -> u8 {
57        align_of::<u32>() as u8
58    }
59
60    #[inline(always)]
61    fn size(&self) -> u8 {
62        size_of::<u32>() as u8
63    }
64}
65
66#[instruction]
67impl<Reg> fmt::Display for Rv32ZbcInstruction<Reg>
68where
69    Reg: fmt::Display,
70{
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        match self {
73            Self::Clmul { rd, rs1, rs2 } => write!(f, "clmul {rd}, {rs1}, {rs2}"),
74            Self::Clmulh { rd, rs1, rs2 } => write!(f, "clmulh {rd}, {rs1}, {rs2}"),
75            Self::Clmulr { rd, rs1, rs2 } => write!(f, "clmulr {rd}, {rs1}, {rs2}"),
76        }
77    }
78}