Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Failure to unroll loop with unknown but small count #116119

Open
Kmeakin opened this issue Nov 13, 2024 · 1 comment
Open

Failure to unroll loop with unknown but small count #116119

Kmeakin opened this issue Nov 13, 2024 · 1 comment

Comments

@Kmeakin
Copy link
Contributor

Kmeakin commented Nov 13, 2024

Consider this function that calculates the number of digits in n's base-10 representation (eg as part of a formatting library):

u8 src(u8 n) {
    u8 num_digits = 0;
    do {
        num_digits++;
        n /= 10;
    } while (n != 0);
    return num_digits;
}

Since n is in the range 0-255, the loop will run exactly 1, 2 or 3 times, and the function can be optimized by unrolling the loop manually:

u8 intermediate(u8 n) {
    u8 num_digits = 0;

    // iteration 1
    num_digits++;
    n /= 10;
    if (n == 0) return num_digits;

    // iteration 2
    num_digits++;
    n /= 10;
    if (n == 0) return num_digits;

    // iteration 3
    num_digits++;
    n /= 10;

    return num_digits;
}

which then simplifies to:

u8 tgt(u8 n) {
    if (n < 10) return 1;
    if (n < 100) return 2;
    return 3;
}

LLVM is smart enough to do this optimization if the base is 16, but not for any other base

@VedantParanjape
Copy link

So do you mean this unrolling works for u16?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants