title: Why does vectorization behave differently for almost the same code?
body: <p>Here are free functions that do the same but in the first case the loop is not vectorized but in the other cases it is. Why is that?</p>
  
  <pre><code>#include &lt;vector&gt;
  
  typedef std::vector&lt;double&gt; Vec;
  
  void update(Vec&amp; a, const Vec&amp; b, double gamma) {
      const size_t K = a.size();
      for (size_t i = 0; i &lt; K; ++i) { // not vectorized
          a[i] = b[i] * gamma - a[i];
      }
  }
  
  void update2(Vec&amp; a, const Vec&amp; b, double gamma) {
      for (size_t i = 0; i &lt; a.size(); ++i) { // vectorized
          a[i] = b[i] * gamma - a[i];
      }
  }
  
  void update3(Vec&amp; a, size_t K, const Vec&amp; b, double gamma) {
      for (size_t i = 0; i &lt; K; ++i) { // vectorized
          a[i] = b[i] * gamma - a[i];
      }
  }
  
  int main(int argc, const char* argv[]) {
      Vec a(argc), b;
      update(a, b, 0.5);
      update2(a, b, 0.5);
      update3(a, a.size(), b, 0.5);
      return 0;
  }
  </code></pre>
  
  <p>Relevant messages from the compiler (VS2013):</p>
  
  <pre><code>1&gt;  c:\home\dima\trws\trw_s-v1.3\trws\test\vector.cpp(7) : info C5002: loop not vectorized due to reason '1200'
  1&gt;  c:\home\dima\trws\trw_s-v1.3\trws\test\vector.cpp(13) : info C5001: loop vectorized
  1&gt;  c:\home\dima\trws\trw_s-v1.3\trws\test\vector.cpp(19) : info C5001: loop vectorized
  </code></pre>
  
  <p>From comment by @tony</p>
  
  <blockquote>
    <p>Reason 1200: "Loop contains loop-carried data dependences that prevent
    vectorization. Different iterations of the loop interfere with each
    other such that vectorizing the loop would produce wrong answers, and
    the auto-vectorizer cannot prove to itself that there are no such data
    dependences." <a href="https://msdn.microsoft.com/en-us/library/jj658585.aspx#BKMK_ReasonCode120x" rel="noreferrer">source</a></p>
  </blockquote>