rust-lang / rust-lang/rust-clippy

`div_ceil` does not yield optimal code for unsigned const divisor

Open
#15,322 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Let's say we have a function:

fn foo(begin: usize) -> usize {
    (begin + 128 - 1) / 128
}

This compiles to:

foo:
        leaq    127(%rdi), %rax
        shrq    $7, %rax
        retq

But clippy suggests that I should use div_ceil:

fn foo(begin: usize) -> usize {
    begin.div_ceil(128)
}

... which compiles to:

foo:
        movq    %rdi, %rax
        shrq    $7, %rax
        andl    $127, %edi
        cmpq    $1, %rdi
        sbbq    $-1, %rax
        retq

It seems that the original version produces better code on x86_64 with only two instructions (without the retq), but 5 instructions (without the retq) for the div_ceil version.

Godbolt

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names no repository files or tests. Start with the Rust example and linked Godbolt comparison, then inspect how Clippy produces the div_ceil suggestion for unsigned constant divisors. Done means deciding the expected behavior and verifying it with an appropriate regression test and codegen comparison.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
performance, tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.