Does gcc optimize c++ code algebraically and if so to what extent?

前端 未结 2 897
梦毁少年i
梦毁少年i 2021-01-24 10:38

Consider the following piece of code showing some simple arithmetic operations

    int result = 0;

    result = c * (a + b) + d * (a + b) + e;

相关标签:
2条回答
  • 2021-01-24 10:53

    GCC (and most C++ compilers, for that matter) does not refactor algebraic expressions.

    This is mainly because as far as GCC and general software arithmetic is concerned, the lines

    double x = 0.5 * (4.6 + 6.7);
    double y = 0.5 * 4.6 + 0.5 * 6.7;
    
    assert(x == y); //Will probably fail!
    

    Are not guaranteed to be evaluate to the exact same number. GCC can't optimize these structures without that kind of guarantee.

    Furthermore, order of operations can matter a lot. For example:

    int x = y;
    int z = (y / 16) * 16;
    
    assert(x == z); //Will only be true if y is a whole multiple of 16
    

    Algebraically, those two lines should be equivalent, right? But if y is an int, what it will actually do is make x equal to "y rounded to the lower whole multiple of 16". Sometimes, that's intended behavior (Like if you're byte aligning). Other times, it's a bug. The important thing is, both are valid computer code and both can be useful depending on the circumstances, and if GCC optimized around those structures, it would prevent programmers from having agency over their code.

    0 讨论(0)
  • 2021-01-24 11:06

    Yes, optimizers, gcc's included, do optimizations of this type. Not necessarily the expression that you quoted exactly, or other arbitrarily complex expressions. But a simpler expresion, (a + a) - a is likely to be optimized to a for example. Another example of possible optimization is a*a*a*a to temp = a*a; (temp)*(temp)

    Whether a given compiler optimizes the expressions that you quote, can be observed by reading the output assembly code.

    No, this type of optimization is not used with floating points by default (unless maybe if the optimizer can prove that no accuracy is lost). See Are floating point operations in C associative? You can let for example gcc do this with -fassociative-math option. At your own peril.

    0 讨论(0)
提交回复
热议问题