title: Do C++ compilers optimize repeated function calls?
body: <p>Do compilers (generally or in particular) optimize repeated function calls?</p>
  
  <p>For example, consider this case.</p>
  
  <pre><code>struct foo {
    member_type m;
    return_type f() const; // returns by value
  };
  </code></pre>
  
  <p>The function definition is in one translation unit</p>
  
  <pre><code>return_type foo::f() const {
    /* do some computation using the value of m */
    /* return by value */
  }
  </code></pre>
  
  <p>Repeated function calls are in another unit</p>
  
  <pre><code>foo bar;
  
  some_other_function_a(bar.f());
  some_other_function_b(bar.f());
  </code></pre>
  
  <p>Would the code in the second translation unit be converted to this?</p>
  
  <pre><code>foo bar;
  
  const return_type _tmp_bar_f = bar.f();
  
  some_other_function_a(_tmp_bar_f);
  some_other_function_b(_tmp_bar_f);
  </code></pre>
  
  <p>Potentially, the computation <code>f</code> does can be expensive, but the returned type can be something very small (think about a mathematical function returning a <code>double</code>). Do compilers do this? Are there cases when they do or don't? You can consider a generalized version of this question, not just for member functions, or functions with no arguments.</p>
  
  <p><em>Clarification per @BaummitAugen's suggestion</em>:</p>
  
  <p>I'm more interested in the theoretical aspect of the question here, and not so much in whether one could rely on this to make real world code run faster. I'm particularly interested in GCC on x86_64 with Linux.</p>