title: "Illegal hardware instruction" from very simple code
body: <p>While investigating <a href="https://youtu.be/Q0vrQFyAdWI?t=2068" rel="noreferrer">a dubious claim</a>, I wrote this little test program <code>noway.c</code></p>
  
  <pre><code>int proveit()
  {
      unsigned int n = 0;
      while (1) n++;
      return 0;
  }
  
  int main()
  {
      proveit();
      return 0;
  }
  </code></pre>
  
  <p>Testing this, I get:</p>
  
  <pre><code>$ clang -O noway.c
  $ ./a.out
  zsh: illegal hardware instruction  ./a.out
  </code></pre>
  
  <p>Wat.</p>
  
  <p>If I compile without optimizations it hangs as expected.  I looked at the assembly, and without all the bells and whistles the <code>main</code> function looks like this:</p>
  
  <pre><code>_main:                                  ## @main
      pushq   %rbp
      movq    %rsp, %rbp
      ud2
  </code></pre>
  
  <p>Where <code>ud2</code> is apparently is an instruction specifically for undefined behavior.  The aforementioned dubious claim, "A function that never returns is UB", is reinforced.  I still find it hard to believe though.  Really!?  You can't safely write a spin loop?</p>
  
  <p>So I guess my questions are:</p>
  
  <ol>
  <li>Is this a correct reading of what is going on?</li>
  <li>If so, can someone point me to some official resource that verifies it?  </li>
  <li>What is a situation in which you would want this type of optimization to occur? </li>
  </ol>
  
  <p>Relevant info</p>
  
  <pre><code>$ clang --version
  Apple clang version 11.0.0 (clang-1100.0.20.17)
  Target: x86_64-apple-darwin18.6.0
  Thread model: posix
  InstalledDir: /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
  </code></pre>