CS 14 -- Lab 5


In today's lab, we will work on procedure calls in assembly. We will work both with non-recursive and recursive procedures.


Simple exponentiation

In this lab, we're going to calculate exponents in a straightforward manner. We are going to assume, for simplicity, that both the base and exponents that we're using are non-negative integers.

If we consider, when y > 0, that xy = x * xy-1, then we can write a recursive procedure that will rely on a call to itself to calculate xy-1, and multiply that result by x. When y = 0, we simply observe that xy = 1, irrespective of the value of x. So, in Java-like pseudo-code, the procedure would be:

  public static int calcExponent (int x, int y) {
    if (y == 0) {
      return 1;
    } else {
      return x * calcExponent(x, y-1);
    }
  }
    

An instruction you will need

In order to multiply numbers, you can use the mul instruction, which is an R-type instruction that is used like so:

mul $t0, $t1, $t2 # $t0 = $t1 * $t2

The assignment itself

  1. Login to romulus, and use the following command to copy a file into your directory, being sure not to forget the space and then the period at the end:
    cp ~sfkaplan/cs14/calcexponent.s .
  2. Bring up your copy of the calcexponent.s file in xemacs. Examine both the __start procedure as well as the printvalue procedure. Note that this latter procedure uses a system call to open a little output window and print numbers into it. This procedure is so simple that it doesn't need an activation frame.
  3. Find the comment labeled TASK 1. Insert two procedure calls to printvalue, such that the base is printed, and then the exponent is printed. The value to be printed must be passed in register $a0.
  4. Load the simulator and test your program. Is the printvalue procedure called? Does it emit the base and the exponent as expected. Do you see how the procedure call is working? Observe the register $ra when the jal instruction is executed.
  5. Find the comment labeled TASK 2. Write the calcexponent procedure. This procedure should expect the base value to have been passed by the caller in register $a0, and the exponent value to have been passed in register $a1. It should calculate the exponent, as described above, and return its result in register $v0.
  6. Find the comment labeled TASK 3. Insert two procedure calls; the first should be to calcexponent to perform the exponentiation, and the second should be to printvalue, where the result of the exponentiation should be emitted.

Finishing the lab

Be sure to logout, whether your in the Sun Lab or connected via VNC from elsewhere.

Use the cs14-submit command to submit your calcexponent.s file. Submit this lab as lab-5, like so:

~sfkaplan/cs14/cs14-submit lab-5 calcexponent.s

This assignment is due Monday, March 4th at 11:59 pm.

Scott F. Kaplan
Last modified: Tue Feb 26 09:25:32 EST 2002