Also, I would like to add that this is nothing more than trading one language quirk that happens to be an optimisation barrier to an other (volatile vs function calls across TUs). If we deem optimization barriers to be useful for debugging/benchmarking, then having them as attributes makes perfect sense.

On 10 June 2022 16:27:07 BST, "Lénárd Szolnoki via Std-Proposals" <std-proposals@lists.isocpp.org> wrote:
Hi,

How does this mesh with LTO? I would throw in [[gnu::noipa]] there for gcc, and at least [[gnu::noinline]] for clang (although noinline is probably not enough). But we are back at attributes. I certainly see the utility of fine grained optimisation hint attributes. I'm not sure if it needs standardisation, but it's not without precedent (likely/unlikely).

Cheers,
Lénárd


On 10 June 2022 16:06:01 BST, Arthur O'Dwyer via Std-Proposals <std-proposals@lists.isocpp.org> wrote:
On Fri, Jun 10, 2022 at 5:34 AM Marcin Jaczewski via Std-Proposals <std-proposals@lists.isocpp.org> wrote:
> >> >
> >> >     void foo(int *p) {
> >> >         if (!p) { printf("null pointer\n"); }
> >> >         volatile bool b = false;
> >> >         if (b) { abort(); }
> >> >         *p = 0;
> >> >     }
[...]
Why not simply name this attribute `[[do_not_optimize]]`?

Google Benchmark already has this, and I wouldn't be surprised if more than one corporate codebase also has it. It's a pure library feature, implementable in plain old standard C++.

    // In another .cpp file:
    void escape(void*) {}

    // In the header file:
    extern void escape(void*);
    template<class T> void DoNotOptimize(T&& t) { escape(&t); }

    void foo(int *p) {
        if (!p) { printf("null pointer\n"); }
        DoNotOptimize(p);
        *p = 0;
    }

The compiler can see that `escape(&p)` is called, but it doesn't know at compile time whether `escape` might throw or terminate, so it can't assume that the line `*p = 0` will necessarily be reached (so it can't hoist that line upward and it can't remove the null-check).

–Arthur