Why does the idiv
x86 assembly instruction divide EDX:EAX
(64 bits) by a given register whereas other mathematical operations, including multiplication, simply operate on single input and output registers?
Multiplication:
mov eax, 3
imul eax, 5
Division:
mov edx, 0
mov eax, 15
mov ebx, 5
idiv ebx
I am aware that EDX
is used to store the remainder, but why is there no separate instruction for this behaviour? It just seems inconsistent to me.
Unsigned Divide (div) div divides a 16-, 32-, or 64-bit register value (dividend) by a register or memory byte, word, or long (divisor). The quotient is stored in the AL, AX, or EAX register respectively. The remainder is stored in AH, Dx, or EDX.
x64 is a generic name for the 64-bit extensions to Intel‟s and AMD‟s 32-bit x86 instruction set architecture (ISA). AMD introduced the first version of x64, initially called x86-64 and later renamed AMD64. Intel named their implementation IA-32e and then EMT64.
The div instruction is used to perform a division. Always divides the 64 bits value accross EDX:EAX by a value. The result of the division is stored in EAX and the remainder in EDX.
Purpose. Divides the contents of a general-purpose register concatenated with the MQ Register by the contents of a general-purpose register and stores the result in a general-purpose register. Note: The div instruction is supported only in the POWER® family architecture.
The instruction set provides the instructions that are necessary to implement arbitrary-width integer arithmetic efficiently. For addition and subtraction, all you need to know for this beyond a fixed width result is whether the operation resulted in a carry (for addition) or a borrow (for subtraction). This is why there is a carry flag. For multiplication, you need to be able to multiply two words and get a double word result. This is why imul
produces its result in edx:eax
. For division, you need to be able to divide a double-width number and get the quotient and the remainder.
To understand why you need these specific operations, see Knuth's The Art of Computer Programming, Volume 2, which goes into detail on the algorithms for implementing arbitrary-width arithmetic.
As for why there aren't more different forms of multiplication and division instructions in the x86 instruction set, multiplication and division that isn't by a power of two is much more rare than other instructions, so Intel probably didn't want to use up opcodes that could be used for instructions that will be used more frequently. Most multiplications and divisions in general purpose programs are by powers of two; for these you can use bitshifts or the lea
instruction instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With