mercredi 7 août 2019

How to ensure some code is optimized away?

tl;dr: Can a unit test be written that e.g. whole loops are optimized away?

When coding, I prefer to stay with C++ mechanics instead of e.g. #if...#endif or keep implementation simple and argue "hey, the compiler will optimize this out anyways".

One example: In a container the destruction of elements is typically a loop:

for(size_t i = 0; i<elements; i++)
    buffer[i].~T();

This works also for build-in types such as int, as the standard allows the explicit call of the destructor also for any scalar types (C++11 12.4-15). In such case the loop does nothing and, in my expectation, is optimized out.

Second example: Code intended for debugging (or profiling or fault-injection etc.) only:

constexpr bool isDebugging = false; // somehow a global flag
void foo(int arg) {
    if( isDebugging ) {
        std::cout << "Arg was " << arg << std::endl; // may not appear in production binary!
    }
    // normal code here...
}

I can look at the disassembly, sure. But being in automotive, it's hard to control all platforms, compilers and their options. The compilers might be certified but are exceptionally buggy. So there is a fear that due to totally stupid reasons a downstream project calls later that we wasted cycles for nothing, or have caused dead debug code.

Bottom line: Is it possible to write unit tests, which give a fail if optimization is not as expected? And that certain code is not contained as safe as a #if would do?

[Timing tests come to my mind for the first problem, but being bare-metal I don't have convenient tools yet.]

Aucun commentaire:

Enregistrer un commentaire