Edison von Myosotis
Edison von Myosotis

Reputation: 643

Is there sth. similar to _udiv128 for gcc?

Is there sth. similar to MSVC's _udiv128() for gcc ? If I use __int128 variable as the dividend and have an normal "/"-divide the compiler doesn't know that the result fits in an unsigned long long and calls an external function which does the subtract and shift division manually. So it would be nice to have sth. like _udiv128().

Upvotes: 1

Views: 193

Answers (1)

chtz
chtz

Reputation: 18827

For a x86_64-only solution, you could provide an inline-assembly function:

uint64_t udiv128_64(__uint128_t a, uint64_t b, uint64_t *r)
{
    asm inline("divq %1\n\t"
        : "+A"(a)
        : "r"(b)
        : "cc");
    if(r)
        *r = a>>64; // upper half of `a` contains remainder
    return a;
}

From your comment, I assume it is ok for you, if the code crashes when the result does not fit into 64bits. Godbolt demo: https://gcc.godbolt.org/z/baezcjvxv

Another disadvantage with inline-assembly is that it won't be optimized away if the result could be computed at compile-time.

gcc does some unnecessary register movements, for the function alone, but these should usually be optimized away, if the function is inlined.

Upvotes: 1

Related Questions