Temporarily disable all purity for debug prints

bearophile bearophileHUGS at lycos.com
Mon Apr 11 15:09:39 PDT 2011


Adam D. Ruppe:

> I wonder if it would be a good idea to have logging or debug prints
> that simply lie about being pure so you can use them there.

If the compiler sees a function as pure, the debug prints may or may not appear according to how much pure-related optimizations the compiler is doing. This is a test done with C code compiled with GCC 4.6:


#include "math.h"
#include "stdio.h"

__attribute__((const, noinline))
static float sigmoid1(const float x) {
    puts("hello world");
    return 1.0f / (1.0f - exp(-x));
}

static float calculate(const float x, const unsigned int n) {
    unsigned int i;
    float sum = 0.0;
    for (i = 0; i < n; ++i)
        sum += sigmoid1(x);
    return sum;
}

int main(int argc, const char **argv) {
    const int x = argc;
    const float y = calculate(x, 20);
    printf("%f\n", y);
    return 0;
}



The GCC attribute "const" is similar to the pure of D (GCC also has the "pure" attribute but I think it's a little different). If you compile this program with -O0 you get 20 hello world, if you compile with -O3 GCC performs the pure optimizations and prints a single hello world. Is this an acceptable debug printing for you? For me it's not good enough.

An alternative solution, that avoids the need of the -disablepure switch, is to state in the D specs that pure-related optimizations are not performed if the program is not compiled in an optimized (-O) way.

I have not used D/DMD for this example because DMD isn't optimizing purity enough yet.

Bye,
bearophile


More information about the Digitalmars-d mailing list