Re:Hello from a libc-free world
by unoti on Wednesday October 26, 2011 @11:46AM
(#3159054)
Why do we use xorl to store 0, but mov for 1?
I'm guessing mov would work in either case, but there's some reason people always do the xorl instead?
[ Parent
| on HN ]
The xorl is one byte smaller, and can be faster. On modern CPUs it's more about the compactness of code than speed, but on some embedded CPUs you can save a cycle or two this way.
Re:Hello from a libc-free world
by alexscheelmeyer on Wednesday October 26, 2011 @11:54AM
(#3159092)
Both will work. The xor version is an old trick that many years ago was faster to execute. I do not think that is still the case, but there is still the difference that the XOR opcode is only one byte and the mov version is multiple, so it saves a few bytes in the executable.
More importantly, these days, is that it saves a few bytes in the caches.
http://stackoverflow.com/questions/1135679/does-using-xor-re... gives more answers than you want, especiallly if you read that Intel PDF.
It is not 100% a "smaller is better" choice. You also will want to check whether an instruction depends on an earlier one (for example, the XOR technically needs to read the register; if the CPU does not know that that is not actually the case, a self-XOR may introduce pipeline bubbles), what instruction unit (if any) it uses, and whether you want to preserve flags.
The xorl instruction uses fewer bytes than the mov. (The movl instruction encoding has the bytes needed for a 32 bit constant, while the xorl instruction encoding would not)
Re:Hello from a libc-free world
by xpaulbettsx on Wednesday October 26, 2011 @01:13PM
(#3159491)
The XOR is also more idiomatic assembly (even though it's not intuitive, every compiler does it and people who know assembly are used to it)
Re:Hello from a libc-free world
by maximilianburke on Wednesday October 26, 2011 @12:36PM
(#3159330)
I think in this case it's a case of not being able to easily determine if "mov ebx, 0" is copying a value into a subregister, making the result dependent on previous operations, or if it's clearing a register. With xor (and sub too, I believe) the processor assumes that no such dependencies exist and can execute the instruction in parallel with others.