Skip to content

Instantly share code, notes, and snippets.

@ashafq
Created May 8, 2020 17:23
Show Gist options
  • Save ashafq/8345e4641dc864d2c559136bad03056a to your computer and use it in GitHub Desktop.
Save ashafq/8345e4641dc864d2c559136bad03056a to your computer and use it in GitHub Desktop.
Fizzbuzz in RV32IM assembly
//
// FizzBuzz in RISC-V Assembly
// build: riscv64-elf-gcc -mcmodel=medany -nostdlib \
// -march=rv32im -mabi=ilp32 -o start start.s
// run: Open in Ripes simulator ;)
//
.section .rodata
// Strings need to be aliged to two byte boundaries
.align 2
s_fizz:
.asciz "fizz\n"
.align 2
s_buzz:
.asciz "buzz\n"
.align 2
s_fizzbuzz:
.asciz "fizzbuzz\n"
//
// Constants
//
.equ ENV_PRINT_INT, 1
.equ ENV_PRINT_FLOAT, 2
.equ ENV_PRINT_STRING, 4
.equ ENV_EXIT, 10
.equ ENV_PRINT_CHAR, 11
//
// Macro helpers
//
.macro puts arg
la a0, \arg
li a7, ENV_PRINT_STRING
ecall
.endm
.macro print_int arg
mv a0, \arg
li a7, ENV_PRINT_INT
ecall
li a0, '\n'
li a7, ENV_PRINT_CHAR
ecall
.endm
.macro exit
li a7, ENV_EXIT
ecall
.endm
.section .text
.global _start
.type _start, @function
_start:
// Prologue
// The stack needs to be aliged to 16 byte boundary.
// Thus, the stack pointer needs to allocate extra.
addi sp, sp, -48
// Push callee save-registers to stack
sw ra, 44(sp)
sw s0, 40(sp)
sw s1, 36(sp)
sw s2, 32(sp)
sw s3, 28(sp)
sw s4, 24(sp)
// Set up counters
mv s0, zero
li s1, 100
li s2, 3
li s3, 5
li s4, 15
fizzbuzz_loop: // Main function loop
addi s0, s0, 1
// Branch operations, if divisible by 3, 5, or 15
rem s5, s0, s4 // if (n % 15 == 0)
beqz s5, p_fizzbuzz // print (fizzbuzz)
rem s5, s0, s3 // if (n % 5 == 0)
beqz s5, p_buzz // print (fizz)
rem s5, s0, s2 // if (n % 3 == 0)
beqz s5, p_fizz // print (fizz)
// Base case, print the number
PRINT_INT s0
next_iter:
blt s0, s1, fizzbuzz_loop
lw ra, 44(sp)
lw s0, 40(sp)
lw s1, 36(sp)
lw s2, 32(sp)
lw s3, 28(sp)
lw s4, 24(sp)
addi sp, sp, 48
EXIT
ret
p_fizz:
PUTS s_fizz
j next_iter
p_buzz:
PUTS s_buzz
j next_iter
p_fizzbuzz:
PUTS s_fizzbuzz
j next_iter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment