title: How do I make an infinite empty loop that won't be optimized away?
body: <p>The C11 standard appears to imply that iteration statements with constant controlling expressions should not be optimized out. I'm taking my advice from <a href="https://stackoverflow.com/a/28681034/1204143">this answer</a>, which specifically quotes section 6.8.5 from the draft standard:</p>
  
  <blockquote>
    <p>An iteration statement whose controlling expression is not a constant expression ... may be assumed by the implementation to terminate.</p>
  </blockquote>
  
  <p>In that answer it mentions that a loop like <code>while(1) ;</code> should not be subject to optimization.</p>
  
  <p>So...why does Clang/LLVM optimize out the loop below (compiled with <code>cc -O2 -std=c11 test.c -o test</code>)?</p>
  
  <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;
  
  static void die() {
      while(1)
          ;
  }
  
  int main() {
      printf("begin\n");
      die();
      printf("unreachable\n");
  }
  </code></pre>
  
  <p>On my machine, this prints out <code>begin</code>, then <em>crashes on an illegal instruction</em> (a <code>ud2</code> trap placed after <code>die()</code>). <a href="https://godbolt.org/z/K8CZAa" rel="noreferrer">On godbolt</a>, we can see that nothing is generated after the call to <code>puts</code>.</p>
  
  <p>It's been a surprisingly difficult task to get Clang to output an infinite loop under <code>-O2</code> - while I could repeatedly test a <code>volatile</code> variable, that involves a memory read that I don't want. And if I do something like this:</p>
  
  <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;
  
  static void die() {
      while(1)
          ;
  }
  
  int main() {
      printf("begin\n");
      volatile int x = 1;
      if(x)
          die();
      printf("unreachable\n");
  }
  </code></pre>
  
  <p>...Clang prints <code>begin</code> followed by <code>unreachable</code> as if the infinite loop never existed.</p>
  
  <p>How do you get Clang to output a proper, no-memory-access infinite loop with optimizations turned on?</p>