What is the fastest instruction to clear the upper 32 bits of a x86_64 GPR (r?x) ?
Asked
Active
Viewed 612 times
2 Answers
3
Perhaps in some circumstances it may end up not being the faster method, but in general it should: use mov reg32, reg32
Intel syntax examples:
mov ebx, ebx ; The topmost 32 bits of rbx will be cleared
mov r11d, r11d ; The topmost 32 bits of r11 will be cleared
The reason it works is because when you write a 32-bit register, its 64-bit brother gets its upper 32 bits cleared. Same would happen with "or reg32, reg32", "and reg32, reg32", "add reg32, 0", etc.
Before using some method to clear the upper 32 bits, make sure you actually need to do such thing, as it may happen that your code can start working with 32-bit operation (which will clear the upper 32 bits automatically), before you need to work with 64-bit wide operands.

LocoDelAssembly
- 818
- 8
- 10
-
Thank you. It's oddly hard to find this out with Google searches. Everybody says `movl` modifies the 32 bit register, but the `movb` instruction leaves the upper bits alone. Why would `movl` be different? – Omnifarious Jul 10 '20 at 04:27
1
Isn't plain old and
good enough?
and rbx,0ffffffffh

Paul R
- 208,748
- 37
- 389
- 560
-
I tried and $0xFFFFFFFF, %rbx. But it doesnt seem to compile. it gives invalid suffix for and.. If the mask needs to be moved to some other register for anding, movq $FFFFFFFF, %rcx.. But this 0xFFFFFFFF will get sign extended and all the upper bits will also become 1. ?? I was wondering if there is any defined instruction for clearing upper 32 bits – user403219 Jan 24 '11 at 09:03
-
only `mov ebx, ebx` is enough. Much shorter. [Why do most x64 instructions zero the upper part of a 32 bit register](http://stackoverflow.com/q/11177137/995714) – phuclv Nov 20 '15 at 03:19