Created
July 12, 2022 13:00
-
-
Save michalmonday/97be57110ae0ea9c92720d00d52131c8 to your computer and use it in GitHub Desktop.
Build 32-bit hex value of a custom RISC-V R-type instruction.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
def reg_index(reg_name): | |
return [ | |
'zero', # always zero (x0) | |
'ra', # return address | |
'sp', # stack pointer | |
'gp', # global pointer | |
'tp', # thread pointer | |
't0', | |
't1', | |
't2', | |
's0', # frame pointer (fp) | |
's1', | |
'a0', # return value | |
'a1', | |
'a2', | |
'a3', | |
'a4', | |
'a5', | |
'a6', | |
'a7', | |
's2', | |
's3', | |
's4', | |
's5', | |
's6', | |
's7', | |
's8', | |
's9', | |
's10', | |
's11', | |
't3', | |
't4', | |
't5', | |
't6' | |
].index(reg_name) | |
def reg_index_to_5_bits(i): | |
return f'{i:05b}' | |
def reg_name_to_bits(name): | |
i = reg_index(name) | |
# print(i) | |
return reg_index_to_5_bits(i) | |
def r_type_instr(func7, rs2_name, rs1_name, func3, rd_name, opcode): | |
rs2 = reg_name_to_bits(rs2_name) | |
rs1 = reg_name_to_bits(rs1_name) | |
rd = reg_name_to_bits(rd_name) | |
# print(rs2_name, rs2, rs1_name, rs1) | |
instr = ''.join([func7, rs2, rs1, func3, rd, opcode]) | |
instr = int(instr, 2) | |
return instr | |
def str_to_r_type_instr(s): | |
s = re.sub(r'[^10]+', '', s) | |
instr = int(s, 2) | |
return instr | |
def print_instr(instr): | |
print(f'.word 0x{instr:08x}') | |
print(f'{instr:032b}') | |
# instr = r_type_instr( | |
# '0000101', # func7 | |
# 't3', # rs2_name | |
# 't4', # rs1_name | |
# '101', # func3 | |
# 't5', # rd_name | |
# '0110011', # opcode | |
# ) | |
instr = r_type_instr( | |
'0000101', # func7 | |
't3', # rs2_name | |
't4', # rs1_name | |
'100', # func3 | |
't0', # rd_name | |
'0110011', # opcode | |
) | |
print_instr(instr) | |
instr = r_type_instr( | |
'0000101', # func7 | |
't3', # rs2_name | |
't4', # rs1_name | |
'110', # func3 | |
't1', # rd_name | |
'0110011', # opcode | |
) | |
print_instr(instr) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment