Why would we use addiu instead of addi?

26,093

and will ruin our calculations

No, MIPS uses two's complement, hence the same instruction for addition/subtraction can be used for both signed and unsigned operations. There's no difference in the result.

That's also true for bitwise instructions, non-widening multiplication and many other operations. See

The only difference between them is that addi generates a trap when overflow while addiu doesn't. So addi and its overflow family (add, sub...) is often useless. In fact it's so rarely used that addi was removed in MIPSr6 to release valuable opcode space to other instructions

Here the instruction name is extremely misleading, because it's not actually an "unsigned" addition. The immediate is still sign extended instead of zero extended. So addiu $1, $2, 0xFFFF will actually subtract 1 from $2 instead of adding 65535 to it.

Despite its name, add immediate unsigned (addiu) is used to add constants to signed integers when we don't care about overflow. MIPS has no subtract immediate instruction, and negative numbers need sign extension, so the MIPS architects decided to sign-extend the immediate field.

Computer Organization and Design: The Hardware/software Interface By David A. Patterson, John L. Hennessy

Read more Difference between add and addu

Share:
26,093
qaispak
Author by

qaispak

Updated on July 19, 2022

Comments

  • qaispak
    qaispak almost 2 years

    In MIPS assembly, what is the benefit of using addiu over addi? Isn't addiu unsigned (and will ruin our calculations?)

  • snowflake
    snowflake about 6 years
    I thought MIPS numbers are 32bit, so addiu $1, $2, 0xFFFFFFFF should substract 1 from $2, and using 0xFFFF should only add that amount (as long as it fits obviously). Or am I wrong?
  • phuclv
    phuclv about 6 years
    @snowflake MIPS instructions are 32-bit long, hence you can't encode a 32-bit constant in them. I-type instructions contain only a 16-bit immediate which will be sign-extended to 32 bits in most cases, including addiu case
  • Peter Cordes
    Peter Cordes about 6 years
    The names seems to match C undefined-behaviour semantics, where signed overflow is undefined (and MIPS addi traps), but unsigned overflow is defined as wrapping (which addiu implements). Of course, many compilers choose to actually implement wrapping semantics for signed integers, too, and use addu / addiu for everything. It's still a weird naming convention, but this is how to remember how they work, and why it makes sense that it has nothing to do with how the 16-bit immediate is treated.