! Mike Burrell ! ! Reads in two integers, x and y, from standard in. Computes the exponent, i.e., ! x**y, and then outputs that number to standard out. define(x_r, l0) ! the number we're raising to an exponent define(y_r, l1) ! the exponent we're raising it to define(e_r, l2) ! our answer of x ** y .global main main: save %sp, -96, %sp ! get x from the user mov '>', %o0 ! print out prompt call writeChar nop call readInt ! read an integer from the user nop mov %o0, %x_r ! and store it ! get x from the user mov '>', %o0 ! print out prompt call writeChar nop call readInt ! read an integer from the user nop mov %o0, %y_r ! and store it ! the way we're going to compute the exponent is start off at 1. then ! we're going to go through a loop y times, each time multiplying our ! answer by x. for example, 3 ** 2 = 1 * 3 * 3 (note we multiplied 2 ! times). mov 1, %e_r ! our answer starts off as 1 ! now we want to loop y times. we just count down from y to 0 ! these next two instructions are a bit tricky if you're not ! comfortable with assembly language yet. the first instruction, ! deccc, says "decrement (by one) and set the condition codes". ! this is equivelent to this: ! sub %y_r, 1, %y_r ! decrement by 1 ! tst %y_r ! set the condition codes ! the next instruction, bl (branch if less than) might seem a ! little bit weird: how on earth can %y_r be less than ! something if we didn't even compare it to anything?! well, ! remember that when you're testing the value of something, ! you're implicitly comparing it against zero. tst %y_r is ! actually nothing more than: ! cmp %y_r, 0 ! so, if we take these two instructions together: ! deccc %y_r ! bl done ! this is saying: "decrement y_r by one, and branch if it ! becomes less than zero". if you're familiar with C or Java, ! this would be the same as saying: ! if (--y < 0) { ... ! once you get the hang of little tricks like this, you'll ! be quite amazed at what you can do in assembly with just ! 2 or 3 instructions! loop: deccc %y_r ! decrement y and set the condition codes bl done ! if y is less than zero, we're done nop mov %e_r, %o0 ! multiply e * x mov %x_r, %o1 call .mul nop mov %o0, %e_r ! and make e the new answer. e.g., e = e * r ba loop ! go back up to the top of the loop nop done: ! we have the answer now! let's print it out mov %e_r, %o0 ! print out e call writeInt nop mov '\n', %o0 ! print out a newline call writeChar nop ret ! exit restore