[PATCH v4 5/5] lib: test_bitops: add compile-time optimization/evaluations assertions

From: Vincent Mailhol
Date: Sun Jan 28 2024 - 00:07:42 EST


Add a function in the bitops test suite to assert that the bitops
helper functions correctly fold into constant expressions (or trigger
a build bug otherwise). This should work on all the optimization
levels supported by Kbuild.

The added function does not perform any runtime tests and gets
optimized out to nothing after passing the build assertions.

Suggested-by: Yury Norov <yury.norov@xxxxxxxxx>
Signed-off-by: Vincent Mailhol <mailhol.vincent@xxxxxxxxxx>
---
lib/Kconfig.debug | 4 ++++
lib/test_bitops.c | 32 ++++++++++++++++++++++++++++++++
2 files changed, 36 insertions(+)

diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug
index 4405f81248fb..85f8638b3ae6 100644
--- a/lib/Kconfig.debug
+++ b/lib/Kconfig.debug
@@ -2439,6 +2439,10 @@ config TEST_BITOPS
compilations. It has no dependencies and doesn't run or load unless
explicitly requested by name. for example: modprobe test_bitops.

+ In addition, check that the compiler is able to fold the bitops
+ function into a compile-time constant (given that the argument is also
+ a compile-time constant) and trigger a build bug otherwise.
+
If unsure, say N.

config TEST_VMALLOC
diff --git a/lib/test_bitops.c b/lib/test_bitops.c
index 3b7bcbee84db..99b612515eb6 100644
--- a/lib/test_bitops.c
+++ b/lib/test_bitops.c
@@ -50,6 +50,34 @@ static unsigned long order_comb_long[][2] = {
};
#endif

+/* Assert that a boolean expression can be folded in a constant and is true. */
+#define test_const_eval(test_expr) \
+({ \
+ /* Evaluate once so that compiler can fold it. */ \
+ bool __test_expr = test_expr; \
+ \
+ BUILD_BUG_ON(!__builtin_constant_p(__test_expr)); \
+ BUILD_BUG_ON(!__test_expr); \
+})
+
+/*
+ * On any supported optimization level (-O2, -Os) and if invoked with
+ * a compile-time constant argument, the compiler must be able to fold
+ * into a constant expression all the bit find functions. Namely:
+ * __ffs(), ffs(), ffz(), __fls(), fls() and fls64(). Otherwise,
+ * trigger a build bug.
+ */
+static __always_inline void test_bitops_const_eval(unsigned int n)
+{
+ test_const_eval(__ffs(BIT(n)) == n);
+ test_const_eval(ffs(BIT(n)) == n + 1);
+ test_const_eval(ffz(~BIT(n)) == n);
+ test_const_eval(__fls(BIT(n)) == n);
+ test_const_eval(fls(BIT(n)) == n + 1);
+ test_const_eval(fls64(BIT_ULL(n)) == n + 1);
+ test_const_eval(fls64(BIT_ULL(n + 32)) == n + 33);
+}
+
static int __init test_bitops_startup(void)
{
int i, bit_set;
@@ -94,6 +122,10 @@ static int __init test_bitops_startup(void)
if (bit_set != BITOPS_LAST)
pr_err("ERROR: FOUND SET BIT %d\n", bit_set);

+ test_bitops_const_eval(0);
+ test_bitops_const_eval(10);
+ test_bitops_const_eval(31);
+
pr_info("Completed bitops test\n");

return 0;
--
2.43.0