[PATCH 2/2] x86/bootflag: Use __builtin_parity() when available

From: Uros Bizjak
Date: Wed Jan 29 2025 - 10:49:51 EST


Compilers (GCC and clang) provide optimized __builtin_parity() function
that returns the parity of X, i.e. the number of 1-bits in X modulo 2.

Use __builtin_parity() built-in function to optimize parity(). This
improves generated parity code to just:

57: 84 db test %bl,%bl
59: 7a 5c jp b7 <sbf_init+0xa7>

where TEST instruction sets parity flag (PF) in EFLAGS, exercised by the
follow-up jump instruction.

Signed-off-by: Uros Bizjak <ubizjak@xxxxxxxxx>
Cc: Thomas Gleixner <tglx@xxxxxxxxxxxxx>
Cc: Ingo Molnar <mingo@xxxxxxxxxx>
Cc: Borislav Petkov <bp@xxxxxxxxx>
Cc: Dave Hansen <dave.hansen@xxxxxxxxxxxxxxx>
Cc: "H. Peter Anvin" <hpa@xxxxxxxxx>
---
arch/x86/kernel/bootflag.c | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/arch/x86/kernel/bootflag.c b/arch/x86/kernel/bootflag.c
index 4d89a2d80d0f..d63247d7abd4 100644
--- a/arch/x86/kernel/bootflag.c
+++ b/arch/x86/kernel/bootflag.c
@@ -22,6 +22,9 @@ int sbf_port __initdata = -1; /* set via acpi_boot_init() */

static bool __init parity(u8 v)
{
+#if __has_builtin(__builtin_parity)
+ int x = __builtin_parity(v);
+#else
int x = 0;
int i;

@@ -29,7 +32,7 @@ static bool __init parity(u8 v)
x ^= (v & 1);
v >>= 1;
}
-
+#endif
return !!x;
}

--
2.42.0