Skip to main content

ab_riscv_primitives/instructions/
zicond.rs

1//! Zicond 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 Zicond instruction (Integer Conditional Operations)
12#[instruction]
13#[derive(Debug, Clone, Copy)]
14#[derive_const(PartialEq, Eq)]
15pub enum ZicondInstruction<Reg> {
16    /// `czero.eqz rd, rs1, rs2` - move zero to `rd` if `rs2 == 0`, else move `rs1`
17    CzeroEqz { rd: Reg, rs1: Reg, rs2: Reg },
18    /// `czero.nez rd, rs1, rs2` - move zero to `rd` if `rs2 != 0`, else move `rs1`
19    CzeroNez { rd: Reg, rs1: Reg, rs2: Reg },
20}
21
22#[instruction]
23const impl<Reg> Instruction for ZicondInstruction<Reg>
24where
25    Reg: [const] Register,
26{
27    const ALIGNMENT: u8 = align_of::<u32>() as u8;
28
29    type Reg = Reg;
30
31    #[inline(always)]
32    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic(const))]
33    fn try_decode(instruction: u32) -> Option<Self> {
34        let opcode = (instruction & 0b111_1111) as u8;
35        let rd_bits = ((instruction >> 7) & 0x1f) as u8;
36        let funct3 = ((instruction >> 12) & 0b111) as u8;
37        let rs1_bits = ((instruction >> 15) & 0x1f) as u8;
38        let rs2_bits = ((instruction >> 20) & 0x1f) as u8;
39        let funct7 = ((instruction >> 25) & 0x7f) as u8;
40
41        // Both Zicond instructions share opcode=0x33 (OP) and funct7=0x07
42        match (opcode, funct7) {
43            (0b011_0011, 0b000_0111) => {
44                let rd = Reg::from_bits(rd_bits)?;
45                let rs1 = Reg::from_bits(rs1_bits)?;
46                let rs2 = Reg::from_bits(rs2_bits)?;
47                match funct3 {
48                    0b101 => Some(Self::CzeroEqz { rd, rs1, rs2 }),
49                    0b111 => Some(Self::CzeroNez { rd, rs1, rs2 }),
50                    _ => None,
51                }
52            }
53            _ => None,
54        }
55    }
56
57    #[inline(always)]
58    fn size(&self) -> u8 {
59        size_of::<u32>() as u8
60    }
61}
62
63impl<Reg> fmt::Display for ZicondInstruction<Reg>
64where
65    Reg: fmt::Display,
66{
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self {
69            Self::CzeroEqz { rd, rs1, rs2 } => write!(f, "czero.eqz {rd}, {rs1}, {rs2}"),
70            Self::CzeroNez { rd, rs1, rs2 } => write!(f, "czero.nez {rd}, {rs1}, {rs2}"),
71        }
72    }
73}