Search code examples
c++optimizationcompiler-constructioncall

Are modern C++ compilers able to avoid calling a const function twice under some conditions?


For instance, if I have this code:

class SomeDataProcessor
{
public:
    bool calc(const SomeData & d1, const SomeData & d2) const;
private:
    //Some non-mutable, non-static member variables
}

SomeDataProcessor sdp;
SomeData data1;
SomeData data2;

someObscureFunction(sdp.calc(data1, data2),
                    sdp.calc(data1, data2));

Let's consider the potentially equivalent code:

bool b = sdp.calc(data1, data2);
someObscureFunction(b,b);

For this to be valid, the calc() function should meet some requirements, and for the example I call the property _pure_const_formula_

A _pure_const_formula_ would:

  • Not change any member, static or global variable state
  • Call only _pure_const_formula_ functions
  • Maybe some other conditions that I don't have in mind

For instance, calling a random number generator would not fit these requirements.

Is the compiler allowed to replace the first code with the second one, even if it needs to dig recursively into called functions? Are modern compilers able to do this?


Solution

  • GCC has the pure attribute (used as __attribute__((pure))) for functions which tells the compiler that redundant calls can be eliminated. It's used e.g. on strlen.

    I'm not aware of any compiler doing this automatically, especially considering the fact that the functions to be called may not be available in source form, and the object file formats contain no metadata about whether a function is pure or not.