Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- .globl read_matrix
- .text
- # ==============================================================================
- # FUNCTION: Allocates memory and reads in a binary file as a matrix of integers
- # If any file operation fails or doesn't read the proper number of bytes,
- # exit the program with exit code 1.
- # FILE FORMAT:
- # The first 8 bytes are two 4 byte ints representing the # of rows and columns
- # in the matrix. Every 4 bytes afterwards is an element of the matrix in
- # row-major order.
- # Arguments:
- # a0 is the pointer to string representing the filename
- # a1 is a pointer to an integer, we will set it to the number of rows
- # a2 is a pointer to an integer, we will set it to the number of columns
- # Returns:
- # a0 is the pointer to the matrix in memory
- # ==============================================================================
- read_matrix:
- # Prologue
- addi sp sp -28
- sw ra 0(sp)
- sw s0 4(sp)
- sw s1 8(sp)
- sw s2 12(sp)
- sw s3 16(sp)
- sw s4 20(sp)
- sw s5 24(sp)
- # save the args
- mv s0 a0
- mv s1 a1 # s1 is the pointer to the number of rows
- mv s2 a2 # s2 is the pointer ot the number of cols
- # open the file
- mv a1 a0
- li a2 0
- jal ra fopen
- li t1, -1
- beq a0 t1 eof_or_error
- mv s3 a0 # s3 is the descriptor
- # read the row num and col num
- mv a1 s3
- mv a2 s1
- li a3 4
- jal ra fread
- li t1, 4
- bne a0 t1 eof_or_error
- mv a1 s3
- mv a2 s2
- li a3 4
- jal ra fread
- li t1, 4
- bne a0 t1 eof_or_error
- # malloc for the matrix
- li t0 1
- lw t1 0(s1)
- blt t1 t0 eof_or_error
- lw t2 0(s2)
- blt t2 t0 eof_or_error
- mul t3 t1 t2
- slli s4 t3 2
- mv a0 s4
- jal ra malloc
- mv s5 a0
- # read the matrix
- mv a1 s3
- mv a2 s5
- mv a3 s4
- jal ra fread
- bne a0 s4 eof_or_error
- # close the file
- mv a1 s3
- jal ra fclose
- li t1 -1
- beq a0 t1 eof_or_error
- # put the resulting matrix into r0
- mv a0 s5
- # Epilogue
- lw ra 0(sp)
- lw s0 4(sp)
- lw s1 8(sp)
- lw s2 12(sp)
- lw s3 16(sp)
- lw s4 20(sp)
- lw s5 24(sp)
- addi sp sp 28
- jr ra
- ret
- eof_or_error:
- li a1 1
- jal exit2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement