Difference between add and addu

collimarco picture collimarco · May 19, 2013 · Viewed 36.1k times · Source

I am confused about the difference between add and addu.

The MIPS instruction reference says:

  • add (with overflow)
  • add unsigned (no overflow)

My understanding is to use add with signed operands and addu with unsigned operands.

But let's consider this example (with only 6bit):

overflow
|
V
1 | 1 1 1  <- carry
  | 1 1 1 1 0 1 +
  | 1 1 1 1 1 0 =
-----------------
  | 1 1 1 0 1 1

And this is my reasoning:

  • if I consider the first and second operand signed numbers (two's complement), then the result is correct (-3 + -2 = -5) and I don't want an overflow exception. So I would use addu to avoid this exception, but, although the result is the same, the name suggests to use addu is for unsigned numbers!
  • if I consider the first and second operand unsigned numbers, then I want an exception to be raised (because 61 + 62 is not equal to 59). So I would use add to raise the exception, and not addu, as the name would suggest to do.

Now my questions are:

  • assuming that operands are signed (negative in the example above) numbers, should I use addu (as my reasoning suggests) or I should use add (as the name suggests)?
  • assuming that operands are unsigned (positive) numbers, should I use add (as my reasoning suggests) or addu (as the name suggests)?

Answer

markgz picture markgz · May 21, 2013

The instruction names are misleading. Use addu for both signed and unsigned operands, if you do not want a trap on overflow.

Use add if you need a trap on overflow for some reason. Most languages do not want a trap on signed overflow, so add is rarely useful.