title: How to mitigate spectre with GCC and Clang (or LLVM in general)
body: <p>Microsoft added a convenient <code>/Qspectre</code> to their MSVC compiler (although that seems to only be (trying to) mitigate Spectre v1 at the moment) that they will be updating over time. This is quite nice from a users perspective, just enable that flag and you get the latest and greatest mitigation they have in store.</p>
  
  <p>With LLVM and GCC it looks a little bit different. I don't think their mitigations are officially released yet.</p>
  
  <p>LLVM is supposed to get a <code>-mretpoline</code> compiler flag that mitigates Spectre v2 via return trampolines for indirect calls.</p>
  
  <p>GCC on the other hand has patches that add three compiler options for mitigating Spectre v2:</p>
  
  <ul>
  <li><code>-mindirect-branch</code> that can be set to <code>thunk</code>. The way I understand it, this creates retpolines for every indirect call.</li>
  <li><code>-mfunction-return</code> that can be set to <code>thunk</code>. I imagine this uses these retpolines for every single function return, which might be necessary for Skylake because these processors can also predict returns?</li>
  <li><code>-mindirect-branch-register</code> This uses a register instead of a stack to store the address of the indirect call?</li>
  </ul>
  
  <p>So I'm quite confused. What compiler option mitigates what and in what scenarios are they necessary for a user space application?</p>
  
  <p>Is it a good idea to generally turn them on? Will they also generate these retpolines if compiled for a processor architecture that doesn't even have any speculative execution (like microprocessors)?</p>
  
  <p>What about Spectre v1?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Let me ask more precise questions:</p>
  
  <ul>
  <li>Is my understanding of what the compiler options do correct?</li>
  <li>Are the GCC options applied everywhere or only on processors with speculative execution?</li>
  <li>Are the LLVM options applied everywhere or only on processors with speculative execution?</li>
  <li>What exactly do these options mitigate (do they fully mitigate spectre v2)?</li>
  <li>Let's consider everything else that I asked to be additional "bonus" questions" that are good to know but not essential to my question.</li>
  </ul>