Monday, April 6, 2020

MIPS register - register subtraction overflow (sub)

This is sample MIPS assembler code demonstrating register - register subtraction overflow. It detects subtraction overflow using MIPS hardware overflow simulation supported by EzMIPS, the MIPS assembler editor & simulator. The code is fully commented.

Launch EzMIPS, copy the following MIPS code and paste it into EzMIPS. Assemble, Run.

# ---------- Register - register subtraction overflow ------------ #

.data

szMenu:         .ascii  "Detect register - register subtraction overflow?\n"
                .ascii  "------------------------------------------------\n"
                .ascii  "1. Runtime exception: arithmetic overflow\n"
                .asciiz "2. Exit\n"

.text

main:

# ............... Test one for subtraction overflow .............. #


    li $t4, 0x80000000    # -2147483648
    li $t5, 0x01          # 1
    
    # OVERFLOW!!!
    # 0x80000000  - 0x01  = 0x7FFFFFFF
    # -2147483648 - 1     = 2147483647         <- OVERFLOW

# ........ Uncomment for test two for subtraction overflow ....... #

    #li $t4, 0xfffffffe    # -2
    #li $t5, 0x7fffffff    # 2147483647

    # OVERFLOW!!!
    # 0xfffffffe  - 0x7fffffff = 0x7fffffff
    # -2          - 2147483647 = 2147483647     <- OVERFLOW

# ................................................................ #
    
    li $t1, 1
    li $t2, 2

# ................................................................ #

print_menu:

    # print menu
    li $v0, 4
    la $a0, szMenu
    syscall

# ................................................................ #
    
    # get user input
    li $v0, 5
    syscall
    # $v0 holds user input

    beq $v0, $t2, exit
    bne $v0, $t1, print_menu

# ................................................................ #
    
    # Runtime exception: arithmetic overflow
    sub $t0, $t4, $t5   # subtraction with Overflow Runtime exception
    j print_menu        # if no runtime exception occured, print menu

# ................................................................ #

exit:

    li $v0, 10
    syscall

# ---------------------------------------------------------------- #

Please let me know of any suggestions or bugs regarding the code above.

Regards,

Antonis

No comments:

Post a Comment