michael105 / optfence

An optimization fence for C. Force gcc to calculate variables, keep functions, prevent unwanted optimizations.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

OPTFENCE

Prevent gcc from optimizing parts of the code out, under all circumstances. Even when volatile shows up useless.

It’s the end for a whole species of Heisenbugs.

Usage

#include "optfence.h", and put OPTFENCE(arg1,…​) calls wherever the trouble is.

Eventually you’ll have to typecast the arguments to (void*), in case the compiler complains.

About

While developing minilib, I’ve been confronted with "heisenbugs". Sort of, as soon you e.g. enable debug mode, or compile with debug symbols, the bugs are gone. Worse, they only sometimes do show up.

One source for heisenbugs is the optimizer of gcc.

E.g., with assembly inline syscalls, sometimes (!) not all arguments are computed correctly, instead the optimizer decides, they are unused. Even more annoying is the fact, that many syscalls will quite often work also with scrambled arguments. Quite some fun, until the assembly revealed its dark secret.

I tried several things, from not optimizing some functions, clobbers to volatile stuff - hopeless.

The solution I came up with is the macro "OPTFENCE". Which showed up useful in other cases, too.

The macro expands to the following code:

asm("jmp 1f");
optfence(arg1,arg2,..);
asm volatile("1:");

optfence is an empty function, with the attributes naked and noipa.

static void __attribute__((naked,noipa,cold))optfence(...){
}

The asm inline jump over the call to optfence is not recognized by gcc; furthermore, gcc ignores whats inside the function optfence (nothing), due to the attribute noipa.

The attribute naked means, there is no code for the function itself generated. (prepare stack).

This is a patch to (IMHO) a compiler bug. However, the macro should be a save way for preventing unhappy optimizations. Not only with gcc.

The overhead is neglecticle, albite a few bytes are generated. (~,say, 16 Bytes for setting up the function call to optfence, and the empty function).

Copyright 2021 Michael misc Myer

BSD 3-Clause

About

An optimization fence for C. Force gcc to calculate variables, keep functions, prevent unwanted optimizations.

License:BSD 3-Clause "New" or "Revised" License


Languages

Language:C 100.0%