Unnecessary instructions generated for _mm_movemask_epi8 intrinsic in x64 mode
<p>The intrinsic function <code>_mm_movemask_epi8</code> from SSE2 is defined by Intel with the following prototype:</p>

<pre><code>  int _mm_movemask_epi8 (__m128i a);
</code></pre>

<p>This intrinsic function directly corresponds to the <code>pmovmskb</code> instruction, which is generated by all compilers.</p>

<p>According to <a href="http://www.tptp.cc/mirrors/siyobik.info/instruction/PMOVMSKB.html" rel="nofollow noreferrer">this reference</a>, the <code>pmovmskb</code> instruction can write the resulting integer mask to either a 32-bit or a 64-bit general purpose register in x64 mode. In any case, only 16 lower bits of the result can be nonzero, i.e. the result is surely within range [0; 65535].</p>

<p>Speaking of the intrinsic function <code>_mm_movemask_epi8</code>, its returned value is of type <code>int</code>, which as a signed integer of 32-bit size on most platforms. Unfortunately, there is no alternative function which returns a 64-bit integer in x64 mode. As a result:</p>

<ol>
<li>Compiler usually generates <code>pmovmskb</code> instruction with 32-bit destination register (e.g. <code>eax</code>).</li>
<li>Compiler cannot assume that upper 32 bits of the whole register (e.g. <code>rax</code>) are zero.</li>
<li>Compiler inserts unnecessary instruction (e.g. <code>mov eax, eax</code>) to zero the upper half of 64-bit register, given that the register is later used as 64-bit value (e.g. as an index of array).</li>
</ol>

<p>An example of code and generated assembly with such a problem can be seen in <a href="https://stackoverflow.com/a/31683632/556899">this answer</a>. Also the comments to that answer contain some related discussion. I regularly experience this problem with MSVC2013 compiler, but it seems that it is also present on GCC.</p>

<p>The questions are:</p>

<ol>
<li>Why is this happening?</li>
<li>Is there any way to reliably avoid generation of unnecessary instructions on popular compilers? In particular, when result is used as index, i.e. in <code>x = array[_mm_movemask_epi8(xmmValue)];</code></li>
<li>What is the approximate cost of unnecessary instructions like <code>mov eax, eax</code> on modern CPU architectures? Is there any chance that these instructions are completely eliminated by CPU internally and they do not actually occupy time of execution units (Agner Fog's instruction tables document mentions such a possibility).</li>
</ol>