diff options
| author | Miquel Sabaté Solà <mikisabate@gmail.com> | 2024-08-12 14:50:07 +0000 |
|---|---|---|
| committer | Miquel Sabaté Solà <mikisabate@gmail.com> | 2024-12-05 16:02:17 +0100 |
| commit | 8e968078e6aee470a02bed7728100b2df1877e90 (patch) | |
| tree | 8f64d8a0e8d8e7a9329a8239fd3c57ce217d5ff7 /basics/factorial.S | |
| parent | c173df46a0a12fe52fdf13323f967e9117462096 (diff) | |
| download | farga-8e968078e6aee470a02bed7728100b2df1877e90.tar.gz farga-8e968078e6aee470a02bed7728100b2df1877e90.zip | |
basics: Add some examples on RISC-V assembly
Signed-off-by: Miquel Sabaté Solà <mikisabate@gmail.com>
Diffstat (limited to 'basics/factorial.S')
| -rw-r--r-- | basics/factorial.S | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/basics/factorial.S b/basics/factorial.S new file mode 100644 index 0000000..7e3df12 --- /dev/null +++ b/basics/factorial.S @@ -0,0 +1,28 @@ +.text +.globl factorial +.type factorial, @function + +factorial: + // If input <= 1, just return the given thing. + addi t0, zero, 1 + bgt a0, t0, else + jr ra +else: + // Preserve the argument and the return address before the call. + addi sp, sp, -16 + sd a0, 0(sp) + sd ra, 8(sp) + + // Call the same function but with a value of argument-1. + addi a0, a0, -1 + call factorial + + // Restore back the original argument and the return address. Then multiply + // the original argument with the returned one from the previous call. + ld t1, 0(sp) + ld ra, 8(sp) + addi sp, sp, 16 + mul a0, t1, a0 + + // And return to the caller. + jr ra |
