C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Second draft of a __COUNTER__ proposal

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Mon, 26 Aug 2024 18:22:42 -0400
On Mon, Aug 26, 2024 at 3:16 PM Jeremy Rifkin via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Good idea. I gave that a try as well as another approach but was
> unable to produce a sufficiently large __COUNTER__ before gcc
> segfaulted after (around a count of 270 million). I'm impartial on
> specifying a 32-bit counter vs a 64-bit counter, both seem reasonable
> to me.
>

Could you share your approach?
For comparison, I used this Python script to generate 50 million
__COUNTER__ invocations:

cat >test.py <<EOF
import sys
print("""
#define C __COUNTER__
#define D C|C|C|C|C|C|C|C|C|C
#define S static_assert(D|D|D|D|D|D|D|D|D|D)
#define T S;S;S;S;S;S;S;S;S;S
#define U T;T;T;T;T;T;T;T;T;T
""")
for i in range(int(sys.argv[1])):
  print("U;")
print("")
EOF
time python test.py 5000 >test.cpp ; time clang++ test.cpp -fsyntax-only
-std=c++17

This compilation takes about 30 seconds on my machine.
But AppleClang starts ICEing ("translation unit is too large for Clang to
process: ran out of source locations") somewhere between 50 million and 100
million, so that didn't tell me anything about the practical behavior of
its __COUNTER__ on overflow.

FWIW, looking at the actual *code* of each compiler, it's easy to tell
that...
- Clang uses an `unsigned`
<https://github.com/llvm/llvm-project/blob/295e4f49aefb2b07501be9f845df598b3ee280f1/clang/include/clang/Lex/Preprocessor.h#L214-L215>
32-bit
__COUNTER__, and wraps to zero
<https://github.com/llvm/llvm-project/blob/295e4f49aefb2b07501be9f845df598b3ee280f1/clang/lib/Lex/PPMacroExpansion.cpp#L1772-L1773>
on overflow.
- GCC uses an `unsigned int`
<https://github.com/gcc-mirror/gcc/blob/942497ad74272e0ef16020d628e471c5f21474b0/libcpp/internal.h#L591-L592>
32-bit __COUNTER__, and wraps to zero
<https://github.com/gcc-mirror/gcc/blob/942497ad74272e0ef16020d628e471c5f21474b0/libcpp/macro.cc#L663>
on overflow.

Cheers,
Arthur

Received on 2024-08-26 22:22:59