title: How is speculative fault due to compiler optimization implemented under the hood?
body: <p>This question is a follow-up question on <a href="https://stackoverflow.com/q/38061281/1175080">Can the C compiler optimizer violate short-circuiting and reorder memory accesses for operands in a logical-AND expression?</a>.</p>
  
  <p>Consider the following code.</p>
  
  <pre><code>if (*p &amp;&amp; *q) {
      /* do something */
  }
  </code></pre>
  
  <p>Now as per the discussion at <a href="https://stackoverflow.com/q/38061281/1175080">Can the C compiler optimizer violate short-circuiting and reorder memory accesses for operands in a logical-AND expression?</a> (especially David Schwartz comment and answer) it is possible for the optimizer of a standard-conformant C compiler to emit CPU instructions that accesses <code>*q</code> before <code>*p</code> while still maintaining the observable behaviour of the sequence point established with the <code>&amp;&amp;</code>-operator.</p>
  
  <p>Therefore although the optimizer may emit code that accesses <code>*q</code> before <code>*p</code>, it still needs to ensure that any side-effects of <code>*q</code> (such as segmentation fault) is observable only if <code>*p</code> is non-zero. If <code>*p</code> is zero, then a fault due to <code>*q</code> should not be observable, i.e. a speculative fault would occur first due to <code>*q</code> being executed first on the CPU but the speculative fault would be ignored away once <code>*p</code> is executed and found to be 0.</p>
  
  <p>My question: How is this speculative fault implemented under the hood?</p>
  
  <p>I would appreciate if you could throw more light on the following points while answering this question.</p>
  
  <ol>
  <li>As far as I know, when the CPU detects a fault, it generates a trap, that the kernel must handle (either take recovery action such as page swap, or signal the fault such as SIGSEGV to the process). Am I correct?</li>
  <li>So if the compiler must emit code to perform speculative fault, it appears to me that the kernel and the compiler (and possibly the CPU too) must all cooperate with each other to implement speculative fault. How does the compiler emit instructions that would tell the kernel or the CPU that a fault generated due to the code should be considered speculative?</li>
  </ol>