Skip to content

Truly independent web browser

LibJS/JIT: Keep x86-64 branches within 32-byte windows

Andreas Klingc3d53ea41b88
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/buffer.rs b/Libraries/LibJS/JIT/Rust/src/asm/buffer.rs
index 8aa7f99bea1..059e629be3e 100644
--- a/Libraries/LibJS/JIT/Rust/src/asm/buffer.rs
+++ b/Libraries/LibJS/JIT/Rust/src/asm/buffer.rs
@@ -109,6 +109,19 @@ pub struct PendingFixup {
pub label: Label,
}
+/// A point in the emission that `CodeBuffer::rewind()` goes back to.
+#[derive(Debug, Clone, Copy)]
+pub struct Checkpoint {
+ offset: usize,
+ fixup_count: usize,
+}
+
+impl Checkpoint {
+ pub fn offset(&self) -> usize {
+ self.offset
+ }
+}
+
/// A growable code buffer with labels.
#[derive(Debug, Default)]
pub struct CodeBuffer {
@@ -239,6 +252,29 @@ impl CodeBuffer {
self.fixups[id as usize].resolved = true;
}
+ pub fn checkpoint(&self) -> Checkpoint {
+ Checkpoint {
+ offset: self.offset(),
+ fixup_count: self.fixups.len(),
+ }
+ }
+
+ /// Drops what was emitted after `checkpoint`, and the references it made. No label may have been bound since.
+ pub fn rewind(&mut self, checkpoint: Checkpoint) {
+ while self.fixups.len() > checkpoint.fixup_count {
+ let fixup = self.fixups.pop().expect("there are fixups past the checkpoint");
+ let state = &mut self.labels[fixup.label.0 as usize];
+ debug_assert!(
+ matches!(*state, LabelState::Unbound { first_fixup } if first_fixup as usize == self.fixups.len()),
+ "a label was bound after the checkpoint"
+ );
+ *state = LabelState::Unbound {
+ first_fixup: fixup.next,
+ };
+ }
+ self.bytes.truncate(checkpoint.offset);
+ }
+
/// Pads with `filler` until the offset is a multiple of `alignment`.
pub fn align_with(&mut self, alignment: usize, filler: u8) {
assert!(alignment.is_power_of_two());
@@ -316,6 +352,28 @@ mod tests {
assert_eq!(code, [0xeb, 3, 0x90, 0x90, 0x90, 0xe9, 0xfb, 0xff, 0xff, 0xff]);
}
+ #[test]
+ fn rewinding_drops_code_and_its_references() {
+ let mut buffer = CodeBuffer::new();
+ let label = buffer.new_label();
+ buffer.emit_u8(0xeb);
+ buffer.emit_u8(0);
+ buffer.add_fixup(label, 1, FixupKind::X86Rel8);
+ let checkpoint = buffer.checkpoint();
+ buffer.emit_u8(0xeb);
+ buffer.emit_u8(0);
+ buffer.add_fixup(label, 3, FixupKind::X86Rel8);
+ buffer.rewind(checkpoint);
+ assert_eq!(buffer.offset(), 2);
+ buffer.emit_u8(0x90);
+ buffer.emit_u8(0xeb);
+ buffer.emit_u8(0);
+ buffer.add_fixup(label, 4, FixupKind::X86Rel8);
+ buffer.bind(label);
+ let code = buffer.finish().unwrap();
+ assert_eq!(code, [0xeb, 3, 0x90, 0xeb, 0]);
+ }
+
#[test]
fn unbound_label_fails() {
let mut buffer = CodeBuffer::new();
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs
index 67f7bf93990..30a09f7a864 100644
--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs
+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs
@@ -137,6 +137,12 @@ fn double_flags(condition: DoubleCondition) -> DoubleFlags {
}
}
+impl BranchGroups for MacroAssembler {
+ fn branch_assembler(&mut self) -> &mut Assembler {
+ &mut self.assembler
+ }
+}
+
impl MacroAssembler {
/// `dst = lhs op rhs` for a commutative operation.
fn commutative(&mut self, op: AluOp, width: Width, dst: Gpr, lhs: Gpr, rhs: Gpr) {
@@ -726,6 +732,8 @@ impl PortableMacroAssembler for MacroAssembler {
self.shift_imm(ShiftOp::Sar, W64, dst, src, amount);
}
+ // NB: Overflow branches do not macro-fuse with the arithmetic before them, so they keep only themselves within
+ // a branch window (see `BranchGroups::branch_group()`).
fn branch_add32_overflow(&mut self, dst: Gpr, lhs: Gpr, rhs: Gpr, overflow: Label) {
self.commutative(AluOp::Add, W32, dst, lhs, rhs);
self.assembler.jcc(Cond::Overflow, overflow);
@@ -767,18 +775,24 @@ impl PortableMacroAssembler for MacroAssembler {
}
fn branch32(&mut self, condition: Condition, lhs: Gpr, rhs: Gpr, target: Label) {
- self.assembler.cmp_rr(W32, lhs, rhs);
- self.assembler.jcc(condition_code(condition), target);
+ self.branch_group(|m| {
+ m.assembler.cmp_rr(W32, lhs, rhs);
+ m.assembler.jcc(condition_code(condition), target);
+ });
}
fn branch32_imm(&mut self, condition: Condition, lhs: Gpr, imm: i32, target: Label) {
- self.compare_imm(W32, lhs, i64::from(imm));
- self.assembler.jcc(condition_code(condition), target);
+ self.branch_group(|m| {
+ m.compare_imm(W32, lhs, i64::from(imm));
+ m.assembler.jcc(condition_code(condition), target);
+ });
}
fn branch64(&mut self, condition: Condition, lhs: Gpr, rhs: Gpr, target: Label) {
- self.assembler.cmp_rr(W64, lhs, rhs);
- self.assembler.jcc(condition_code(condition), target);
+ self.branch_group(|m| {
+ m.assembler.cmp_rr(W64, lhs, rhs);
+ m.assembler.jcc(condition_code(condition), target);
+ });
}
fn branch_if_stack_pointer_below(&mut self, limit: &Address, target: Label) {
@@ -786,53 +800,73 @@ impl PortableMacroAssembler for MacroAssembler {
}
fn branch64_imm(&mut self, condition: Condition, lhs: Gpr, imm: i64, target: Label) {
- self.compare_imm(W64, lhs, imm);
- self.assembler.jcc(condition_code(condition), target);
+ self.branch_group(|m| {
+ m.compare_imm(W64, lhs, imm);
+ m.assembler.jcc(condition_code(condition), target);
+ });
}
fn branch32_memory_imm(&mut self, condition: Condition, address: &Address, imm: i32, target: Label) {
- self.assembler.cmp_mi(W32, address, imm);
- self.assembler.jcc(condition_code(condition), target);
+ self.branch_group(|m| {
+ m.assembler.cmp_mi(W32, address, imm);
+ m.assembler.jcc(condition_code(condition), target);
+ });
}
fn branch16_memory_imm(&mut self, condition: Condition, address: &Address, imm: u16, target: Label) {
// NB: 16-bit compares only see the low 16 bits, so a sign-extended
// imm8 matches the zero-extended value if it has the same bits.
match i8::try_from(imm as i16) {
- Ok(imm8) if matches!(condition, Condition::Equal | Condition::NotEqual) => {
- self.assembler.cmp16_mi8(address, imm8);
- }
+ Ok(imm8) if matches!(condition, Condition::Equal | Condition::NotEqual) => self.branch_group(|m| {
+ m.assembler.cmp16_mi8(address, imm8);
+ m.assembler.jcc(condition_code(condition), target);
+ }),
_ => {
self.assembler.movzx16_rm(SCRATCH, address);
- self.assembler.cmp_ri(W32, SCRATCH, i32::from(imm));
+ self.branch32_imm(condition, SCRATCH, i32::from(imm), target);
}
}
- self.assembler.jcc(condition_code(condition), target);
}
fn branch64_memory(&mut self, condition: Condition, address: &Address, rhs: Gpr, target: Label) {
- self.assembler.cmp_mr(W64, address, rhs);
- self.assembler.jcc(condition_code(condition), target);
+ self.branch_group(|m| {
+ m.assembler.cmp_mr(W64, address, rhs);
+ m.assembler.jcc(condition_code(condition), target);
+ });
}
fn branch64_memory_imm(&mut self, condition: Condition, address: &Address, imm: i64, target: Label) {
- if let Ok(imm) = i32::try_from(imm) {
- self.assembler.cmp_mi(W64, address, imm);
- } else {
+ let Ok(imm) = i32::try_from(imm) else {
self.move_imm64(SCRATCH, imm as u64);
- self.assembler.cmp_mr(W64, address, SCRATCH);
- }
- self.assembler.jcc(condition_code(condition), target);
+ self.branch64_memory(condition, address, SCRATCH, target);
+ return;
+ };
+ self.branch_group(|m| {
+ m.assembler.cmp_mi(W64, address, imm);
+ m.assembler.jcc(condition_code(condition), target);
+ });
}
fn branch_test32(&mut self, condition: Condition, value: Gpr, mask: u32, target: Label) {
- self.test_mask(W32, value, u64::from(mask));
- self.assembler.jcc(condition_code(condition), target);
+ self.branch_group(|m| {
+ m.test_mask(W32, value, u64::from(mask));
+ m.assembler.jcc(condition_code(condition), target);
+ });
}
fn branch_test64(&mut self, condition: Condition, value: Gpr, mask: u64, target: Label) {
- self.test_mask(W64, value, mask);
- self.assembler.jcc(condition_code(condition), target);
+ if mask != u64::MAX && i32::try_from(mask as i64).is_err() {
+ self.move_imm64(SCRATCH, mask);
+ self.branch_group(|m| {
+ m.assembler.test_rr(W64, value, SCRATCH);
+ m.assembler.jcc(condition_code(condition), target);
+ });
+ return;
+ }
+ self.branch_group(|m| {
+ m.test_mask(W64, value, mask);
+ m.assembler.jcc(condition_code(condition), target);
+ });
}
fn compare32_set(&mut self, condition: Condition, dst: Gpr, lhs: Gpr, rhs: Gpr) {
@@ -999,11 +1033,15 @@ impl PortableMacroAssembler for MacroAssembler {
self.assembler.jcc(Cond::Parity, fail);
if negative_zero == NegativeZero::Fail {
let done = self.assembler.new_label();
- self.assembler.test_rr(W32, dst, dst);
- self.assembler.jcc(Cond::NotEqual, done);
+ self.branch_group(|m| {
+ m.assembler.test_rr(W32, dst, dst);
+ m.assembler.jcc(Cond::NotEqual, done);
+ });
self.assembler.movmskpd(SCRATCH, src);
- self.assembler.test_ri(W32, SCRATCH, 1);
- self.assembler.jcc(Cond::NotEqual, fail);
+ self.branch_group(|m| {
+ m.assembler.test_ri(W32, SCRATCH, 1);
+ m.assembler.jcc(Cond::NotEqual, fail);
+ });
self.assembler.bind(done);
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs
index a50d2686fcc..56a2b7bb3a1 100644
--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs
@@ -153,6 +153,51 @@ enum Prefix {
#[derive(Debug, Default)]
pub struct Assembler {
buffer: CodeBuffer,
+ /// Whether a group of instructions that ends in a branch is being emitted (see `BranchGroups::branch_group()`), whose
+ /// branches leave keeping it within a branch window to the group.
+ in_branch_group: bool,
+}
+
+/// The windows of code that branches stay within (see `BranchGroups::branch_group()`).
+const BRANCH_WINDOW: usize = 32;
+
+/// Emitters of code with branches, which keep the branches within 32-byte windows.
+pub trait BranchGroups: Sized {
+ fn branch_assembler(&mut self) -> &mut Assembler;
+
+ /// Emits a branch with `emit`, or the instructions that macro-fuse with a branch and the branch, so that they
+ /// neither cross nor end at the end of a 32-byte window, padding with NOPs to the next one where they would.
+ ///
+ /// OPTIMIZATION: Skylake-derived cores (with the microcode for their JCC erratum) keep no 32-byte window of code
+ /// with such a branch in their micro-op cache, and decode it again every time it runs, at a fraction of the rate.
+ /// Other cores only run the NOPs where code falls through to the padded branch.
+ ///
+ /// NB: `emit` runs again after the padding, so it may not bind labels or have other effects.
+ fn branch_group(&mut self, emit: impl Fn(&mut Self)) {
+ if self.branch_assembler().in_branch_group {
+ emit(self);
+ return;
+ }
+ let assembler = self.branch_assembler();
+ assembler.in_branch_group = true;
+ let checkpoint = assembler.buffer.checkpoint();
+ emit(self);
+ let assembler = self.branch_assembler();
+ let (start, end) = (checkpoint.offset(), assembler.offset());
+ let crosses = start / BRANCH_WINDOW != (end - 1) / BRANCH_WINDOW || end.is_multiple_of(BRANCH_WINDOW);
+ if end > start && end - start < BRANCH_WINDOW && crosses {
+ assembler.buffer.rewind(checkpoint);
+ assembler.nops(start.next_multiple_of(BRANCH_WINDOW) - start);
+ emit(self);
+ }
+ self.branch_assembler().in_branch_group = false;
+ }
+}
+
+impl BranchGroups for Assembler {
+ fn branch_assembler(&mut self) -> &mut Assembler {
+ self
+ }
}
impl Assembler {
@@ -845,12 +890,14 @@ impl Assembler {
/// `jcc label`, rel8 when the label is bound and in range, rel32 otherwise.
pub fn jcc(&mut self, cond: Cond, label: Label) {
- if self.backward_rel8_reaches(label, 2) {
- self.jcc_short(cond, label);
- } else {
- self.buffer.emit_bytes(&[0x0f, 0x80 | cond as u8]);
- self.emit_rel32(label);
- }
+ self.branch_group(|a| {
+ if a.backward_rel8_reaches(label, 2) {
+ a.jcc_short(cond, label);
+ } else {
+ a.buffer.emit_bytes(&[0x0f, 0x80 | cond as u8]);
+ a.emit_rel32(label);
+ }
+ });
}
/// `jcc rel8 label`. Fails at bind or finish time if out of range.
@@ -861,12 +908,14 @@ impl Assembler {
/// `jmp label`, rel8 when the label is bound and in range, rel32 otherwise.
pub fn jmp(&mut self, label: Label) {
- if self.backward_rel8_reaches(label, 2) {
- self.jmp_short(label);
- } else {
- self.buffer.emit_u8(0xe9);
- self.emit_rel32(label);
- }
+ self.branch_group(|a| {
+ if a.backward_rel8_reaches(label, 2) {
+ a.jmp_short(label);
+ } else {
+ a.buffer.emit_u8(0xe9);
+ a.emit_rel32(label);
+ }
+ });
}
/// `jmp rel8 label`. Fails at bind or finish time if out of range.
@@ -877,33 +926,45 @@ impl Assembler {
/// `call label` (rel32).
pub fn call(&mut self, label: Label) {
- self.buffer.emit_u8(0xe8);
- self.emit_rel32(label);
+ self.branch_group(|a| {
+ a.buffer.emit_u8(0xe8);
+ a.emit_rel32(label);
+ });
}
/// `call reg`.
pub fn call_r(&mut self, target: Gpr) {
- self.emit_instruction(Prefix::None, false, &[0xff], 2, Rm::Reg(target.0), ByteRegisters::No, 0);
+ self.branch_group(|a| {
+ a.emit_instruction(Prefix::None, false, &[0xff], 2, Rm::Reg(target.0), ByteRegisters::No, 0);
+ });
}
/// `call qword [address]`.
pub fn call_m(&mut self, address: &Address) {
- self.emit_instruction(Prefix::None, false, &[0xff], 2, Rm::Mem(*address), ByteRegisters::No, 0);
+ self.branch_group(|a| {
+ a.emit_instruction(Prefix::None, false, &[0xff], 2, Rm::Mem(*address), ByteRegisters::No, 0);
+ });
}
/// `jmp reg`.
pub fn jmp_r(&mut self, target: Gpr) {
- self.emit_instruction(Prefix::None, false, &[0xff], 4, Rm::Reg(target.0), ByteRegisters::No, 0);
+ self.branch_group(|a| {
+ a.emit_instruction(Prefix::None, false, &[0xff], 4, Rm::Reg(target.0), ByteRegisters::No, 0);
+ });
}
/// `call qword [rip + label]`.
pub fn call_label_indirect(&mut self, label: Label) {
- self.emit_instruction(Prefix::None, false, &[0xff], 2, Rm::Rip(label), ByteRegisters::No, 0);
+ self.branch_group(|a| {
+ a.emit_instruction(Prefix::None, false, &[0xff], 2, Rm::Rip(label), ByteRegisters::No, 0);
+ });
}
/// `jmp qword [address]`.
pub fn jmp_m(&mut self, address: &Address) {
- self.emit_instruction(Prefix::None, false, &[0xff], 4, Rm::Mem(*address), ByteRegisters::No, 0);
+ self.branch_group(|a| {
+ a.emit_instruction(Prefix::None, false, &[0xff], 4, Rm::Mem(*address), ByteRegisters::No, 0);
+ });
}
fn backward_rel8_reaches(&self, label: Label, instruction_size: usize) -> bool {
@@ -935,7 +996,7 @@ impl Assembler {
}
pub fn ret(&mut self) {
- self.buffer.emit_u8(0xc3);
+ self.branch_group(|a| a.buffer.emit_u8(0xc3));
}
pub fn nop(&mut self) {
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/tests.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/tests.rs
index 08538178fd0..0bc4a0d828f 100644
--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/tests.rs
@@ -293,8 +293,9 @@ fn branches_to_labels() {
"ud2" => |a| a.ud2();
});
- // Backward branches just out of rel8 range are near.
+ // Backward branches just out of rel8 range are near. (They start at 32-byte windows, which they stay within.)
let code = bytes(|a| {
+ a.nops(2);
let label = a.new_label();
a.bind(label);
a.nops(126);
@@ -302,8 +303,45 @@ fn branches_to_labels() {
a.nops(1);
a.jcc(Cond::Equal, label);
});
- assert_eq!(&code[126..128], [0xeb, 0x80]);
- assert_eq!(&code[129..135], [0x0f, 0x84, 0x79, 0xff, 0xff, 0xff]);
+ assert_eq!(&code[128..130], [0xeb, 0x80]);
+ assert_eq!(&code[131..137], [0x0f, 0x84, 0x79, 0xff, 0xff, 0xff]);
+}
+
+/// Where each instruction of `code` starts, and what it is.
+fn layout(code: &[u8]) -> Vec<(usize, String)> {
+ disassembler::listing(super::super::Architecture::X86_64, code)
+ .into_iter()
+ .map(|instruction| (instruction.offset, instruction.text))
+ .collect()
+}
+
+#[test]
+fn branches_stay_within_32_byte_windows() {
+ // A branch that would cross the end of a 32-byte window, or end at it, starts the next one.
+ type Emit = fn(&mut Assembler);
+ let cases: [(usize, Emit, &str, usize); 6] = [
+ (29, |a| a.jmp_r(RAX), "jmp rax", 29),
+ (30, |a| a.jmp_r(RAX), "jmp rax", 32),
+ (30, |a| a.ret(), "ret", 30),
+ (31, |a| a.ret(), "ret", 32),
+ (26, |a| a.call_m(&base(RAX, 8)), "call qword ptr [rax+8]", 26),
+ (30, |a| a.call_m(&base(RAX, 8)), "call qword ptr [rax+8]", 32),
+ ];
+ for (offset, emit, text, start) in cases {
+ let code = bytes(|a| {
+ a.nops(offset);
+ emit(a);
+ });
+ let layout = layout(&code);
+ let (branch_start, branch) = layout.last().unwrap();
+ assert_eq!((*branch_start, branch.as_str()), (start, text), "{layout:?}");
+ assert!(
+ layout[..layout.len() - 1]
+ .iter()
+ .all(|(_, text)| text.starts_with("nop") || text == "xchg ax, ax"),
+ "{layout:?}"
+ );
+ }
}
#[test]
@@ -415,6 +453,22 @@ mod macro_assembler {
use super::super::super::PortableMacroAssembler;
use super::*;
+ #[test]
+ fn compares_move_with_the_branches_they_fuse_with() {
+ let mut masm = MacroAssembler::new();
+ let label = masm.new_label();
+ masm.assembler.nops(26);
+ masm.branch32_imm(Condition::Equal, RAX, 1000, label);
+ masm.bind(label);
+ let code = masm.assembler.finish().unwrap();
+ let layout = layout(&code);
+ let tail = layout[layout.len() - 2..]
+ .iter()
+ .map(|(offset, text)| (*offset, text.as_str()))
+ .collect::<Vec<_>>();
+ assert_eq!(tail, [(32, "cmp eax, 0x3e8"), (38, "je 0x2c")], "{layout:?}");
+ }
+
#[test]
fn operations_are_legalized() {
assert_encodings!(MacroAssembler, disassembler::x86_64, {