A memory operand with a zero offset was encoded with a mod 01 ModR/M and an explicit zero displacement byte. Use the mod 00 form instead, which saves a byte for every load, store and atomic with a zero offset, as LLVM emits them for the first field of a struct and for every plain pointer dereference. The exception are rbp and r13 as base register, where mod 00 with r/m 101 selects a RIP-relative disp32 and with SIB base 101 a disp32 without base, so these keep their displacement byte. Also let emit_st() reuse emit_insn_suffix() instead of open-coding the ModR/M encoding. Before/after for r0 = *(u64 *)(r1 + 0): 48 8b 47 00 movq 0x0(%rdi),%rax 48 8b 07 movq (%rdi),%rax Signed-off-by: Daniel Borkmann --- arch/x86/net/bpf_jit_comp.c | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c index adec4f8e422e..70243ccbe423 100644 --- a/arch/x86/net/bpf_jit_comp.c +++ b/arch/x86/net/bpf_jit_comp.c @@ -1120,18 +1120,26 @@ static void emit_movsx_reg(u8 **pprog, int num_bits, bool is64, u32 dst_reg, *pprog = prog; } +/* + * rbp and r13 as base register always need a displacement, since mod 00 + * with r/m 101 encodes a RIP-relative disp32 and with SIB base 101 a + * disp32 without base instead. + */ +static bool base_needs_disp(u32 reg) +{ + return reg2hex[reg] == 5; +} + /* Emit the suffix (ModR/M etc) for addressing *(ptr_reg + off) and val_reg */ static void emit_insn_suffix(u8 **pprog, u32 ptr_reg, u32 val_reg, int off) { u8 *prog = *pprog; - if (is_imm8(off)) { - /* 1-byte signed displacement. - * - * If off == 0 we could skip this and save one extra byte, but - * special case of x86 R13 which always needs an offset is not - * worth the hassle - */ + if (!off && !base_needs_disp(ptr_reg)) { + /* No displacement */ + EMIT1(add_2reg(0x00, ptr_reg, val_reg)); + } else if (is_imm8(off)) { + /* 1-byte signed displacement */ EMIT2(add_2reg(0x40, ptr_reg, val_reg), off); } else { /* 4-byte signed displacement */ @@ -1144,7 +1152,10 @@ static void emit_insn_suffix_SIB(u8 **pprog, u32 ptr_reg, u32 val_reg, u32 index { u8 *prog = *pprog; - if (is_imm8(off)) { + if (!off && !base_needs_disp(ptr_reg)) { + EMIT2(add_2reg(0x04, BPF_REG_0, val_reg), + add_2reg(0, ptr_reg, index_reg) /* SIB */); + } else if (is_imm8(off)) { EMIT3(add_2reg(0x44, BPF_REG_0, val_reg), add_2reg(0, ptr_reg, index_reg) /* SIB */, off); } else { EMIT2_off32(add_2reg(0x84, BPF_REG_0, val_reg), add_2reg(0, ptr_reg, index_reg) /* SIB */, off); @@ -1507,11 +1518,7 @@ static void emit_st(u8 **pprog, struct bpf_insn *insn, u32 dst_reg, break; } - if (is_imm8(insn_off)) - EMIT2(add_1reg(0x40, dst_reg), insn_off); - else - EMIT1_off32(add_1reg(0x80, dst_reg), insn_off); - + emit_insn_suffix(&prog, dst_reg, BPF_REG_0, insn_off); EMIT(imm32, bpf_size_to_x86_bytes(BPF_SIZE(insn->code))); *pprog = prog; } -- 2.43.0