c++coptimizationsemantics

Sequence points, conditionals and optimizations


I had an argument today with one of my collegues regarding the fact that a compiler could change the semantics of a program when agressive optimizations are enabled.

My collegue states that when optimizations are enabled, a compiler might change the order of some instructions. So that:

function foo(int a, int b)
{
  if (a > 5)
  {
    if (b < 6)
    {
      // Do something
    }
  }
}

Might be changed to:

function foo(int a, int b)
{
  if (b < 6)
  {
    if (a > 5)
    {
      // Do something
    }
  }
}

Of course, in this case, it doesn't change the program general behavior and isn't really important.

From my understanding, I believe that the two if (condition) belong to two different sequence points and that the compiler can't change their order, even if changing it would keep the same general behavior.

So, dear SO users, what is the truth regarding this ?


Solution

  • If the compiler can verify that there is no observable difference between those two, then it is free to make such optimizations.

    Sequence points are a conceptual thing: the compiler has to generate code such that it behaves as if all the semantic rules like sequence points were followed. The generated code doesn't actually have to follow those rules if not following them produces no observable difference in the behavior of the program.

    Even if you had:

    if (a > 5 && b < 6)
    

    the compiler could freely rearrange this to be

    if (b < 6 && a > 5)
    

    because there is no observable difference between the two (in this specific case where a and b are both int values). [This assumes that it is safe to read both a and b; if reading one of them could cause some error (e.g., one has a trap value), then the compiler would be more restricted in what optimizations it could make.]