Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of XORing a register with itself? [duplicate]

Tags:

x86

assembly

People also ask

What happens if you XOR something with itself?

This means that any value XOR'd with zero is left unchanged. This means that any value XOR'd with itself gives zero.

Is XOR faster than MOV?

This wouldn't be captured in a micro-benchmark comparing the two options, but in the real world it will make code run slightly faster. And, ignoring the reduced i-cache misses, XOR on any CPU in the last many years is the same speed or faster than MOV.

What is the difference between CMP and test?

This is a reasonable question to ask, because cmp is an arithmetic operation, (it performs a subtraction and discards the result,) while test is a logical operation, (it performs a bitwise AND and discards the result,) so one could reasonably suspect that they may modify the Flags register differently.


Yes, it is more efficient.

The opcode is shorter than mov eax, 0, only 2 bytes, and the processor recognizes the special case and treats it as a mov eax, 0 without a false read dependency on eax, so the execution time is the same.


Also to avoid 0s when compiled as used on shell codes for exploitation of buffer overflows, etc. Why avoid the 0 ? Well, 0 represents the end of string in c/c++ and the shell code would be truncated if the mean of exploitation is a string processing function or the like.

Btw im referring to the original question: "Any reason to do a “xor eax, eax”?" not what the MSVC++ compiler does.

Since there's some debate in the comments about how this is pertinent in the real world, see this article and this section on Wikipedia.


xor eax, eax is a faster way of setting eax to zero. This is happening because you're returning zero.

The in instruction is doing stuff with I/O ports. Basically reading a word of data from the port specified dx in and storing it in al. It's not clear why it is happening here. Here's a reference that seems to explain it in detail.