Re: static_branch/jump_label vs branch merging

From: Peter Zijlstra
Date: Fri Apr 09 2021 - 09:04:23 EST


On Fri, Apr 09, 2021 at 02:03:46PM +0200, Peter Zijlstra wrote:
> On Fri, Apr 09, 2021 at 07:55:42AM -0400, David Malcolm wrote:

> > Sorry if this is a dumb question, but does the function attribute:
> > __attribute__ ((pure))
> > help here? It's meant to allow multiple calls to a predicate to be
> > merged - though I'd be nervous of using it here, the predicate isn't
> > 100% pure, since AIUI the whole point of what you've built is for
> > predicates that very rarely change - but can change occasionally.
>
> I actually tried that, but it doesn't seem to work. Given the function
> arguments are all compile time constants it should DTRT AFAICT, but
> alas.

FWIW, I tried the below patch and GCC-10.2.1 on current tip/master.

---
diff --git a/arch/x86/include/asm/jump_label.h b/arch/x86/include/asm/jump_label.h
index 610a05374c02..704438d07bc8 100644
--- a/arch/x86/include/asm/jump_label.h
+++ b/arch/x86/include/asm/jump_label.h
@@ -14,7 +14,7 @@
#include <linux/stringify.h>
#include <linux/types.h>

-static __always_inline bool arch_static_branch(struct static_key * const key, const bool branch)
+static __always_inline __pure bool arch_static_branch(struct static_key * const key, const bool branch)
{
asm_volatile_goto("1:"
".byte " __stringify(BYTES_NOP5) "\n\t"
@@ -30,7 +30,7 @@ static __always_inline bool arch_static_branch(struct static_key * const key, co
return true;
}

-static __always_inline bool arch_static_branch_jump(struct static_key * const key, const bool branch)
+static __always_inline __pure bool arch_static_branch_jump(struct static_key * const key, const bool branch)
{
asm_volatile_goto("1:"
".byte 0xe9\n\t .long %l[l_yes] - 2f\n\t"
diff --git a/include/linux/jump_label.h b/include/linux/jump_label.h
index 05f5554d860f..834086663c26 100644
--- a/include/linux/jump_label.h
+++ b/include/linux/jump_label.h
@@ -195,12 +195,12 @@ struct module;
#define JUMP_TYPE_LINKED 2UL
#define JUMP_TYPE_MASK 3UL

-static __always_inline bool static_key_false(struct static_key *key)
+static __always_inline __pure bool static_key_false(struct static_key * const key)
{
return arch_static_branch(key, false);
}

-static __always_inline bool static_key_true(struct static_key *key)
+static __always_inline __pure bool static_key_true(struct static_key * const key)
{
return !arch_static_branch(key, true);
}