lib_rv32 0.1.1

A library and CLI tool for emulating, testing, and learning RISC-V.
Documentation
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use crate::decode::*;
use crate::{b_imm, func3, func7, i_imm, j_imm, opcode, rd, rs1, rs2, s_imm, u_imm};
use crate::{traits::Memory, traits::RegisterFile, RiscvError, REG_NAMES};

use log::info;

/// Decode and execute instruction. This will use the program counter to
/// fetch an instruction from memory, decode/evaluate it, and commit the
/// results to `pc`, `mem`, and `rf`.
///
/// It logs using the `log` crate. If a logger is registered, log outputs
/// are in this format:
///
/// `[PC] instruction  |  op  rd, rs1, rs2  |  <output generated by mem/rf>\n`
///
/// Parameters:
///     `ir`: The instruction
///     `mem`: The memory which implements the `Memory` trait
///     `rf`: The register file which implements the `RegisterFile` trait
///
/// Returns:
///     `Result<u32, RiscvError>`: Returns the next program counter and
///     the error that occurred during execution, if one exists.
///
/// Example:
/// ```
/// use lib_rv32::mcu::*;
/// use lib_rv32::exec_one;
///
/// // Create an implementation of `pc`/`mem`/`rf`.
/// let mut mcu = Mcu::new(1024 * 64);
///
/// // Program MCU.
/// let instruction = 0x018c0c33;
/// mcu.mem.write_word(0x0, instruction).unwrap();
///
/// // Execute a single instruction.
/// exec_one(&mut mcu.pc, &mut mcu.mem, &mut mcu.rf).unwrap();
/// ```
///
/// A note on signedness:
///
/// We interpret everything as an unsigned 32-bit integer (u32).
/// This works great since the assembler encodes signed numbers
/// as two's-complement. So, if we read '-1' encoded in 2C from the
/// register-file, then add it to another number, the overflow
/// will result in a correct operation. There is--in general--no
/// need to care about the signedness of what we are operating on.
///
/// The only exception to this is comparisons and loading
/// bytes/half-words. For comparisons, we need to consider the sign
/// due to the sign bit being the MSB. For loading units smaller than
/// a word, we need to sign extend them before putting them into the
/// 32-bit registers.
pub fn exec_one<M, R>(pc: &mut u32, mem: &mut M, rf: &mut R) -> Result<(), RiscvError>
where
    M: Memory,
    R: RegisterFile,
{
    let ir = mem.fetch(*pc);
    if let Err(why) = ir {
        return Err(why);
    }
    let ir = ir.unwrap();
    let opcode = opcode!(ir) as u8;

    info!("[{:04x}]  {:08x}  |  ", pc, ir);

    return match opcode {
        OPCODE_LUI => {
            let rd = rd!(ir);
            let imm = u_imm!(ir);

            info!(
                "{:25} |  ",
                format!(
                    "{:6} {}, 0x{:x} ({})",
                    "lui", REG_NAMES[rd as usize], imm, imm as i32
                )
            );

            if let Err(why) = rf.write(rd, imm) {
                return Err(why);
            }
            *pc += 4;

            info!("\n");
            Ok(())
        }

        OPCODE_AUIPC => {
            let rd = rd!(ir);
            let imm = u_imm!(ir);

            info!(
                "{:25} |  ",
                format!(
                    "{:6} {}, 0x{:x}",
                    "auipc",
                    REG_NAMES[rd as usize],
                    (imm >> 12)
                )
            );

            if let Err(why) = rf.write(rd, *pc + imm) {
                return Err(why);
            }
            *pc += 4;

            info!("\n");
            Ok(())
        }

        OPCODE_JAL => {
            let rd = rd!(ir);
            let imm = j_imm!(ir);

            info!(
                "{:25} |  ",
                format!(
                    "{:6} {}, 0x{:x} ({})",
                    "jal", REG_NAMES[rd as usize], imm, imm as i32
                )
            );

            if let Err(why) = rf.write(rd, *pc + 4) {
                return Err(why);
            }
            *pc = pc.overflowing_add(imm).0;
            info!("pc <- 0x{:x}; ", pc);

            info!("\n");
            Ok(())
        }

        OPCODE_JALR => {
            let rd = rd!(ir);
            let rs1 = rs1!(ir);
            let imm = i_imm!(ir);

            info!(
                "{:25} |  ",
                format!(
                    "{:6} {}, ({}){}",
                    "jalr", REG_NAMES[rd as usize], imm as i32, REG_NAMES[rs1 as usize]
                )
            );

            let rs1_data = match rf.read(rs1) {
                Ok(d) => d,
                Err(why) => return Err(why),
            };
            if let Err(why) = rf.write(rd, *pc + 4) {
                return Err(why);
            }

            *pc = rs1_data.overflowing_add(imm).0;
            info!("pc <- 0x{:x}; ", pc);

            info!("\n");
            Ok(())
        }

        OPCODE_BRANCH => {
            let rs1 = rs1!(ir);
            let rs1_data = match rf.read(rs1) {
                Ok(d) => d,
                Err(why) => return Err(why),
            };
            let rs2 = rs2!(ir);
            let rs2_data = match rf.read(rs2) {
                Ok(d) => d,
                Err(why) => return Err(why),
            };
            let func3 = func3!(ir);
            let taken = match func3 {
                FUNC3_BEQ => rs1_data == rs2_data,
                FUNC3_BNE => rs1_data != rs2_data,
                FUNC3_BLT => rs1_data < rs2_data,
                FUNC3_BGE => rs1_data >= rs2_data,
                FUNC3_BLTU => rs1_data < rs2_data,
                FUNC3_BGEU => rs1_data > rs2_data,
                _ => return Err(RiscvError::InvalidFunc3Error(ir, func3)),
            };
            let imm = b_imm!(ir);

            info!(
                "{:25} |  {}",
                format!(
                    "{:6} {}, {}, {}",
                    match func3 {
                        FUNC3_BEQ => "beq",
                        FUNC3_BNE => "bne",
                        FUNC3_BLT => "blt",
                        FUNC3_BGE => "bge",
                        FUNC3_BLTU => "bltu",
                        FUNC3_BGEU => "bgeu",
                        _ => "",
                    },
                    REG_NAMES[rs1 as usize],
                    REG_NAMES[rs2 as usize],
                    imm as i32,
                ),
                if taken {
                    "branch taken; "
                } else {
                    "branch not taken; "
                }
            );

            if taken {
                *pc = pc.overflowing_add(imm).0;
                info!("pc <- 0x{:x}; ", pc);
            } else {
                *pc += 4;
            }

            info!("\n");
            Ok(())
        }

        OPCODE_LOAD => {
            let rs1 = rs1!(ir);
            let base = match rf.read(rs1) {
                Ok(d) => d,
                Err(why) => return Err(why),
            };
            let imm = i_imm!(ir);
            let addr = base.overflowing_add(imm).0;
            let rd = rd!(ir);
            let func3 = func3!(ir);

            info!(
                "{:25} |  ",
                format!(
                    "{:6} {}, {}({})",
                    match func3 {
                        FUNC3_LB => "lb",
                        FUNC3_LH => "lh",
                        FUNC3_LBU => "lbu",
                        FUNC3_LHU => "lhu",
                        FUNC3_LW => "lw",
                        _ => "",
                    },
                    REG_NAMES[rd as usize],
                    imm as i32,
                    REG_NAMES[rs1 as usize]
                )
            );

            if let Err(why) = rf.write(
                rd,
                match {
                    match func3 {
                        FUNC3_LB => match mem.read_byte(addr) {
                            Ok(d) => Ok((d as i8) as u32), // sign-extension
                            Err(why) => return Err(why),
                        },
                        FUNC3_LH => match mem.read_half_word(addr) {
                            Ok(d) => Ok((d as i16) as u32), // sign-extension
                            Err(why) => return Err(why),
                        },
                        FUNC3_LBU => mem.read_byte(addr),
                        FUNC3_LHU => mem.read_half_word(addr),
                        FUNC3_LW => mem.read_word(addr),
                        _ => return Err(RiscvError::InvalidFunc3Error(ir, func3)),
                    }
                } {
                    Ok(d) => d,
                    Err(why) => return Err(why),
                },
            ) {
                return Err(why);
            }
            *pc += 4;

            info!("\n");
            Ok(())
        }

        OPCODE_STORE => {
            let rs1 = rs1!(ir);
            let rs2 = rs2!(ir);
            let imm = s_imm!(ir);
            let func3 = func3!(ir);

            info!(
                "{:25} |  ",
                format!(
                    "{:6} {}, {}({})",
                    match func3 {
                        FUNC3_SB => "sb",
                        FUNC3_SH => "sh",
                        FUNC3_SW => "sw",
                        _ => "",
                    },
                    REG_NAMES[rs2 as usize],
                    imm as i32,
                    REG_NAMES[rs1 as usize]
                )
            );

            let addr = match rf.read(rs1) {
                Ok(d) => d,
                Err(why) => return Err(why),
            }
            .overflowing_add(imm)
            .0;
            let data = match rf.read(rs2) {
                Ok(d) => d,
                Err(why) => return Err(why),
            };
            if let Err(why) = match func3 {
                FUNC3_SB => mem.write_byte(addr, data),
                FUNC3_SH => mem.write_half_word(addr, data),
                FUNC3_SW => mem.write_word(addr, data),
                _ => Err(RiscvError::InvalidFunc3Error(ir, func3!(ir))),
            } {
                return Err(why);
            }
            *pc += 4;

            info!("\n");
            Ok(())
        }

        OPCODE_ARITHMETIC | OPCODE_ARITHMETIC_IMM => {
            let rd = rd!(ir);
            let rs1 = rs1!(ir);
            let lhs = match rf.read(rs1) {
                Ok(d) => d,
                Err(why) => return Err(why),
            };
            let rhs = match opcode {
                OPCODE_ARITHMETIC => match rf.read(rs2!(ir)) {
                    Ok(d) => d,
                    Err(why) => return Err(why),
                },
                OPCODE_ARITHMETIC_IMM => i_imm!(ir),
                _ => return Err(RiscvError::InvalidOpcodeError(ir, opcode!(ir))),
            };
            let ir_name: &str;
            let bi_operator = match func3!(ir) {
                // This func3 is complicated, it depends on whether we're
                // using immediates or not.
                FUNC3_ADD_SUB => match opcode {
                    OPCODE_ARITHMETIC => match func3!(ir) {
                        FUNC7_SUB => {
                            ir_name = "sub";
                            |l: u32, r: u32| l.overflowing_sub(r).0
                        }
                        FUNC7_ADD => {
                            ir_name = "add";
                            |l: u32, r: u32| l.overflowing_add(r).0
                        }
                        _ => return Err(RiscvError::InvalidFunc7Error(ir, func7!(ir))),
                    },
                    OPCODE_ARITHMETIC_IMM => {
                        ir_name = "add";
                        |l: u32, r: u32| l.overflowing_add(r).0
                    }
                    _ => return Err(RiscvError::InvalidOpcodeError(ir, opcode!(ir))),
                },
                FUNC3_SLL => {
                    ir_name = "sll";
                    |l: u32, r: u32| l << r
                }
                FUNC3_SLT => {
                    ir_name = "slt";
                    // sign-extension
                    |l: u32, r: u32| if (l as i32) < (r as i32) { 1 } else { 0 }
                }
                FUNC3_SLTU => {
                    ir_name = "sltu";
                    |l: u32, r: u32| if l < r { 1 } else { 0 }
                }
                FUNC3_XOR => {
                    ir_name = "xor";
                    |l: u32, r: u32| l ^ r
                }
                FUNC3_SRA_SRL => match func7!(ir) {
                    FUNC7_SRA => {
                        ir_name = "sra";
                        |l: u32, r: u32| ((l as i32) >> r) as u32 // sign-extension
                    }
                    FUNC7_SRL => {
                        ir_name = "srl";
                        |l: u32, r: u32| l >> r
                    }
                    _ => return Err(RiscvError::InvalidFunc3Error(ir, func3!(ir))),
                },
                FUNC3_OR => {
                    ir_name = "or";
                    |l: u32, r: u32| l | r
                }
                FUNC3_AND => {
                    ir_name = "and";
                    |l: u32, r: u32| l & r
                }
                _ => return Err(RiscvError::InvalidFunc3Error(ir, func3!(ir))),
            };

            info!(
                "{:25} |  ",
                format!(
                    "{:6} {}, {}, {}",
                    ir_name.to_owned()
                        + match opcode {
                            OPCODE_ARITHMETIC => "",
                            OPCODE_ARITHMETIC_IMM => "i",
                            _ => "?",
                        },
                    REG_NAMES[rd as usize],
                    REG_NAMES[rs1 as usize],
                    match opcode {
                        OPCODE_ARITHMETIC => String::from(REG_NAMES[rs2!(ir) as usize]),
                        OPCODE_ARITHMETIC_IMM => (i_imm!(ir) as i32).to_string(),
                        _ => String::from("?"),
                    }
                )
            );

            if let Err(why) = rf.write(rd!(ir), bi_operator(lhs, rhs)) {
                return Err(why);
            }
            *pc += 4;

            info!("\n");
            Ok(())
        }
        _ => Err(RiscvError::InvalidOpcodeError(ir, opcode!(ir))),
    };
}