Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly: Difference between add instruction and operator add

Tags:

assembly

Is there any difference between the following two:

mov     eax, [eax+4]

and

add     eax, 4
mov     eax, [eax]

If not then, does the assembler choose which one to pick for some kind of optimization?

like image 435
pkumar Avatar asked Aug 12 '14 21:08

pkumar


2 Answers

There are a few differences between these two pieces of code. For one, the instruction encoding and sizes. The first is encoded as follows...

8b 40 04                mov    eax, [eax+4]

...amounting two 3 bytes.

For the second one...

83 c0 04                add    eax, 4
8b 00                   mov    eax, [eax]

...totals 5 bytes.

Moreover, the add instruction sets the OF (overflow), SF (sign), ZF (zero), AF (adjust/auxiliary), CF (carry), and PF (parity) flags according to the result. The mov instruction neither sets or scrambles any of these flags.

Finally to answer your last question... No. There is no existing assembler that helps with any optimization. Code in assembly is compiled on a strictly literal basis. My suggestion is to use the 3-byte piece of code, as it is shorter and executes faster.

Good luck!

like image 136
Pyromaster Avatar answered Sep 30 '22 10:09

Pyromaster


Yes, there are differences. Whether you care about them is a different matter. The add affects the flags, the [eax+4] doesn't. The two versions have different instruction and byte counts and they possibly use different execution units. These might matter when optimizing.

Normally, the assembler will not change your code, whatever you write is what you will get.

like image 35
Jester Avatar answered Sep 30 '22 08:09

Jester