https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89035

            Bug ID: 89035
           Summary: Request - builtins for unspecified and arbitrary
                    values
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: david at westcontrol dot com
  Target Milestone: ---

Occasionally it is useful to have an unspecified or arbitrary value in C (and
C++) programming.  For example, you might want to have a function that
calculates a particular value for valid inputs, and returns an unspecified
value on invalid inputs.

At the moment, gcc has __builtin_unreachable() to indicate intentional manually
created undefined behaviour - it is useful for getting optimal code, and also
for documenting code.  And it provides a reliable way of saying "this can't
happen", unlike other undefined behaviour (such as writing "1/0;").

Unspecified and arbitrary values are different from undefined values - the
compiler is free to pick them in any way it likes, but the values are valid and
non-trapping, and operations using them are defined behaviour, though with
possibly unspecified or arbitrary results.

An unspecified value can be created by making a local variable and leaving it
uninitialised - but that will usually be flagged by a warning from gcc, and it
is not clear in the code.  An arbitrary value can be generated by inline
assembly, such as " int x;  asm("" : "=r" (x)); " which generates no code. 
However, that does not give the compiler freedom to pick a different arbitrary
value of its liking.

I would like to suggest there be builtin functions __builtin_unspecified() and
__builtin_arbitrary().  They would both return an "int" - I don't think there
is need for any other types.

The difference between this can be seen with code like this:

    int x = __builtin_arbitrary();
    int y = x - x;    // y is guaranteed to be 0.

    int x = __builtin_unspecified();
    int y = x - x;    // y is unspecified.

An initial implementation could be very simple.

__builtin_unspecified() can use the existing unspecified value logic in the
compiler, or could be viewed as __builtin_arbitrary().

__builtin_arbitrary() can work like the inline assembly shown above, or just
return 0.

Of course, a better implementation would allow more optimisations - the
compiler could pick different values that result in more efficient code later.

Reply via email to