Review - Midterm 2 PDF
Review - Midterm 2 PDF
Review - Midterm 2 PDF
CS270
Max Luttrell, Fall 2016
1. What is the value in $t0, $t2, and $t4 at the end
of the following sequence?
li $t0, 1
li $t2, 2
slt $t4, $t2, $t0
beq $t4, $zero, Lskip
sll $t2, $t2, 1
Lskip:
sll $t2, $t2, 1
2. What is the value in $s1 when the program gets
to label "done"?
li $s0, 3
li $s1, 0
loop:
beq $s0, $zero, done
subi $s0, $s0, 1
addi $s1, $s1, 5
j loop
done:
3. Translate the function below to MIPS assembler. Fill in
the table of where your variables are on the right. Follow
the procedure calling convention. You may assume that
the InputDialogString and munge functions are defined
already.
b Ldoitrtn
# int doit
Ldoitcont:
doit:
#temp = munge(i,j,k,temp,buffer);
# home all arg registers except $a0
move $a3, $v0
addiu $sp,$sp, -48
lw $a0,52($sp)
sw $ra, 44($sp)
lw $a1,56($sp)
sw $a1,52($sp)
lw $a2,60($sp)
sw $a2,56($sp)
add $t0,$sp,24
sw $a3,60($sp)
sw $t0,16($sp)
# temp at 20($sp)
jal munge
# buffer at 24($sp)
# *num = temp
# temp = IDS (prompt, buffer, 20);
lw $t0,64($sp)
li $a2,20
sw $v0,0($t0)
add $a1,$sp,24
# return 1
jal IDS
li $v0,1
# if (temp == 0 ) return(0);
Ldoitrtn:
bne $v0,$zero,Ldoitcont
lw $ra,44($sp)
li $v0,0
addiu $sp,$sp, 48
jr $ra
4. Write a MIPS function char *strdup2(char *str1, char *str2)
that:
• allocates memory on the heap (using malloc) for a new string large
enough to hold a copy of str1 concatenated with str2
strdup2 can assume the parameters passed in are pointers to valid, null-
terminated C-strings. it does not need to check for NULL pointers.
strdup2() must use functions from util.s to do its work: strcpy, strlen
and malloc. Do not write your own loops for this function: you must call
these existing functions.
You must write your function in C-like code first, then translate it to assembler.
Part of your grade will be how well your assembly code follows your C code.
Fill in a table with your variables and their register or stack assignments.
4. solution - C code
# int nb;
# char *ptr;
# char *ptr2;
# ptr = NULL;
# nb = strlen(str1);
# nb += strlen(str2);
# ptr = malloc(nb+1);
# strcpy(ptr,str1);
# ptr2=ptr + strlen(ptr);
# strcpy(ptr2,str2);
# return(ptr);
4. solution - MIPS assembly
# ptr = malloc(nb+1);
addi $a0, $s0, 1
strdup2: jal malloc
addiu $sp, $sp, -28 move $s1, $v0
sw $ra, 24($sp)
sw $s0, 16($sp) # strcpy(ptr,str1);
sw $s1, 20($sp) move $a0, $s1
lw $a1, 28($sp)
# home args jal strcpy
sw $a0, 28($sp) # str1
sw $a1, 32($sp) # str2 # ptr2= ptr + strlen(ptr);
move $a0, $s1
# int nb; # $s0 jal strlen
# char *ptr; # $s1 add $t0, $v0, $s1
# char *ptr2; # $t0
# ptr = NULL; # strcpy(ptr2,str2);
li $s1, 0 move $a0, $t0
# nb = strlen(str1); lw $a1, 32($sp)
jal strlen jal strcpy
move $s0, $v0
# return(ptr);
# nb += strlen(str2); move $v0, $s1
lw $a0, 32($sp) lw $ra, 24($sp)
jal strlen lw $s0, 16($sp)
add $s0, $s0, $v0 lw $s1, 20($sp)
addiu $sp, $sp, 28
jr $ra
5. The code on the next page implements
void callxyz(int *A, int N, int scale);