title: gcc flags to disable arithmetic optimisations
body: <p>Does gcc/g++ have flags to enable or disable arithmetic optimisations, e.g. where <code>a+a+...+a</code> is replaced by <code>n*a</code> when <code>a</code> is an integer? In particular, can this be disabled when using <code>-O2</code> or <code>-O3</code>?</p>
  
  <p>In the example below even with <code>-O0</code> the add operations are replaced by a single multiplication:</p>
  
  <pre><code>$ cat add1.cpp
  unsigned int multiply_by_22(unsigned int a)
  {
      return a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a+a;
  }
  
  $ g++ -S -masm=intel -O0 add1.cpp
  
  $ cat add1.s
  ...
          imul    eax, edi, 22
  </code></pre>
  
  <p>Even disabling all the flags used in <code>-O0</code> (see <code>g++ -c -Q -O0 --help=optimizers | grep enabled</code>) still produces the <code>imul</code> operation.</p>
  
  <p>When adding loops, it requires <code>-O1</code> to simplify the repeated addition to a single multiplication:</p>
  
  <pre><code>$ cat add2.cpp
  unsigned int multiply(unsigned int a, unsigned int b)
  {
      unsigned int sum=0;
      for(unsigned int i=0; i&lt;b; i++)
          sum += a;
      return sum;
  }
  
  $ g++ -S -masm=intel -O1 add2.cpp
  
  $ cat add2.s
  ...
          mov     eax, 0
  .L3:
          add     eax, 1
          cmp     esi, eax
          jne     .L3
          imul    eax, edi
          ret
  </code></pre>
  
  <p>I.e. <code>-O1</code> has moved the <code>sum += a;</code> outside the loop and replaced it by a single multiplication. With <code>-O2</code> it will also remove the dead loop.</p>
  
  <p>I'm just asking out of interest as I was trying to time some basic integer operations and noticed that the compiler optimised my loops away and I couldn't find any flags to disable this.</p>