Skip to content

x86 optimization: logical AND and OR in if-conditionals can turn to multiple branch instructions #160612

@Explorer09

Description

@Explorer09
extern void subroutine_foo(void);
extern void subroutine_bar(void);
void func_a(int x, int y) {
    if (x == 0 || y == 0)
        subroutine_foo();
    else
        subroutine_bar();
}
void func_b(int x, int y) {
    if (x == 0)
        subroutine_foo();
    else if (y == 0)
        subroutine_foo();
    else
        subroutine_bar();
}

x86-64 clang-trunk-20250924 with -Os option produces:

func_a:
        testl   %edi, %edi
        setne   %al
        testl   %esi, %esi
        setne   %cl
        testb   %cl, %al
        jne     subroutine_bar@PLT
        jmp     subroutine_foo@PLT
func_b:
        testl   %edi, %edi
        je      subroutine_foo@PLT
        testl   %esi, %esi
        je      subroutine_foo@PLT
        jmp     subroutine_bar@PLT

https://godbolt.org/z/ns1YxeKr5

Clang misses that there's no need to make temporary boolean variables for the conditional. It can use multiple branch instructions instead.

This issue looks x86 specific. Clang for AArch64 target generates optimal code.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions