when is it necessary to clear out edx before a divide?

mov eax, 2423432
mov ebx, 987987
xor edx, edx ; when is this necessary
div ebx

I guess what I'm asking is what causes the divide by 0 exception when you don't clear or sign extend edx?

Also is it possible to get an exception from not putting
xor edx, edx
before a multiplication?
Posted on 2002-06-08 21:32:48 by grv575
An exception is generated when the result of the divide can't fit into 32-bits. Clearing EDX ensures that this doesn't happen. The CDQ / CWD / CBW instructions were designed to be used before IDIV. Just remember that the divide is 64-bit number divided by a 32-bit number. EDX is cleared because it is the top 32-bits of the dividend.
Posted on 2002-06-08 22:47:08 by bitRAKE
Well, it's pretty much *always* necessary to clear edx before division. Except, of course, you are dividing the full 64-bit value edx:eax.

As for divide by zero... well, it happens when you divide by zero. I'll assume you mean the more general overflow division which happens when the result won't fit into eax. This'll happen if edx >= divisor. This'll cause at least a 33 bit result (and hence, an overflow)

Leaving out the xor edx,edx before multiplication won't cause an exception. In fact, there really isn't any point in doing it because anything like mul r/m will wipe edx out. Also, if you know the result will fit into 32 bits, use imul r,r/m.

--Chorus
Posted on 2002-06-08 22:50:02 by chorus
You also don't need to clear edx if your div is after a mul:


; eax * ecx / ebx
mul ecx
div ebx


MUL puts it's result in EDX:EAX and thus sets edx to the correct value (64-bits output)
However you still need to be sure the result of the division will fit in the 32 result bits of eax.

Thomas
Posted on 2002-06-09 03:20:09 by Thomas