Skip to content

a & ~(a - b) optimizes to a & (~a + b) even though most targets have an ANDN instruction #140639

@Validark

Description

@Validark

Godbolt link

#include <stdint.h>

uint64_t foo(uint64_t a, uint64_t b) {
    return a & ~(a - b);
}

Optimized LLVM IR:

define dso_local i64 @foo(i64 %0, i64 %1) local_unnamed_addr {
Entry:
  %2 = xor i64 %0, -1
  %3 = add i64 %2, %1
  %4 = and i64 %3, %0
  ret i64 %4
}

Should be: (llc godbolt)

define dso_local i64 @foo(i64 %0, i64 %1) local_unnamed_addr {
Entry:
  %2 = sub i64 %0, %1
  %3 = xor i64 %2, -1
  %4 = and i64 %3, %0
  ret i64 %4
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions