3

I have some valid C++ code that does not compile under ubsan with g++. In a nutshell (https://gcc.godbolt.org/z/9qvz89na8):

struct foo {
  void bar() { }
};

void process(auto f) {
  if constexpr(&decltype(f)::bar);
}

int main() {
  process(foo{});
}

yields

In instantiation of 'void process(auto:1) [with auto:1 = foo]':
error: '(foo::bar != 0)' is not a constant expression

Thus I want to detect if I am building under ubsan, to try to mitigate the issue by making the if constexpr conditionally constexpr.

It's trivial under clang, but with g++ when I try to look at the predefined macros:

echo | g++ -fsanitize=undefined -dM -E -

I cannot see anything that hints that ubsan is enabled. Is there any way to detect this?

Jean-Michaël Celerier
  • 7,412
  • 3
  • 54
  • 75
  • this is of course a reduction from a more complex example, where the function pointer actually can be null.. https://github.com/woboq/verdigris/blob/master/src/wobjectimpl.h#L1180 so no, the code isn't buggy and yes this is the intention. And ubsan being right or not cannot be known because ubsan isn't even running yet at this point, it's purely a run-time feature and this is a compile-time problem. – Jean-Michaël Celerier Aug 07 '23 at 16:05

1 Answers1

1

Here is an oracle that seems to work.

template<class T>
concept Check = sizeof(int[&T::bar != nullptr]) == sizeof(int[true]);

See: https://gcc.godbolt.org/z/jra1bbY43 for full example.