Search code examples
csparc

Need help translating following C function to SPARC assembler


I was working on a SPARC assembly program in which I call a subroutine called power which takes a base number and multiplies the base times its self based on the exponent. Essentially just calculating a power function. My problem is I am having trouble translating the following C function into SPARC assembly.

power(int base, int exponent)
{
    register int p, e;
    p = 1;

    for(int e=1; e <= exponent; e++)
    {
        p *= base;
    }
} 

This is what I have but I just get 49 as my answer:

 .global main

main: save %sp,-96,%sp
      mov 7,%i0
      mov 5,%i1
      mov 1,%l2
loop: mov %i0,%o0
      mov %i0,%o1
      call .mul
      nop
      cmp %l2,%i1
      ble loop
      dec %i1

Solution

  • .global main
    
    main: save %sp,-96,%sp
          mov 7,%i0      ! base
          mov 5,%i1      ! exponent
          mov 1,%l2      ! p
          mov %l2,%o0    ! %o0 = p = 1
          cmp  %i1,0     
          ble  end       ! if (exponent <= 0) -> end
    loop: mov %i0,%o1    ! %o1 = base
          call .mul      ! %o0 = %o0 * %o1 -> p = p * base
          nop
          cmp %l2,%i1
          bl loop
          dec %i1
    end:
    

    Changes to get the result (7⁵=16807):

    • Initalized %o0 with 1
    • Removed mov %i0,%o0 (every iteration you were smashing the mul result)
    • Replaced ble by bl