~charles/awk-riscv

b64c256d15be435405efc0fb02b08290b9bc0ddf — Charles Daniels 10 months ago 10f0d47
add conditional branch instructions
2 files changed, 39 insertions(+), 1 deletions(-)

M riscv.awk
A tests/simulation/condbranch.txt
M riscv.awk => riscv.awk +12 -1
@@ 390,7 390,7 @@ function memread(memaddr,      res) {


# run the CPU for one tick
function nextstate(    inst) {
function nextstate(    inst, branchtarget) {
	inst = memread(PC)

	if (traceinst) {


@@ 423,6 423,9 @@ function nextstate(    inst) {

	PC_NEXT = PC + 4

	# resolve the branch target up front, since we will use it several times
	branchtarget = PC + two2dec(immB(inst))

	# integer register-immediate instructions
	if (op2str(inst) == "ADDI") { regwrite(rd(inst), dec2two(two2dec(regread(rs1(inst))) + two2dec(immI(inst)))) }
	else if (op2str(inst) == "SLTI") { regwrite(rd(inst), two2dec(regread(rs1(inst))) < two2dec(immI(inst))) }


@@ 452,6 455,14 @@ function nextstate(    inst) {
	else if (op2str(inst) == "JAL") { regwrite(rd(inst), PC+4) ; PC_NEXT = PC + two2dec(immJ(inst))}
	else if (op2str(inst) == "JALR") { regwrite(rd(inst), PC+4) ; PC_NEXT = and(two2dec(immI(inst)) + two2dec(regread(rs1(inst))), 0xfffffffe) }

	# conditional branches
	else if (op2str(inst) == "BEQ" ) { if ( regread(rs1(inst)) == regread(rs2(inst)) ) { PC_NEXT = branchtarget } }
	else if (op2str(inst) == "BNE" ) { if ( regread(rs1(inst)) != regread(rs2(inst)) ) { PC_NEXT = branchtarget } }
	else if (op2str(inst) == "BLT" ) { if (two2dec(regread(rs1(inst))) < two2dec(regread(rs2(inst)))) { PC_NEXT = branchtarget } }
	else if (op2str(inst) == "BLTU") { if (regread(rs1(inst)) < regread(rs2(inst))) {PC_NEXT = branchtarget } }
	else if (op2str(inst) == "BGE" ) { if (two2dec(regread(rs1(inst))) >= two2dec(regread(rs2(inst)))) { PC_NEXT = branchtarget } }
	else if (op2str(inst) == "BGEU") { if (regread(rs1(inst)) >= regread(rs2(inst))) {PC_NEXT = branchtarget } }

	PC = PC_NEXT
}


A tests/simulation/condbranch.txt => tests/simulation/condbranch.txt +27 -0
@@ 0,0 1,27 @@
traceregs 1
traceinst 1
tracemem 1

poke 0x000  0x00100293   # addi x5,x0,0x00000001
poke 0x004  0x00100313   # addi x6,x0,0x00000001
poke 0x008  0x00200393   # addi x7,x0,0x00000002
poke 0x00c  0x00000513   # addi x10,x0,0x000000004
poke 0x010  0x00728863   # beq x5,x7,0x00000008
poke 0x014  0x00150513   # addi x10,x10,0x00000007
poke 0x018  0x00628463   # beq x5,x6,0x00000004
poke 0x01c  0x00100513   # addi x10,x0,0x000000019
poke 0x020  0x00629863   # bne x5,x6,0x00000008
poke 0x024  0x00150513   # addi x10,x10,0x000000014
poke 0x028  0x00729463   # bne x5,x7,0x00000004
poke 0x02c  0x00100513   # addi x10,x0,0x0000000116

# TODO: should probably also test blt, bltu, bge, and bgeu

step 100

assert reg 5 1
assert reg 6 1
assert reg 7 2
assert reg 10 2

showregs