title: How to make GCC generate bswap instruction for big endian store without builtins?
body: <p><strong>Update:</strong> This was fixed in GCC 8.1.</p>
  <p>I'm working on a function that stores a 64-bit value into memory in big endian format. I was hoping that I could write <strong>portable C99 code that works on both little and big endian platforms</strong> and have modern x86 compilers generate a <code>bswap</code> instruction automatically <strong>without any builtins or intrinsics</strong>. So I started with the following function:</p>
  <pre><code>#include &lt;stdint.h&gt;
  
  void
  encode_bigend_u64(uint64_t value, void *vdest) {
      uint8_t *bytes = (uint8_t *)vdest;
      bytes[0] = value &gt;&gt; 56;
      bytes[1] = value &gt;&gt; 48;
      bytes[2] = value &gt;&gt; 40;
      bytes[3] = value &gt;&gt; 32;
      bytes[4] = value &gt;&gt; 24;
      bytes[5] = value &gt;&gt; 16;
      bytes[6] = value &gt;&gt; 8;
      bytes[7] = value;
  }
  </code></pre>
  <p>This works fine for clang which compiles this function to:</p>
  <pre><code>bswapq  %rdi
  movq    %rdi, (%rsi)
  retq
  </code></pre>
  <p>But GCC <a href="https://gcc.godbolt.org/z/sqxeKPod7" rel="nofollow noreferrer">fails to detect the byte swap</a>. I tried a couple of different approaches but they only made things worse. I know that GCC can detect byte swaps using bitwise-and, shift, and bitwise-or, but why doesn't it work when writing bytes?</p>
  <p><strong>Edit:</strong> I found the corresponding <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=42587" rel="nofollow noreferrer">GCC bug</a>.</p>