assemblysar

Assembly sarl and idivl - interpreting


I've a problem understanding the following Assembly Code. It would be great if you could just give me an example with numbers how this looks like behind the scenes.

movl $0, %ecx
movl $0, %eax
addl $1, %eax
movl %eax, %edx
sarl $31, %edx
idivl $7
movl %edx, %eax
movl (%esp, %eax, 4), %eax
movl %eax, (%esp, %ecx, 4)

I think I may misinterpret the sarl and idivl because my result makes no sense..

Thanks a lot for your help!! I've been sitting in front of that code for 3 hours now^^

I think:

ecx = 0

eax = 0

eax = 0 + 1 = 1

edx = eax = 1

now shifting edx => edx = 0

now edx:eax is divided by 7?

why can't I just set edx = 0 and leave sarl out? wouldn't that be the same?


Solution

  • why can't I just set edx = 0 and leave sarl out? wouldn't that be the same?

    Not for a signed division, which is what idiv is. These two instructions are simulating what the CDQ instruction does:

    movl %eax, %edx
    sarl $31, %edx
    

    That is,

    "SAR preserves the sign of the source operand by clearing empty bit positions if the operand is positive and setting the empty bits if the operand is negative."

    and

    "The CDQ instruction copies the sign (bit 31) of the doubleword in the EAX register into every bit position in the EDX register. The CDQ instruction can be used to produce a quadword dividend from a doubleword before doubleword division."

    Note that sarl updates some of the status flags, while cdq doesn't, so movl + sarl won't be exactly the same as cdq. It's not clear from the question why the code doesn't simply use cdq.