Where can I learn about compilers and assert optimization?

Viewed 132

We discovered recently that compilers (for us it is GCC) can optimize some code in conjunction with asserts set by developers.

This code for example:

#include <cassert>
int getBatteryLevel(){
    return 0;
}
int process(int level);
int main() {
    [[maybe_unused]] const auto level = getBatteryLevel();
    assert(level > 0);
    process(level);
}

Will link with -O2 even if process has no implementation. It does not link without optimizations.

Is this documented anywhere?

1 Answers

Is this documented anywhere?

The documentation of optimisations isn't very thorough. The optimisations that are probably used here are "inline expansion", "constant folding" and "dead code elmination".

Where can I learn about compilers

Books are a good place to start, unless you intend to invent computing from ground up. Academic papers can also contain good information, but filtering out irrelevant stuff, and figuring out required preliminary knowledge can be a lot of work. Plus, they tend to be quite expensive per unit of information.


P.S. If you don't define the function that is odr-used, then the program is ill-formed. Language implementations are allowed to accept ill-formed programs, but are not required to. Usually, they are required to diagnose such bugs, but this particular case is where implementations are not required to diagnose.

Related