Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why X86 provides pair of division and multiply instructions?

Tags:

c

x86

I noticed that, unsigned int and int shared the same instruction for addition and subtract. But provides idivl / imull for integer division and mutiply, divl / mull for unsigned int . May I know the underlying reason for this ?

like image 239
Yang Bo Avatar asked Nov 18 '12 12:11

Yang Bo


1 Answers

The results are different when you multiply or divide, depending on whether your arguments are signed or unsigned.

It's really the magic of two's complement that allows us to use the same operation for signed and unsigned addition and subtraction. This is not true in other representations -- ones' complement and sign-magnitude both use a different addition and subtraction algorithm than unsigned arithmetic does.

For example, with 32-bit words, -1 is represented by 0xffffffff. Squaring this, you get different results for signed and unsigned versions:

Signed: -1 * -1 = 1 = 0x00000000 00000001
Unsigned: 0xffffffff * 0xffffffff = 0xfffffffe 00000001

Note that the low word of the result is the same. On processors that don't give you the high bits, there is only one multiplication instruction necessary. On PPC, there are three multiplication instructions — one for the low bits, and two for the high bits depending on whether the operands are signed or unsigned.

like image 87
Dietrich Epp Avatar answered Nov 15 '22 21:11

Dietrich Epp