movzx into a 32-bit register already clears the upper 32 bits, so the REX.W prefix on the 8 and 16-bit BPF_LDX loads only costs a byte. This also matches what the arena variants of these loads emit. Likewise, the 32-bit movsx from an 8-bit register only needs a REX prefix when the destination is an extended register or the source is sil, dil, bpl or an extended register. LLVM emits these loads for u8 and u16 fields and, with cpu v4, the movsx for a cast to s8 or s16. Before/after for r0 = *(u8 *)(r1 + 0): 48 0f b6 47 00 movzbq 0x0(%rdi),%rax 0f b6 47 00 movzbl 0x0(%rdi),%eax Before/after for w1 = (s8)w0: 40 0f be f8 movsbl %al,%edi 0f be f8 movsbl %al,%edi Signed-off-by: Daniel Borkmann --- arch/x86/net/bpf_jit_comp.c | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c index 083fcd6cf15b..adec4f8e422e 100644 --- a/arch/x86/net/bpf_jit_comp.c +++ b/arch/x86/net/bpf_jit_comp.c @@ -1106,8 +1106,9 @@ static void emit_movsx_reg(u8 **pprog, int num_bits, bool is64, u32 dst_reg, } else { /* movs[b,w]l dst, src */ if (num_bits == 8) { - EMIT4(add_2mod(0x40, src_reg, dst_reg), 0x0f, 0xbe, - add_2reg(0xC0, src_reg, dst_reg)); + if (is_ereg(dst_reg) || is_ereg_8l(src_reg)) + EMIT1(add_2mod(0x40, src_reg, dst_reg)); + EMIT3(0x0f, 0xbe, add_2reg(0xC0, src_reg, dst_reg)); } else if (num_bits == 16) { if (is_ereg(dst_reg) || is_ereg(src_reg)) EMIT1(add_2mod(0x40, src_reg, dst_reg)); @@ -1273,12 +1274,16 @@ static void emit_ldx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off) switch (size) { case BPF_B: - /* Emit 'movzx rax, byte ptr [rax + off]' */ - EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB6); + /* Emit 'movzx eax, byte ptr [rax + off]' */ + if (is_ereg(dst_reg) || is_ereg(src_reg)) + EMIT1(add_2mod(0x40, src_reg, dst_reg)); + EMIT2(0x0F, 0xB6); break; case BPF_H: - /* Emit 'movzx rax, word ptr [rax + off]' */ - EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB7); + /* Emit 'movzx eax, word ptr [rax + off]' */ + if (is_ereg(dst_reg) || is_ereg(src_reg)) + EMIT1(add_2mod(0x40, src_reg, dst_reg)); + EMIT2(0x0F, 0xB7); break; case BPF_W: /* Emit 'mov eax, dword ptr [rax+0x14]' */ -- 2.43.0