Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of xorps on the same register?

Tags:

c++

assembly

I was looking at the following disassembled c++ code

    auto test2 = convert<years, weeks>(2.0);
00007FF6D6475ECC  mov         eax,16Dh  
00007FF6D6475ED1  xorps       xmm1,xmm1  
00007FF6D6475ED4  cvtsi2sd    xmm1,rax  
00007FF6D6475ED9  mulsd       xmm1,mmword ptr [__real@4000000000000000 (07FF6D64AFE38h)]  
00007FF6D6475EE1  divsd       xmm1,mmword ptr [__real@401c000000000000 (07FF6D64AFE58h)] 

and was curious as to what the point of the xorps xmm1, xmm1 instruction was. It seems like any number xor itself would just give 0? If so, what's the purpose of clearing the register?

Note: I'm just asking this out of pure curiosity. I know very little about assembly language.

like image 892
Nicolas Holthaus Avatar asked Jan 30 '16 15:01

Nicolas Holthaus


1 Answers

The XMM register has 128 bits and using cvtsi2sd only fills up the low 64 bits. Therefore, the xorps instruction is used to clear the possible garbage values and/or dependency chains that would otherwise affect subsequent operations.

Basically, the sequence of operations you have is:

mov         eax, 16Dh       ; load 0x16D into lower 32 bits of RAX register
xorps       xmm1, xmm1      ; zero xmm1
cvtsi2sd    xmm1, rax       ; load lower 32 bits from RAX into xmm1
<do more stuff with xmm1>

The necessity of zeroing a register is very frequent in assembly when only loading parts of registers where the subsequent instructions operate on their full range. Doing xor x, x is one of the usual register clearing patterns.

See also this (very exhaustive and great, as per comments) answer for more details on why xor can be preferrable to other alternatives (mov x, 0, and x, 0).

like image 158
Zdeněk Jelínek Avatar answered Oct 22 '22 10:10

Zdeněk Jelínek