Truly independent web browser
LibJS/JIT: Concatenate the parts of template literals inline
Andreas Kling57979f1f5f83
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs b/Libraries/LibJS/JIT/Rust/src/builder/checks.rsindex 384fc0a198e..a220d59bad8 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/checks.rs@@ -213,6 +213,7 @@ impl GraphBuilder<'_> {Instruction::GetByValue { .. } => self.build_get_by_value(instruction, info),Instruction::PutByValue { .. } => self.build_put_by_value(instruction, info),Instruction::GetLength { .. } => self.build_get_length(instruction),+ Instruction::ConcatString { dst, src } => self.build_concat_string(instruction, info, dst, src),Instruction::GetById { .. } => self.build_get_by_id(instruction),Instruction::PutById { .. } => self.build_put_by_id(instruction),Instruction::IteratorClose { .. } => self.build_iterator_close(instruction),diff --git a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs b/Libraries/LibJS/JIT/Rust/src/builder/handling.rsindex 950fa6f5832..f2347d326f2 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/handling.rs@@ -305,11 +305,13 @@ pub fn handling(opcode: OpCode) -> Handling {// are int32 values already.O::ToObject | O::ToLength => EXPANDED,+ // Concatenations of strings, and of a string and an integer.+ O::ConcatString => EXPANDED,+// Checks that only throw in their slow path.O::ThrowIfTDZ | O::ThrowIfNotObject | O::ThrowIfNullish | O::ResolveThisBinding => EXPANDED,O::Exp- | O::ConcatString| O::CopyObjectExcludingProperties| O::ImportCall| O::NewClassdiff --git a/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs b/Libraries/LibJS/JIT/Rust/src/builder/speculation.rsindex cb03dfd1e88..53485f7b468 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs@@ -1053,6 +1053,30 @@ impl GraphBuilder<'_> {}}+ /// `ConcatString`: the string in `dst` (which is one) and the string of+ /// `src`, where `src` is a string or an integer whose string the VM has.+ pub(super) fn build_concat_string(+ &mut self,+ instruction: &Instruction,+ info: GenericInfo,+ dst: Operand,+ src: Operand,+ ) -> Result<Flow, CompileFailure> {+ if self.runtime.rope_allocation.allocator == 0 {+ return self.build_generic(instruction, info);+ }+ let (lhs, rhs) = (self.read(dst)?, self.read(src)?);+ let mut paths = self.start_slow_paths(Some(Repr::Tagged))?;+ let (lhs, rhs) = (self.tagged(lhs), self.tagged(rhs));+ let string = self.branch_to_next_case(&mut paths, BranchCondition::String, vec![lhs], true);+ let integers = self.runtime.layout.numeric_string_cache != 0;+ let other = self.string_on_path(&mut paths, rhs, integers);+ self.finish_concatenation(&mut paths, string, other);+ let result = self.join_hot_paths(paths).expect("ConcatString has a value");+ self.write(dst, result)?;+ Ok(Flow::Continue)+ }+/// The string `value` is, or if `integers`, the string of the integer/// it is, where the VM has that: tests send other values on.fn string_on_path(&mut self, paths: &mut SlowPaths, value: NodeId, integers: bool) -> NodeId {diff --git a/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs b/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rsindex 32238071234..ef4ff63b312 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs@@ -44,14 +44,17 @@ use super::facts::Location;use super::facts::ValueKind;use super::facts::elements_kind_implies;use crate::bitset::BitSet;+use crate::bytecode::OpCode;use crate::code::Dependency;use crate::inline_vec::InlineVec;use crate::ir::BlockId;+use crate::ir::BranchCondition;use crate::ir::ElementsKind;use crate::ir::Graph;use crate::ir::NodeId;use crate::ir::Op;use crate::ir::ShapeCheck;+use crate::ir::value;use crate::snapshot::CellId;/// What the analysis decided for the nodes of one visit of the graph.@@ -111,7 +114,7 @@ pub fn run(graph: &mut Graph) {let mut skipped = Vec::new();for block in 0..block_count {let block_id = BlockId::from_index(block);- let Some(facts) = facts_at_entry(graph, block_id, &mut edge_facts, &visited) else {+ let Some(facts) = facts_at_entry(graph, block_id, &mut edge_facts, &visited, &revisited, &decisions) else {// No visited predecessor reaches this block.edge_facts[block].clear();skipped.push(block_id);@@ -170,11 +173,16 @@ pub fn run(graph: &mut Graph) {/// assumed to agree, and checked when the next round sees what they bring./// Roots start knowing nothing, except that the code is valid: invalidated/// code is discarded, so nothing enters it.+///+/// A phi of a block that no back edge leads to is of a kind one of its+/// inputs is, where it comes from.fn facts_at_entry(graph: &Graph,block: BlockId,edge_facts: &mut [Vec<(BlockId, Facts)>],visited: &[bool],+ revisited: &[bool],+ decisions: &Decisions,) -> Option<Facts> {let predecessors = &graph.block(block).predecessors;if predecessors.is_empty() {@@ -192,14 +200,41 @@ fn facts_at_entry(incoming.extend(edges.extract_if(.., |(target, _)| *target == block)- .map(|(_, facts)| facts),+ .map(|(_, facts)| (*predecessor, facts)),);}- match incoming.len() {- 0 => None,- 1 => incoming.pop(),- _ => Some(Facts::merge(incoming.into_iter())),+ let phis = &graph.block(block).phis;+ // NB: Each predecessor brings the facts along its one edge here.+ let knows_phi_inputs = !revisited[block.index()]+ && !phis.is_empty()+ && incoming.len() == predecessors.len()+ && predecessors+ .iter()+ .all(|predecessor| incoming.iter().filter(|(source, _)| source == predecessor).count() == 1);+ if !knows_phi_inputs {+ return match incoming.len() {+ 0 => None,+ 1 => incoming.pop().map(|(_, facts)| facts),+ _ => Some(Facts::merge(incoming.into_iter().map(|(_, facts)| facts))),+ };}+ let mut facts = Facts::merge(incoming.iter().map(|(_, facts)| facts.clone()));+ for phi in phis {+ let inputs = graph+ .node(*phi)+ .inputs+ .iter()+ .zip(predecessors)+ .map(|(input, predecessor)| {+ let (_, facts) = incoming+ .iter()+ .find(|(source, _)| source == predecessor)+ .expect("each predecessor brings facts");+ (facts, decisions.value(graph, *input))+ });+ facts.set_phi_kinds(graph, *phi, inputs);+ }+ Some(facts)}/// Applies the nodes of `block` to `facts`, recording decisions, and returns@@ -268,6 +303,15 @@ fn visit_block(let mut passed = facts.clone();passed.set_branch_outcome(key, true);facts.set_branch_outcome(key, false);+ // Strings that are the empty value where only the slow path makes+ // them are strings where they are not.+ if let BranchCondition::TaggedEquals { equal } = condition+ && graph.constant_value(inputs[1]) == Some(value::EMPTY)+ && matches!(graph.node(inputs[0]).op, Op::ConcatenateStrings | Op::IntegerToString)+ {+ let not_empty = if equal { &mut facts } else { &mut passed };+ not_empty.set_value_kind(inputs[0], ValueKind::String);+ }return vec![(if_true, passed), (if_false, facts)];}}@@ -400,6 +444,15 @@ fn visit_node(}// NB: Values that pass are int32 values.Op::CheckInt32 => facts.set_value_kind(input(0), ValueKind::Int32),+ // NB: ConcatString makes a string, also in its slow path, which may+ // run other code.+ ref op @ Op::CallSlowPath {+ opcode: OpCode::ConcatString,+ ..+ } => {+ facts.apply(&op.properties(), &graph.stable_shapes);+ facts.set_value_kind(node_id, ValueKind::String);+ }Op::CheckPrototypeChainValid { validity } => {remove = facts.is_prototype_chain_valid(validity);facts.set_prototype_chain_valid(validity);diff --git a/Libraries/LibJS/JIT/Rust/src/passes/facts.rs b/Libraries/LibJS/JIT/Rust/src/passes/facts.rsindex 5f558288a62..7096f501156 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/facts.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/facts.rs@@ -393,6 +393,17 @@ impl Facts {self.narrow_kinds(value, Kinds::of(kind));}+ /// Records that the phi `phi` is of a kind one of its inputs is, given+ /// as each input with the facts where it comes from.+ pub fn set_phi_kinds<'a>(&mut self, graph: &Graph, phi: NodeId, inputs: impl Iterator<Item = (&'a Facts, NodeId)>) {+ let kinds = inputs.fold(Kinds(0), |kinds, (facts, input)| {+ kinds.union(facts.kinds_in(graph, input))+ });+ if kinds != Kinds(0) {+ self.narrow_kinds(phi, kinds);+ }+ }+pub fn is_object(&self, value: NodeId) -> bool {self.value_kind(value) == Some(ValueKind::Object)}diff --git a/Tests/LibJS/JIT/ir/template-literals.js b/Tests/LibJS/JIT/ir/template-literals.jsnew file mode 100644index 00000000000..5bf2f3d8e1c--- /dev/null+++ b/Tests/LibJS/JIT/ir/template-literals.js@@ -0,0 +1,32 @@+// REQUIRES: inline-allocation+// A template literal concatenates its strings with the strings of integers the VM has inline, and leaves the rest to+// the slow path, which makes a string too: the length of the result is that of a string, whichever path made it.++function describe(value, count) {+ return `value ${value} of ${count}`.length;+}+jit.prepare(describe);+for (let i = 0; i < 10; ++i) describe(i, 100000);+jit.compile(describe);++// CHECK-FUNCTION: describe+// CHECK-PASS: dead code elimination+// CHECK-COUNT-2: = IntegerToString+// CHECK-COUNT-3: = ConcatenateStrings+// CHECK-COUNT-3: = CallSlowPath ConcatString+// CHECK-COUNT-1: = StringLength+// CHECK-COUNT-0: BranchObject++// The slow path may call a toString() that changes any object, so a property loaded before it is loaded again after.+function reread(o, s) {+ const text = `${s}${o.x}${o.value}`;+ return o.x + text.length;+}+const o = { x: 1, value: 5 };+jit.prepare(reread);+for (let i = 0; i < 10; ++i) reread(o, "s");+jit.compile(reread);++// CHECK-FUNCTION: reread+// CHECK-PASS: dead code elimination+// CHECK-COUNT-2: = LoadNamed +0diff --git a/Tests/LibJS/Runtime/template-literals.js b/Tests/LibJS/Runtime/template-literals.jsindex d70ceb985fd..4c682cd76d9 100644--- a/Tests/LibJS/Runtime/template-literals.js+++ b/Tests/LibJS/Runtime/template-literals.js@@ -32,6 +32,56 @@ test("expressions at beginning of template literal", () => {expect(`${"foo bar baz"}`).toBe("foo bar baz");});+test("expressions of every kind, many times over", () => {+ const object = { toString: () => "an object" };+ const values = [+ 0,+ 7,+ 999,+ 1000,+ 100000,+ -1,+ -2147483648,+ 2147483647,+ 1.5,+ -0,+ NaN,+ "",+ "x",+ "a longer string than most",+ ];+ values.push(true, null, undefined, 10n, object, [1, 2]);+ const describe = value => `value ${value} of ${values.length}`;+ for (let i = 0; i < 100; ++i) {+ for (const value of values) {+ const expected = "value " + String(value) + " of 20";+ expect(describe(value)).toBe(expected);+ expect(describe(value).length).toBe(expected.length);+ }+ expect(`${""}${""}`).toBe("");+ expect(() => describe(Symbol())).toThrow(TypeError);+ }+});++test("toString() of a substitution changing what the template literal read before", () => {+ const object = { x: 1, value: 5 };+ const bump = {+ toString() {+ object.x++;+ return "bumped";+ },+ };+ const read = (object, prefix) => {+ const text = `${prefix}${object.x}${object.value}`;+ return object.x;+ };+ for (let i = 0; i < 1000; ++i) {+ object.value = i % 2 ? bump : i;+ const expected = object.x + (i % 2);+ expect(read(object, "prefix")).toBe(expected);+ }+});+test("multiple template literals", () => {expect(`foo ${"bar"} ${"baz"}`).toBe("foo bar baz");});