title: Optimizing a NEON XOR implementation
body: <p>Trying to xor a huge <code>uint32</code> array I decided to use NEON coprocessor.</p>
  
  <p>I implemented two <code>c</code> versions:</p>
  
  <p><strong>version 1:</strong></p>
  
  <pre><code>uint32_t xor_array_ver_1(uint32_t *array, int size)
  {
      uint32x2_t acc = vmov_n_u32(0);
      uint32_t acc1 = 0;
      for (; size != 0; size -= 2) {
          uint32x2_t vec;
          vec = vld1_u32(array);
          array += 2;
          acc = veor_u32(acc, vec);
      }
      acc1 = vget_lane_u32(acc,0) ^ vget_lane_u32(acc,1);
      return acc1;
  }
  </code></pre>
  
  <p><strong>version 2:</strong></p>
  
  <pre><code>uint32_t xor_array_ver_2(uint32_t *array, int size)
  {
      uint32x4_t acc = vmovq_n_u32(0);
      uint32_t acc1 = 0;
  
      for (; size != 0; size -= 4) {
          uint32x4_t vec;
          vec = vld1q_u32(array);
          array += 4;
          acc = veorq_u32(acc, vec);
      }
  
      acc1 ^= vgetq_lane_u32(acc,0);
      acc1 ^= vgetq_lane_u32(acc,1);
      acc1 ^= vgetq_lane_u32(acc,2);
      acc1 ^= vgetq_lane_u32(acc,3);
  
      return acc1;
  }
  </code></pre>
  
  <p>Comparing the above 2 versions to the traditional xor implementation:</p>
  
  <pre><code>for (i=0; i&lt;arr_size; i++)
          val ^= my_array[i];
  </code></pre>
  
  <p>I observed 2 issues:</p>
  
  <ol>
  <li>Version 1 has the same performance.</li>
  <li>Version 2 is s bit more than <strong>30%</strong> better.</li>
  </ol>
  
  <hr>
  
  <ol>
  <li>Can I rewrite it to be even better? where <code>my_array</code> is declared as
  <code>uint32_t my_array[BIG_LENGTH];</code></li>
  <li>Is there a <strong>non-NEON</strong> way I can improve the performance of the regular xoring code? <a href="http://en.wikipedia.org/wiki/Duff%27s_device" rel="nofollow noreferrer">unrolling the loop</a> doesn't give any improvement. </li>
  </ol>