Skip to content

Instantly share code, notes, and snippets.

@jdtech3
Last active March 4, 2024 01:25
Show Gist options
  • Save jdtech3/24540e488dda4bcdb644d7241afb9b8e to your computer and use it in GitHub Desktop.
Save jdtech3/24540e488dda4bcdb644d7241afb9b8e to your computer and use it in GitHub Desktop.
Generate Nios II assembly to save registers to stack
STORE_MEM_INST = 'stw'
REGISTER_PREFIX = 'r'
STACK_POINTER_REG = 'sp'
RETURN_POINTER_REG = 'ra'
WORD_SIZE = 4
from_reg = int(input("from register: "))
to_reg = int(input("to register: "))
output = []
cur_offset = 0
output.append(f'subi {STACK_POINTER_REG}, {STACK_POINTER_REG}, {WORD_SIZE * (to_reg - from_reg + 2)}')
output.append(f'stw {RETURN_POINTER_REG}, {cur_offset}({STACK_POINTER_REG})')
cur_offset += WORD_SIZE
for reg in range(from_reg, to_reg + 1):
output.append(f'stw {REGISTER_PREFIX}{reg}, {cur_offset}({STACK_POINTER_REG})')
cur_offset += WORD_SIZE
output.append('\n# CODE HERE\n')
cur_offset = 0
output.append(f'ldw {RETURN_POINTER_REG}, {cur_offset}({STACK_POINTER_REG})')
cur_offset += WORD_SIZE
for reg in range(from_reg, to_reg + 1):
output.append(f'ldw {REGISTER_PREFIX}{reg}, {cur_offset}({STACK_POINTER_REG})')
cur_offset += WORD_SIZE
output.append(f'addi {STACK_POINTER_REG}, {STACK_POINTER_REG}, {WORD_SIZE * (to_reg - from_reg + 2)}')
print('-' * 20)
for line in output:
print(line)
@GaryZhous
Copy link

Python Scripting is so good

@LancelotShih
Copy link

WOOOOOOO

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment