summaryrefslogtreecommitdiff
path: root/src/instructions/rvi.rs
blob: e3c0e090e0ee4ca17ce43c9685cd9fd691e873f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use crate::{
    consts::{Addr, DWord},
    core::{Core, InstructionResult},
    decode::Instruction,
    instructions::{
        OpcodeHandler,
        gen_tools::insert_funct3_splitter,
        opcodes::{FUNCT3_ADDI, FUNCT3_SD, OP_IMM, STORE},
    },
    mem::PageNum,
};

pub(super) fn add_instrs(list: &mut [OpcodeHandler; 32]) {
    let funct3_split_op_imm = insert_funct3_splitter(&mut list[OP_IMM as usize].splitter);
    funct3_split_op_imm[FUNCT3_ADDI as usize].handler =
        Some(super::InstructionHandler { runner: addi });

    let funct3_split_store = insert_funct3_splitter(&mut list[STORE as usize].splitter);
    funct3_split_store[FUNCT3_SD as usize].handler = Some(super::InstructionHandler { runner: sd })
}

fn addi(core: &mut Core, instr: Instruction) -> InstructionResult {
    core.reg_write(
        instr.rd(),
        core.reg_read(instr.rs1()).wrapping_add(instr.imm_i()),
    );

    core.pc = core.pc.wrapping_add(4);

    InstructionResult::Normal
}

fn sd(core: &mut Core, instr: Instruction) -> InstructionResult {
    let addr = core.reg_read(instr.rs1()).wrapping_add(instr.imm_s());

    if !addr.is_multiple_of(std::mem::size_of::<DWord>() as Addr) {
        return InstructionResult::Exception(());
    }

    let page = (addr / 4096) as PageNum;
    let offset = (addr & ((4096 / std::mem::size_of::<DWord>() as Addr) - 1)) as u16;
    let value = core.reg_read(instr.rs2());

    match core.mem.write_dword(page, offset, value) {
        Ok(_) => {
            core.pc = core.pc.wrapping_add(4);
            InstructionResult::Normal
        }
        Err(_) => InstructionResult::Exception(()),
    }
}