Search code examples
c++coptimization

Do C and C++ optimizers typically know which functions have no side effects?


Say for very common math functions, such as sin, cos, etc... does the compiler realise they have no side effects and have the ability to move them to outer loops? For example

// Unoptimized

double YSinX(double x,int y)
{
   double total = 0.0;
   for (int i = 0; i < y; i++)
      total += sin(x);
   return total;
}

// Manually optimized

double YSinX(double x,int y)
{
   double total = 0.0, sinx = sin(x);
   for (int i = 0; i < y; i++)
      total += sinx;
   return total;
}

If they can, is there a way of declaring a function as having no side effects, and hence being safe to optimize in this way? Initial profiling of a VS2010 app suggests that the optimization is beneficial.

See also this related question, which is close but doesn't quite answer my own.

Edit: Some great answers. The one I accepted was based as much on the comments it provoked as the answer itself, notably the linked article, and the fact that hoisting may not occur in situations where errno is set (i.e. a side effect). As such, and in the context of what I'm doing, this type of manual optimization still appears to make sense.


Solution

  • GCC has two attributes, pure and const, that may be used to mark such function. If the function has no side-effect and its result depends only on its arguments, the function should be declared const, if the results may also depend on some global variable the function should be declared pure. Recent versions also have a -Wsuggest-attribute warning option that can point functions which ought to be declared const or pure.