title: Calculate nth Fibonacci number using RISC-V (RV32I) compiler without recursion
body: <p>I have written a code for calculating nth fibonacci number in RISC-V assembly language. It has two parts- <code>fib.s</code> and <code>runtest.s</code>, which loads the value of <code>n</code> into <code>a0</code> and calls <code>fib</code>, which calculates the nth fibonacci number (without recursion), loads the result into <code>a0</code> itself and returns. Here is my code:</p>
  <pre><code>.global fib              # the runtest.s will give an a0 value as input n and call fib 
  fib:
      li a1, 0             # This is a
      li a2, 1             # This is b
      li a3, 0             # This is c 
      li a4, 2             # This is i
     
      li a6, 2             # dummy, just to check a0 with
      ble a0, a6, cond1    # check if a0 &lt;= 2
      bgt a0, a6, head     # if a0 &gt; 2, proceed to loop
  
  head:                    # start of loop
      add a3, a1, a2       # Here I'm implementing the space optimized version of fibonacci series without recursion:
      mv a1, a2            # for i in range(2, n+1): c = a + b; a = b; b = c; return b
      mv a2, a3            
      addi a4, a4, 1
      blt a4, a0, head
      bge a4, a0, end      # iterates n-1 times and goes to end
  
  cond1:
      li a0, 1             # if n==1 or n==2 return 1
      li a7, 93
      ecall
  
  end:
      mv a0, a2            # copying the value of a2 (which is b) to a0, since the testbench
      li a7, 93            # runtest.s is setup that way.
      ecall
  </code></pre>
  <p>And here is my testbench (<code>runtest.s</code>):</p>
  <pre><code>.global _start
  _start:
      # Load 'n' into a0 and call fib
      # Test 1
      li      a0,1  # Check n'th Fib number
      call    fib
      li      a5,1  # Expected result
      bne     a0,a5,.FINISH
      # Test 2
      li      a0,3  
      call    fib
      li      a5,3  
      bne     a0,a5,.FINISH
      # Test 3
      li      a0,7  
      call    fib
      li      a5,13  
      bne     a0,a5,.FINISH
      # Test 4
      li      a0,9 
      call    fib
      li      a5,34
      bne     a0,a5,.FINISH
      # Test 5
      li      a0,20 
      call    fib
      li      a5,6765 
      bne     a0,a5,.FINISH
      # Test 6
      li      a0,30
      call    fib
      li      a5,832040 
      bne     a0,a5,.FINISH
      # Finished tests
      li      a5,0  # All passed
  .FINISH:
      mv      a0, a5
      li      a7, 93
      ecall
  </code></pre>
  <p>Everytime I run this code I'm only getting a return value of 1. Can someone point out the error in this? Also if there's a better way to implement the same logic, please let me know of that as well.</p>