Re: [PATCH RFC 4/5] x86/alternative: Improve code generation readability

From: Josh Poimboeuf
Date: Wed Apr 09 2025 - 16:02:49 EST


On Wed, Apr 09, 2025 at 11:02:29AM -0700, Linus Torvalds wrote:
> On Wed, 9 Apr 2025 at 10:41, Josh Poimboeuf <jpoimboe@xxxxxxxxxx> wrote:
> >
> > I actually think the compactness of putting the entry on a single line
> > is really nice.
>
> Yeah, I think the noise with size calculations in particular is stuff
> that I never look at, and making it one long line is better than
> multiple lines, I think.
>
> That said, for some of the alternatives, it would be even nicer if we
> could make the noise more compact by just hardcoding sizes. Our
> generic alternatives macros do result in some *very* verbose output
> that is entirely illegible to humans.

What if we were to use a global asm() to define an alternative .macro
whenever "alternative.h" gets included?

e.g.:

asm(".macro alternative oldinstr, newinstr, ft_flags\n"
"771:\t\\oldinstr\n"
"772:\t.skip -(((" alt_rlen ")-(" alt_slen ")) > 0) * "
"((" alt_rlen ")-(" alt_slen ")),0x90\n"
"773:\n"
".pushsection .altinstructions,\"a\"\n\t"
".long 771b - .\n\t" /* label */
".long 774f - .\n\t " /* new instruction */
".4byte \\ft_flags\n\t" /* feature + flags */
".byte " alt_total_slen "\n\t" /* source len */
".byte " alt_rlen "\n\t" /* replacement len */
".popsection\n"
".pushsection .altinstr_replacement, \"ax\"\n"
"774:\t\\newinstr\n"
"775:\n"
".popsection\n"
".endm");

#define ALTERNATIVE(oldinstr, newinstr, ft_flags) \
"alternative \"" oldinstr "\", \"" newinstr "\", \"" __stringify(ft_flags) "\"; "

Then it becomes extremely readable:

alternative "", "stac", "( 9*32+20)";

Of course the downside is the macro gets generated even if it's never
used.

--
Josh