MIPS recursive function flow - mips

I am new to MIPS and I have a given MIPS recursive code which I have to apply it to a specific number (ex. number 3)
Bellow is the given MIPS code and I am supposed to write if I were to pass ex. number 3 in the function what would be the changes in the registries and cache for the recursion for said number 3?
I have tried to do it step by step on a piece of paper but got nowhere.
fact:
addi $sp, $sp, -8
sw $ra, 4($sp)
sw $a0, 0($sp)
slti $t0,$a0,1
beq $t0,$zero,L1
addi $v0,$zero,1
addi $sp,$sp,8
jr $ra
Ll:addi $a0,$a0,-1
jal fact
lw $a0, 0($sp)
lw $ra, 4($sp)
addi $sp, $sp, 8
mul $v0,$a0,$v0
jr $ra

Always test your code with the smallest possible input first.  If you try with 0, and single step some 8 instructions worth, you can observe that your code doesn't return to its caller with the proper stack pointer value — an important part of functions is to preserve the registers that must be preserved for the caller, and that includes the stack pointer.  Usually, the way to restore the stack pointer is to deallocate any allocated space, and as long as this is balanced, the preservation rule for $sp is honored.
As a result of an improper stack pointer, the caller is messed up.  Where this bites you, then is when the caller tries to return to its caller.  Likely this is not a problem for main b/c on MARS, for example, we usually exit main via the exit syscall.  However, if you do fact(2), you'll see that the first return it executes works ok, but after that the caller (fact itself, recursive caller) doesn't work — it is unable to return to its caller, because it cannot properly restore its previously preserved $ra, because the stack pointer has been unbalanced by the terminal case.
We need to balance prologue with epilogue: not just statically but dynamically.
Your code is allocating stack space in all cases, though in the terminal case, your code is omitting the deallocation of the stack, so it becomes unbalanced.
Either add stack adjustment (deallocation) to the terminal case, or, test for the terminal case before even allocating stack space (so you don't have to either allocate or deallocate in that terminal case).

Related

MIPS palindrome checker

I am having a hard time figuring out where to start with this project. I am needing to write code in PLP that is a palindrome checker.
the task is to write a program that recieves a string of characters via UART, checks if this string is a palindrome, then uses a print function to print either"yes" of "no". I have been given a template that I am to follow when creating the program.
The template project file contains six function stubs that need to be implemented. five are called from the main loop and the sixth is called from "period_check: in the template file it contains descriptions of what each function needs to do and how it should be implemented. I have attempted to fill in some, however I do not think I am on the right track. Please help.
***** I have gotten this much code in, but it does not print out the right output****
it prints no for everything vs no for non palindromes and yes for palindrome.
.org 0x10000000
# Initializations
# NOTE: You may add initializations after line 10, but please do not
# remove or change the initializations to $sp, $s0, $s1, or $s2
li $sp, 0x10fffffc # Starting address of empty stack
li $s0, 0xf0000000 # UART base address
li $s1, array_ptr # Array head pointer
li $s2, array_ptr # Array tail pointer
####################################################################
# Do not make changes to the jump to main, the allocation of
# memory for the array, or the main loop
####################################################################
j main
nop
array_ptr: # Label pointing to 100 word array
.space 100
main:
jal poll_UART
nop
jal period_check
nop
jal space_check
nop
jal case_check
nop
jal array_push
nop
j main
nop
####################################################################
# ******************************************************************
####################################################################
# The "poll_UART" function should poll the status register of the UART.
# If the 2^1 bit position (ready bit) is set to 1 then it
# should copy the receive buffer's value into $v0 and send
# a clear status command (2^1) to the command register before
# returning (a return statement is already included). In order to
# receive full credit, $s0 must contain the base address of the UART
# and must be used with the appropriate offsets to access UART
# registers and buffers
poll_UART:
lw $t1, 4($s0)
li $t2, 0b10
and $t3, $t1, $t2
beq $t3, $0, main
nop
lw $v0, 8($s0)
sw $t2, 0($s0)
jr $ra
nop
# The "period_check" function should check if the current character ($v0)
# is a period ("."). If it is a period then the function should go to the
# label, "palindrome_check". If the character is not a period then it
# should use the included return.
period_check:
li $t0, 0x2E
beq $v0, $t0, palindrome_check
nop
# The "space_check" function should check if the current character ($v0)
# is a space (" "). If it is then it should jump to "main" so
# that it skips saving the space character. If not it should
# use the included return.
space_check:
li $t4, 0x20
beq $t4, $v0, main
jr $ra
nop
# The "case_check" function should perform a single inequality check.
# If the current character ($v0) is greater than the ASCII value of 'Z',
# which indicates the current character is lowercase, then it should convert
# the value of $v0 to the uppercase equivalent and then return. If the
# current character ($v0) is already uppercase (meaning the inequality
# mentioned before was not true) then the function should return without
# performing a conversion.
case_check:
li $t5, 0x5A
slt $t6, $v0, $t5
li $t7, 1
beq $t6, $t7, convert
convert:
addiu $v0, $v0, -32
jr $ra
nop
# The "array_push" function should save the current character ($v0) to the
# current location of the tail pointer, $s2. Then it should increment the
# tail pointer so that it points to the next element of the array. Last
# it should use the included return statement.
array_push:
sw $v0, 0($s2)
addiu, $s2, $s2, 4
jr $ra
nop
# The "palindrome_check" subroutine should be jumped to by the period
# check function if a period is encountered. This subroutine should contain
# a loop that traverses the array from the front towards the back (using the
# head pointer, $s1) and from the back towards the front(using the tail
# pointer, $s2). If the string is a palindrome then as the array is traversed
# the characters pointed to should be equal. If the characters are not equal
# then the string is not a palindrome and the print function should be used
# to print "No". If the pointers cross (i.e. the head pointer's address is
# greater than or equal to the tail pointer's address) and the compared
# characters are equal then the string is a palindrome and "Yes" should be
# printed.
#
# Remember to restore the head and tail pointers to the first element
# of the array before the subroutine jumps back to main to begin processing the
# next string. Also, keep in mind that because the tail pointer is updated at
# the end of "array_push" it technically points one element past the last
# character in the array. You will need to compensate for this by either
# decrementing the pointer once at the start of the array or using an offset
# from this pointer's address.
palindrome_check:
addiu $s2, $s2, -8
move $s3, $s1
subu $s6, $s2, $s3
beq $s6, $0, palindrome
nop
check_loop:
lw $s4, 0($s3)
lw $s5, 0($s2)
bne $s5, $t0, not_palindrome
nop
adjust_pointers:
addiu $s2, $s2, -4
addiu $s3, $s3, 4
slt $t8, $s3, $s2
bne $t8, $t0, check_loop
nop
j palindrome
nop
palindrome:
li $a0, 1
call project3_print
move $s2, $s1
j main
not_palindrome:
li $a0, 0
call project3_print
move $s2, $s1
j main
nop
Ok, this is just my opinion, but you are definitely not on the right track.
The control flow you're showing is problematic.
To see one reason why, try writing this same in C or any other language that you know.  You won't be able to do it because of the non-local goto's that's using, where one procedure jumps (without calling) to another procedure.
Further, finding whether an input is a palindrome is not a fixed sequence of one-time steps that are executed on each input character.
You will (1) need to store the characters for later comparison, and (2) need a decision point where you can determine (and print) yes it is, or no it isn't.  You don't have any control structure for that.
that recieves a string of characters via UART, checks if this string is a palindrome, then uses a print function to print either"yes" of "no".
Yes, your main should reflect the above description you've been given:
receive a string of characters
checks if this string is a palindrome
print either "yes" of "no"
In other words you might have something like:
int len = input_string();
if ( check_palindrome(len) ) {
print "yes";
else
print "no"
Suggest you write it in C or other language you know, then translate that to assembly.
Also consider that we some things we program are functions returning a value rather than procedures that don't return values.  Returning a value so that main can take a different course of action (e.g. print yes vs. no) is much better than using non-local goto's to alter the flow of control from within a subroutine.
If your instruction/coursework has given you that main, and is recommending non-local goto's that would be very sad.
I feel for you and your classmates, as this is one of the worst examples of teaching assembly I've seen in a long long time.
array_ptr: # Label pointing to 100 word array
.space 100
The label name is misleading.  This space is used as an array of words, not a pointer to an array.  The storage reserved is 25 words, since .space operates in terms of bytes and words are 4 bytes each.  So, the comment is just plain wrong.
The various "functions" called using jal are single use function, so there's really no need for functions in this assignment at all.  The "functions" also are going to each other and back to main instead of returning properly like they would in structured programming.  So, this is what we call spaghetti code — such code is difficult to reason over and one of the reasons that other languages don't even bother to offer this kind of flow control.
The array being used is storing whole words, when the input elements are only characters, so that's harmless but unnecessary.
beq $t6, $t7, convert
convert:
This control structure will never choose between two options, it will always convert.  Why?  Because in the case $t6 is true it will branch to convert: and in the case that $t6 is not true it will fall through to convert:, so same location, will run same code in either case.
You should be able to observe this during debugging.
Debugging Tips
Get to know your data.  You should know the address of the array as you debug.  You can find this during execution, e.g. look at a register after li ... array_ptr (btw, that opcode should be la, but no matter if it works).  Otherwise you can observe the data section and its layout to find that out before running the first instruction.
Single step each line like one would to debug code in any other language, verifying program state between each line.  In MIPS assembly, not much program state changes between lines so usually this is pretty simple — usually each instruction only changes one register or one memory location — but you must verify that such change is as you're expecting.  Once the first part of the program is properly storing characters into the array, you can use the break point feature to stop at the palindrome check routine and single step only from there on.
Use the smallest possible input first, (in the most degenerate case that would be an empty string, but you may not be handling those so instead) might try a single letter input (should be a palindrome).  Once that is working, try two letter input.  As I said, first make sure that the character values are being placed into the array properly, and only when you've verified that's working, go on to debug the palindrome check code.

The meaning of AddrConstant4($s1) in MIPS

I just started studying computer organization.
My question is similar to this article
How are the address of the memory and that of the register connected?(AddrConstant MIPS instruction)
lw $t0, AddrConstant4($s1)
The meaning of this instruction is $t0=constant 4
How I understand this instruction is adding 4 to the value of register $s1 and, load (4+value of register $s1) into $t0.
My question is that I don't know what value does $s1 already have.
If $s1 has 0, it makes sense.
However, if $s1 has 5, $t0 will have 4+5=9.
who knows what value is in $s1.
or what I understood is wrong?
As soon as I wrote this question, another idea came to me.
AddrConstant4($s1) means put 4 into the value of register $s1. (It doesn't matter what value $s1 had before.)
So lw $t0, AddrConstant4($s1) is same as $t0==4.
This is right?
Its a pseudo instruction, that may expand to two or more instructions.
lw $t0, label($t1)
Expands to something like:
la $at, label
addu $at, $at, $t1
lw $t0, 0($at)
Where la itself is a pseudo instruction involving lui and perhaps ori.
There are some optimizations possible, but for the best code, much better to use la to load the label address into a register for a longer duration, e.g. that can be done outside a loop. (OR change algorithm to use pointers.)

"Memory limits" using sw in mips

Lets say i have the following command in MIPS:
sw $t0, 0($sp) # $sp=-4
Does that mean that the register $t0 is saved from 0 to -3 byte or from -4 to -7 byte ?
Stack growing downward in memory to make space for new data to be saved. The stack pointer $sp point to the top of stack.
The stack pointer $sp starts at a high memory address and decrements to expand as needed. Figure (b) shows the stack expanding
to allow two more data words of temporary storage. To do so, $sp decrements by 8 to become 0x7FFFFFF4. Two additional data words,
0xAABBCCDD and 0x11223344, are temporarily stored on the stack.
So in your case if I understand your question well the sw is word- addressable and the word will be stored on that location in memory which $sp point to. In case you store the next word it must have an offset of 4.
[Harris&Harris]
UPDATE
Take this example when you use lb
Say you have this word 0x23456789
when using lb $s0,1($0) After the load byte instruction, lb $s0, 1($0),
$s0 would contain 0x00000045 on a big-endian system and 0x00000067 on a
little-endian system.[Harris&Harris]

Using syscall 9 with linked list in MIPS

I'm trying to implement a linked list in MIPS and I also need to allocate memory for it. In every example I see, they assume that the first element in the list is on certain register, but they don't actually explain how to do it realistically.
I tried this, but it says "store address not aligned on word boundary 0x10040319"
# Allocate memory with syscall 9
li $v0, 9
addi $a0, $zero, 8 # Reserve 8 bytes, 4 for int data, 4 for pointer to next
syscall
# Make $t0 point to the beginning of the reserved memory?
add $t0, $v0, $zero
# Create linked list node
addi $t1, $zero, 10 # $t1 has the int data
sw $t1, 0($t0) # $t1 is now node->data
sw $zero, 4($t0) # node->next is NULL
So I have two questions here, but they are related to each other. One is how to properly allocate memory with syscall 9, and the other one is how to reference it so it can be used in a linked list (I actually need to implement a sorting algorithm using linked lists, because I need to be able to sort any number of elements (not a fixed number) and this is step -1 haha). Thanks.
Oh god, apparently it was the simulator they uploaded for the assignment.
I downloaded the most recent version of Mars MIPS from the official website and it worked. Well, this is awkward.

How does a program written in MIPS knows what to return?

I have this program I just wrote:
countzeroes:
li $v0, 0 # count = 0
li $t0, 0 # int i = 0
li $v1, 1 # compare bit = 1
cz_loop:
bge $t0, 32, cz_exit # exit loop if i >= 32
andi $t1, $a0, 1 # bit = arg0 & 1
beq $t1, $v1, cz_skip # skip if bit = 1
addi $v0, $v0, 1 # adds 1 to count
cz_skip:
srl $a0, $a0, 1 # shifts input right by 1
add $t0, $t0, 1 # i++
j cz_loop
cz_exit:
jr $ra
Pretty simple, just computes the number of zeroes in a 32 bit word. I was wondering how the program knows how to return $v0 at the end? I know v0 and v1 are return registers, but I was wondering if those two are always returned. If not, how does the program know to return v0?
In addition, I know jr $ra jumps to the return address- but what does that mean?
Thanks for your help.
"how the program knows how to return $v0 at the end?"
It doesn't know, you're writing the "return" value in $v0, in fact you could return the "result or return values" in any available register such as the temporals, it's just a convention to use the $v0 register to return values (in MIPS).
"I was wondering if those two are always returned"
Remember that in any subroutine in your program you always have access to all registers, so there's not "restriction" about what register store values that can be semantically called "return values", so I could easily create a method that returns 3 numbers in $t0, $t1, $t2 but that's my choice, you can return values in the stack also, there are a lot of possibilities, and this depends and lays down on the good programming practices and also the calling conventions, here you can find the MIPS calling convention: https://courses.cs.washington.edu/courses/cse410/09sp/examples/MIPSCallingConventionsSummary.pdf
" jr $ra jumps to the return address- but what does that mean?"
The program is executed instruction by instruction(the program has an instruction pointer aka program counter), when you call a subroutine the address of the next instruction is being stored in the $ra register, then when you make jr $ra, the program execution returns to that address (the instruction pointer gets the value of $ra).
In MIPS there are three different jumps you'll see. j, jr & jal.
j: it is considered an unconditional jump. Simply just do:
j function
jr:aka jump to register. Exactly as the name sounds you jump to register. This is when you have a register already saved somewhere in your program you want to jump back to. It will usually look like so:
jr $ra
$ra being the register which had been previously set aside before your jal (see below) which will jump the program back to that address.
jal: aka Jump and link copies the address of the next instruction into the register and then jumps to the address label. In other words, both jal and jr are used in conjunction with each other mainly for going to functions which are usually placed after the exit calls.
Ex:
main:
#program
jal function
#continue with program
function:
#
#do something
#
jr $ra
Also, most helpful site when I started learning: http://logos.cs.uic.edu/366/notes/mips%20quick%20tutorial.htm
Some other quick hints that I wish someone told me when I started:
Always start with "main:"
Be wary of the difference between high/low registers in multiplying
and dividing integers
Always keep track of your registers because with so many $s and $t
and $f and $p and $a and $v registers working at one time things can
get messy very quickly.