Skip to content

Unnecessary compares and branches in asm output #45459

@Boscop

Description

@Boscop

https://godbolt.org/g/62GNZf

pub fn f1(v: &mut Vec<f32>) {
  v.clear();
}

pub fn f2(v: &mut Vec<f32>) {
  unsafe { v.set_len(0); }
}
example::f1:
  push rbp
  mov rbp, rsp
  cmp qword ptr [rdi + 16], 0
  je .LBB0_2
  mov qword ptr [rdi + 16], 0
.LBB0_2:
  pop rbp
  ret

example::f2:
  push rbp
  mov rbp, rsp
  mov qword ptr [rdi + 16], 0
  pop rbp
  ret

In f1, the lines cmp qword ptr [rdi + 16], 0 and je .LBB0_2 should be optimized away, but aren't, why?
(It sets the len to 0 if it's not 0, otherwise leaves it at 0. The len will be 0 afterwards either way, so it should eliminate the check and just set it to 0 like set_len(0).)

I thought I'd open this issue because I don't think such optimization opportunities should be left on the table because it accumulatively affects a lot of code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchE-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.I-slowIssue: Problems and improvements with respect to performance of generated code.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions