2

What other optimizations, like the one presented here `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.

Community
  • 1
  • 1
DavidH
  • 205
  • 1
  • 4
  • 6
  • what is this for? Hopefully you don't think you can outperform the compiler on this level? – jalf Jan 09 '10 at 00:02
  • I just stumbled upon ["Code size optimization for embedded processors"](http://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-607.pdf). – Niccolo M. Jan 27 '15 at 14:32

3 Answers3

2

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 Engström
  • 4,825
  • 2
  • 35
  • 36
  • 1
    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 Jan 13 '10 at 07:57
0

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
  • 10,740
  • 4
  • 33
  • 32
  • 4
    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". – Gunther Piez Jan 08 '10 at 23:50
-1

I found another one:

add eax, 1

replaced with

inc eax
DavidH
  • 205
  • 1
  • 4
  • 6
  • 1
    This is not the same. "add eax,1" changes the sign, zero and carry flag, while "inc eax" changes only carry. – Gunther Piez Jan 08 '10 at 23:58
  • drhirsch: can you detail a little more? – DavidH Jan 09 '10 at 00:11
  • 2
    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 ;-) – Gunther Piez Jan 09 '10 at 00:20