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

Poor optimization of negative signs #46

Open
dtolnay opened this issue Nov 20, 2024 · 1 comment
Open

Poor optimization of negative signs #46

dtolnay opened this issue Nov 20, 2024 · 1 comment

Comments

@dtolnay
Copy link
Owner

dtolnay commented Nov 20, 2024

#[inline(never)]
fn repro(buffer: &mut itoa::Buffer, n: i32) -> &str {
    buffer.format(n)
}

fn main() {
    println!("{}", repro(&mut itoa::Buffer::new(), i32::MIN));
}

The x86_64 assembly for repro is:

mov rax, rdi
mov edx, 11
movabs rcx, 3905527098775974194
mov word ptr [rdi + 9], 14388
mov qword ptr [rdi + 1], rcx
mov byte ptr [rdi], 45
ret

The string returned by repro is "-2147483648". The four immediates visible in the assembly are:

  • 11: string length
  • 3905527098775974194: first 8 digits 0x3633383437343132
  • 14388: last 2 digits 0x3834
  • 45: ASCII '-'

A better implementation might be able to compile to just 3 immediates.

@dtolnay
Copy link
Owner Author

dtolnay commented Nov 20, 2024

Desired output:

mov rax, rdi
mov edx, 11
movabs rcx, 3690757306333606445
mov dword ptr [rdi + 7], 942945843
mov qword ptr [rdi], rcx
ret

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

No branches or pull requests

1 participant