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

--- Comment #6 from Kang-Che Sung <Explorer09 at gmail dot com> ---
Hello.

I'm not sure if GCC developers are still looking at the issue or thinking of
how to optimize this. But I found an interesting case where the ((x >> 7) == 0)
optimization can make smaller code on one architecture but makes larger code on
another.

This code is from my personal code snippet:

```c
// Code simplified from <https://gitlab.com/Explorer09/utf_convert>

uint32_t utf8_to_code_point(const uint8_t **sequence)
{
    uint32_t value = *(*sequence)++;

#if VARIANT == 1
    if (value <= 0x7F)
#elif VARIANT == 2
    if ((value >> 7) == 0)
#endif
    {
        return value;
    }

    uint32_t mask = 1 << 6;
    while ((value & mask) != 0) {
#if VARIANT == 1
        if ((unsigned int)**sequence - 0x80 > 0x3F)
#elif VARIANT == 2
        if ((((unsigned int)**sequence - 0x80) >> 6) > 0)
#endif
        {
            return (uint32_t)-1;
        }
        value = (value << 6) | ((unsigned int)**sequence - 0x80);
        (*sequence)++;
        mask <<= 5;
    }

    value &= (mask - 1);

    if (value <= (((mask - 1) >> 5) | 0x7F)) {
        return (uint32_t)-1;
    }
    if ((value >> 11) == (0xD800 >> 11)) {
        return (uint32_t)-1;
    }
    return value;
}
```

In x86-64, VARIANT 1 is smaller.
In RV32 and RV64, VARIANT 2 compiles to smaller code. (The code size difference
is negligible (just 4 bytes). In the performance perspective this might not be
worth it, but in `-Oz` mode this is an optimization to consider).
In AArch64 and ARM, the code sizes are the same (doesn't seem to have an
obvious winner).

Reply via email to