GCC optimization of pure functions

I am confused by the guarantees that GCC makes to optimize functions pure(from online documents ):

pure

Many functions have no effects other than a return value, and their return value depends only on parameters and / or global variables. (...)

Interesting impure functions are functions with infinite loops or those that depend on volatile memory or other system resources that can change between two consecutive calls (for example, feofin a multithreading environment).

And for const:

const

Many functions do not check values ​​other than their arguments, and have no effects other than the return value. Basically, this is a slightly more strict class than the pure attribute below, since functions are not allowed to read global memory.

Note that a function that has pointer arguments and examines the data should not be declaredconst . Similarly, a function that calls a non-constant function usually should not be const.

So, I tried to create a function that takes a pointer parameter, and tried to label it pure. However, I tried to compile this function using GCC online (I tried both const, and pure):

typedef struct
{
    int32_t start;
    int32_t end;
}
Buffer;

inline __attribute__((pure,always_inline)) int32_t getLen(Buffer * b) 
{
    return b->end - b->start;
}

And noticed that GCC (at least a few online compiler versions I tried):

  • (.. ), Buffer* ,
  • (.. ), () .
  • , const pure, const , ?

, Buffer / , Buffer .

. , GCC pure, ?

+4
2

, GCC , ?

, ; , IO.

, const- inline; , , . , , .

, , const-:

__attribute__((__pure__)) int a();
__attribute__((__const__)) int b();
void c();

a , , , a ; , a , , a:

int f() {
    int i = a();
    i += a();
    return i;  // optimized to "return a() * 2;"
}

c a, , a c:

int g() {
    int i = a();
    c();
    i += a();
    return i;  // no optimization possible
}

, a const b, , b , c :

int h() {
    int i = b();
    c();
    i += b();
    return i;  // optimized to "c(); return b() * 2;"
}
+3

" GCC".

. pure const promises, GCC.

promises, . , , ( , , ). pure const .

+1

Source: https://habr.com/ru/post/1681783/


All Articles