views:

99

answers:

3

What other optimizations, like the one presented here http://stackoverflow.com/questions/147173/x86-assembly-testl-eax-against-eax can one apply in order to reduce code size?

I am interested especially in one-line optimizations like using test eax, eax instead of cmp eax, 0.

Thanks.

A: 

Moving some constants into registers can be done more efficiently without using mov. For instance, to move zero into rax:

xor eax, eax

Or to set rax to one:

xor eax, eax
inc eax

eax (rather than rax) can be used since the upper half of rax is implicitly cleared (thanks for the comment)

Michael Williamson
This is actually an example of an worse optimization. You can shorten it by one byte per line if you use eax to clear rax. rax requires an additional opcode. Remember that any operation on eax implictly clears the upper half of rax. So better would be "xor eax,eax".
drhirsch
Edited the post accordingly, thanks.
Michael Williamson
A: 

I found another one:

add eax, 1

replaced with

inc eax
DavidH
This is not the same. "add eax,1" changes the sign, zero and carry flag, while "inc eax" changes only carry.
drhirsch
drhirsch: can you detail a little more?
DavidH
In the intel instruction set reference at http://www.intel.com/Assets/PDF/manual/253666.pdf everything is explained in great detail. Look at page 559. And of course I made an error: "inc eax" changes everything, but not carry. Stupid me ;-)
drhirsch
+2  A: 

Moving constant signed bytes (-128 to 127) to registers can be used with push and pop to save a couple of bytes.

6A09         push byte 9     ; Push byte 9 on stack
58           pop eax         ; Pop into 32-bit eax

That's three bytes in comparsion to the mov five byte equivalent

B809000000   mov eax, 9
Jonas Gulle
Note that the byte is effectively treated as signed and "push byte ptr 0FFh; pop eax" will result in eax=0FFFFFFFFh and not eax=000000FFh.
PhiS