Two’s Complement

Subtraction

Overflow

OperationSign Bit of XSign Bit of YSign Bit of ResultSign Bit of Expected
Adding two +ve (0)
X + Y001X + Y = 0
X - Y011(X - (-Y)) = 0
Subtracting two -ve (1)
X + Y110((-X) + (-Y)) = 1
X - Y100((-X) - Y) = 1

MIPS “Unsigned”

  • Sign extension (arithmetic operations)
    • addi
    • addiu
    • slti
    • lh
    • lb
  • Zero extension (logical operations)
    • andi
    • ori
    • lhu
    • lbu

Important

Immediate operand in MIPS is always sign extended

Arithmetic Logic Unit (ALU)

1-Bit Full Adder

ABCarry InCarry OutSum Outa + b + CarryIn
000000 + 0 + 0 = 00
001010 + 0 + 1 = 01
010010 + 1 + 0 = 01
011100 + 1 + 1 = 10
100011 + 0 + 0 = 01
101101 + 0 + 1 = 10
110101 + 1 + 0 = 10
111111 + 1 + 1 = 11

Note that

Note that

|400

  • Bin and Cin can be combined
BInvertCarryIn
AND0x
OR0x
NOT00
SUB11
  • slt
    • operation 3 for slt
    • alu1 - alu31 set = 0
    • alu0 set = alu31 set

Overflow

OperationSign ASign BSign ResultBInverta3b3set
A + B0010001
A + B1100110
A - B0111011
A - B1001100

beq (A - B == 0)

  • BInvert = 1
  • Operation = 2
  • Check if all bits 0, and then NOT

Multiplication

  • Multiplier, stored in product
  • Multiplicand (M), 32 bits
  • Product (P), 32 + 32 = 64 bits
    • Initially zero extended
    • Left(P) is 0
    • Right(P) is the multiplier
  1. If Product0 is 1
    1. Left(P) = Left(P) + M
  2. P >> 1
  3. Exit on the 32nd repetition

Signed Multiplication

  • Do the above calculation based on the absolute value
  • Negate result based on sign of multiplicand/multiplier
  • Booth’s algorithm

Unsigned Overflow

No overflow if Hi is 0

multu $s0, $s1
mfhi $at
mflo $s2

beq $at, $0, no_overflow
    # overflow
no_overflow:
    # no overflow

Signed Overflow

No overflow if every bit in Hi is same as sign bit of Lo

sra $t0, $s2, 31 will turn 0...x to 0...0, making all bit to the sign of Lo, then compare it with Hi

mult $s0, $s1
mfhi $at
mflo $s2

sra $t0, $s2, 31 # shift right arithmetic
beq $at, $t0, no_overflow
    # overflow
no_overflow:
    # no overflow

Division

  • Quotient, stored in remainder
  • Dividend, stored in remainder
  • Divisor (D), 32 bits
  • Remainder (R), 32 + 32 = 64 bits
    • Initially zero extended
      • Left(R) is 0
      • Right(R) is dividend
    • Quotient appear from the right by shifting
    • Remainder will appear at the left at the end
  1. R << 1, now the lsb is the useless 0
  2. Left(R) = Left(R) - D
  3. If Left(R) < 0
    1. Left(R) = Left(R) + D, to undo subtraction
    2. R << 1
    3. R_0 = 0
  4. If Left(R) >= 0
    1. R << 1
    2. R_0 = 1
  5. Exit on 32nd repetition
  6. Left(R) >> 1

If divisor is 0, quotient will be all 1

Signed Division

  • Sign of dividend and remainder is same
  • Deduce sign of quotient by looking at divisor
DividendDivisorQuotientRemainder
++++
-+--
+--+
--+-