Truly independent web browser
LibJS/JIT: Exit instead of rejoining slow paths of Math builtins
Andreas Klingdc0cabd93bfb
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs b/Libraries/LibJS/JIT/Rust/src/builder/checks.rsindex 6b2a955d63f..212312f4e19 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/checks.rs@@ -328,9 +328,19 @@ impl GraphBuilder<'_> {hot: Vec::new(),cold: Vec::new(),next_case: Vec::new(),+ exits: false,})}+ /// Makes the cold edges of `slow_paths` exit to the interpreter instead of+ /// running the instruction's slow path, unless such an exit was taken there+ /// before. The code after the instruction then joins no path that ran+ /// other code, so it keeps what it knew before the instruction. For+ /// instructions whose slow path only handles rare cases.+ pub(super) fn exit_instead_of_slow_path(&mut self, slow_paths: &mut SlowPaths) {+ slow_paths.exits = self.may_speculate(ExitKind::SlowPath);+ }+/// Ends the current block with a branch on `condition` of `inputs`,/// which continues in a new block where the condition is/// `continue_when`, and takes a cold edge of `slow_paths` to the@@ -583,6 +593,19 @@ impl GraphBuilder<'_> {/// edge they took jumps to, with the operands the slow path wrote, if/// any edge was taken.fn build_slow_path(&mut self, slow_paths: &SlowPaths) -> Option<(BlockId, Vec<NodeId>)> {+ if slow_paths.exits {+ for edge in &slow_paths.cold {+ self.block = *edge;+ let exit = self.set_control(+ Op::Exit {+ kind: ExitKind::SlowPath,+ },+ Vec::new(),+ );+ self.graph.nodes[exit.index()].frame_state = Some(slow_paths.frame_state);+ }+ return None;+ }let slow = match slow_paths.cold.as_slice() {[] => return None,[edge] => *edge,@@ -621,6 +644,9 @@ pub(in crate::builder) struct SlowPaths {/// The edges that `GraphBuilder::branch_to_next_case()` took since the/// last case started.next_case: Vec<BlockId>,+ /// Whether the cold edges exit instead (see+ /// `GraphBuilder::exit_instead_of_slow_path()`).+ exits: bool,}impl SlowPaths {diff --git a/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs b/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rsindex 6114b20bd97..82f5c193da8 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs@@ -46,7 +46,8 @@ const MAX_MIN_MAX_ARGUMENTS: usize = 8;impl GraphBuilder<'_> {/// Builds `Math.<op>(argument)`, a `CallBuiltinMath*` instruction, for/// numbers, if `callee` is the builtin of any realm. The instruction's- /// slow path, which calls the callee, handles everything else.+ /// slow path, which calls the callee, handles everything else, or the code+ /// exits there where that did not happen before.pub(super) fn build_math_function(&mut self,op: Float64UnaryOp,@@ -66,6 +67,7 @@ impl GraphBuilder<'_> {let callee = self.read(callee)?;let argument = self.read(argument)?;let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;+ self.exit_instead_of_slow_path(&mut slow_paths);self.branch_to_slow_path(&mut slow_paths, BranchCondition::Builtin(builtin), vec![callee], true);let result = if let Some(integer) = self.int32_value_of(argument) {self.build_int32_math_function(&mut slow_paths, op, integer)diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rsindex feaf104aa1f..2ae556a4f37 100644--- a/Libraries/LibJS/JIT/Rust/src/code.rs+++ b/Libraries/LibJS/JIT/Rust/src/code.rs@@ -87,9 +87,11 @@ pub enum ExitKind {/// compile time (a method on a prototype, the key of a keyed access)/// was another value.UnexpectedValue,- /// An instruction whose slow path cannot run from compiled code met a- /// case only its slow path handles (like an append that needs to grow- /// an array, or a probe that cannot tell), so the interpreter runs it.+ /// An instruction whose slow path cannot run from compiled code, or that+ /// was compiled to exit instead of running its slow path, met a case only+ /// its slow path handles (like an append that needs to grow an array, a+ /// probe that cannot tell, or `Math.abs` of a string), so the+ /// interpreter runs it.SlowPath,/// An `arguments[i]` the compiled code read from the frame's arguments/// had an index that is not an int32 within the passed arguments.diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rsindex e13e858a5dc..270f3b25710 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs@@ -3256,7 +3256,8 @@ fn math_builtin_calls() {(12, js_round),(13, f64::sqrt),];- let call = |builtin: u8, callee: u64, argument_value: u64| {+ // NB: Where the code exited before, it calls the slow path instead.+ let call_with = |builtin: u8, callee: u64, argument_value: u64, exited: bool| {let instruction = match builtin {9 => Instruction::CallBuiltinMathAbs {call_feedback: 0,@@ -3306,8 +3307,20 @@ fn math_builtin_calls() {Instruction::Return { value: r(5) },]});- let (result, _) =- run_program_with_snapshot(&program, &[callee, argument_value, value::UNDEFINED], |_| {}, |_| {});+ let pc = program.offsets[1];+ let (result, _) = run_program_with_snapshot(+ &program,+ &[callee, argument_value, value::UNDEFINED],+ |snapshot| {+ if exited {+ snapshot.executables[0].exit_sites = vec![(pc, ExitKind::SlowPath), (pc, ExitKind::Overflow)];+ }+ },+ |_| {},+ );+ if result.status == crate::code::JitStatus::Resume as u64 {+ return EXITED;+ }assert_eq!(result.status, RETURNED);result.value};@@ -3343,34 +3356,42 @@ fn math_builtin_calls() {let integers = [0, 1, -1, 5, -7, i32::MAX, i32::MIN];for (builtin, reference) in functions {let callee = fake_function(Some(builtin));- for number in numbers {- let expected = box_number(reference(number));- assert_eq!(- call(builtin, callee, number.to_bits()),- expected,- "builtin {builtin} of {number:?}"- );- }- for integer in integers {- // NB: The absolute value of the smallest int32 is no int32; the- // slow path makes it.- let expected = if builtin == 9 && integer == i32::MIN {- MARKER- } else {- box_number(reference(f64::from(integer)))- };+ // NB: Before any exit at the site, the cases the slow path handles+ // exit instead.+ for exited in [true, false] {+ let slow = if exited { MARKER } else { EXITED };+ for number in numbers {+ let expected = box_number(reference(number));+ assert_eq!(+ call_with(builtin, callee, number.to_bits(), exited),+ expected,+ "builtin {builtin} of {number:?}"+ );+ }+ for integer in integers {+ // NB: The absolute value of the smallest int32 is no int32;+ // the slow path makes it.+ let expected = if builtin == 9 && integer == i32::MIN {+ slow+ } else {+ box_number(reference(f64::from(integer)))+ };+ assert_eq!(+ call_with(builtin, callee, value::int32(integer), exited),+ expected,+ "builtin {builtin} of {integer}"+ );+ }+ // Other callees and arguments take the slow path.assert_eq!(- call(builtin, callee, value::int32(integer)),- expected,- "builtin {builtin} of {integer}"+ call_with(builtin, fake_function(Some(builtin + 1)), value::int32(1), exited),+ slow);+ assert_eq!(call_with(builtin, fake_function(None), value::int32(1), exited), slow);+ assert_eq!(call_with(builtin, value::UNDEFINED, value::int32(1), exited), slow);+ assert_eq!(call_with(builtin, callee, value::UNDEFINED, exited), slow);+ assert_eq!(call_with(builtin, callee, value::TRUE, exited), slow);}- // Other callees and arguments take the slow path.- assert_eq!(call(builtin, fake_function(Some(builtin + 1)), value::int32(1)), MARKER);- assert_eq!(call(builtin, fake_function(None), value::int32(1)), MARKER);- assert_eq!(call(builtin, value::UNDEFINED, value::int32(1)), MARKER);- assert_eq!(call(builtin, callee, value::UNDEFINED), MARKER);- assert_eq!(call(builtin, callee, value::TRUE), MARKER);}}diff --git a/Tests/LibJS/JIT/ir/math-and-string-builtins.js b/Tests/LibJS/JIT/ir/math-and-string-builtins.jsindex 7c189b88022..61b362fad18 100644--- a/Tests/LibJS/JIT/ir/math-and-string-builtins.js+++ b/Tests/LibJS/JIT/ir/math-and-string-builtins.js@@ -1,7 +1,7 @@// Calls of Math functions of one number and of charCodeAt and charAt are-// built as IR: branches on the callee and the operands go to a cold block that-// calls the instruction's slow path, and the common case computes the result-// in IR.+// built as IR: the common case computes the result in IR, and branches on the+// callee and the operands go to a cold block. Math functions exit there,+// unless that happened at the site before.function floorPlusAbs(x) {return Math.floor(x) + Math.abs(x);@@ -17,7 +17,7 @@ jit.compile(floorPlusAbs);// CHECK-NEXT: RefineBuiltin {{[0-9]+}} ([[FLOOR]])// CHECK-NEXT: BranchInt32Value ([[X:v[0-9]+]]) -> [[INT32:b[0-9]+]], [[OTHER:b[0-9]+]]// CHECK: [[COLD]] <- {{b[0-9]+}} cold:-// CHECK-NEXT: Jump [[SLOW:b[0-9]+]]+// CHECK-NEXT: Exit SlowPath// CHECK: [[INT32]] <- {{b[0-9]+}}:// CHECK-NEXT: [[INTEGER:v[0-9]+]] = RefineInt32Value ([[X]])// CHECK-NEXT: UnboxInt32 ([[INTEGER]])@@ -27,9 +27,29 @@ jit.compile(floorPlusAbs);// CHECK-NEXT: [[NUMBER:v[0-9]+]]:float64 = UnboxDouble ([[REFINED]])// CHECK-NEXT: [[FLOORED:v[0-9]+]]:float64 = Float64Floor ([[NUMBER]])// CHECK-NEXT: BoxFloat64 ([[FLOORED]])-// CHECK: [[SLOW]] <- {{b[0-9]+}}, {{b[0-9]+}} cold:-// CHECK-NEXT: CallSlowPath CallBuiltinMathFloor {{@[0-9]+}} ([[FLOOR]], {{[^)]*}}[[X]])// CHECK: Float64Abs+// CHECK-NOT: CallSlowPath++// A site that exited calls the slow path instead.++function floorOf(x) {+ return Math.floor(x);+}+jit.prepare(floorOf);+for (let i = 0; i < 10; ++i) floorOf(i + 0.5);+jit.compile(floorOf);+floorOf("1.5");+jit.discard(floorOf);+jit.compile(floorOf);++// CHECK-FUNCTION: floorOf+// CHECK-PASS: graph building+// CHECK: BranchDouble ({{v[0-9]+}}) -> {{b[0-9]+}}, [[COLD:b[0-9]+]]+// CHECK: [[COLD]] <- {{b[0-9]+}} cold:+// CHECK-NEXT: Jump [[SLOW:b[0-9]+]]+// CHECK: [[SLOW]] <- {{b[0-9]+}}, {{b[0-9]+}} cold:+// CHECK-NEXT: CallSlowPath CallBuiltinMathFloor+// CHECK-NOT: Exit SlowPathfunction characters(s, i) {return s.charCodeAt(i) + s.charAt(i).length;@@ -59,11 +79,11 @@ jit.compile(characters);// CHECK: [[ASCII:v[0-9]+]]:int32 = RefineInt32LessThan ([[CHARACTER]], #i32:128)// CHECK-NEXT: SingleCharacterString ([[ASCII]])-console.log(floorPlusAbs(-2.5), characters("abc", 1), characters("abc", 9));+console.log(floorPlusAbs(-2.5), floorOf(-2.5), characters("abc", 1), characters("abc", 9));// Int32 arguments take int32 paths: the absolute value of an int32 is one-// (but for the smallest, which goes to the slow path), and its square root-// is that of its double.+// (but for the smallest, which exits), and its square root is that of its+// double.function absAndSqrt(n) {const i = n | 0;