Skip to content

Truly independent web browser

LibJS: Inline method calls on objects of shapes the JIT knows

Andreas Kling66aa13c7dbb0
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs b/Libraries/LibJS/JIT/Rust/src/builder/caches.rs
index b3e14d5514b..da04b0c578f 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/caches.rs
@@ -86,6 +86,9 @@ pub(super) struct CacheEntry {
/// For `Get`s from a prototype: the object the property held at compile
/// time, if it held one, and which intrinsic that is.
pub prototype_property: Option<(CellId, Option<Intrinsic>)>,
+ /// The snapshot executable of the function `prototype_property` holds,
+ /// if calls of it may be inlined.
+ pub prototype_property_inline_executable: Option<u32>,
}
impl CacheEntry {
@@ -159,6 +162,7 @@ impl CacheEntry {
prototype_property: entry
.prototype_property
.map(|cell| (cell, entry.prototype_property_intrinsic)),
+ prototype_property_inline_executable: entry.prototype_property_inline_executable,
})
}
@@ -231,11 +235,26 @@ impl GraphBuilder<'_> {
entries: &[CacheEntry],
apply: impl FnMut(&mut Self, &CacheEntry, NodeId) -> Option<NodeId>,
) -> Option<NodeId> {
+ let entries = self.entries_for_known_shape(object, entries);
let shapes = entries.iter().map(|entry| self.shape_guard(entry)).collect::<Vec<_>>();
let one_action = entries.iter().all(|entry| entry.action == entries[0].action);
self.dispatch_on_shapes(object, entries, &shapes, one_action, apply)
}
+ /// The entries that apply to `object`: only the one for its shape, where
+ /// the code allocated it and knows the shape it has now (see
+ /// `AbstractFrame::fresh_shapes`), which needs no shape switch. Its shape
+ /// is still checked, which check elimination removes where it can tell.
+ pub(super) fn entries_for_known_shape<'e>(&self, object: NodeId, entries: &'e [CacheEntry]) -> &'e [CacheEntry] {
+ let Some(shape) = self.fresh_shape(object) else {
+ return entries;
+ };
+ entries
+ .iter()
+ .position(|entry| entry.shape.shape == shape)
+ .map_or(entries, |index| &entries[index..=index])
+ }
+
/// Checks that `object` has one of `shapes` and applies the action of
/// the first entry if `one_action`, or switches on the shapes to the
/// action of each entry otherwise. The actions get the object refined
@@ -286,6 +305,7 @@ impl GraphBuilder<'_> {
let join = self.graph.add_block(Block::default());
let mut results = Vec::new();
+ let mut case_shapes = Vec::with_capacity(cases.len());
for (index, (shape, block)) in cases.iter().enumerate() {
self.block = *block;
self.frame = frame.clone();
@@ -294,10 +314,13 @@ impl GraphBuilder<'_> {
debug_assert_eq!(self.frame.slots, frame.slots, "cases do not change frame slots");
self.set_control(Op::Jump { target: join }, Vec::new());
self.graph.blocks[join.index()].predecessors.push(self.block);
+ case_shapes.push(std::mem::take(&mut self.frame.fresh_shapes));
}
self.order.push(join);
self.block = join;
self.frame = frame;
+ // NB: Cases may change shapes, like additions do.
+ self.frame.fresh_shapes = super::AbstractFrame::common_fresh_shapes(case_shapes.iter().map(Vec::as_slice));
let results = results.into_iter().collect::<Option<Vec<_>>>()?;
if results.iter().all(|result| *result == results[0]) {
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
index c14c02b7622..a728f300657 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
@@ -87,6 +87,9 @@ pub(super) struct InlineCall {
/// The values returned, one per predecessor of the continuation, with
/// what was known at each return.
pub returns: Vec<NodeId>,
+ /// The shapes every return knew objects have (see
+ /// `AbstractFrame::fresh_shapes`), once the first return is built.
+ pub return_fresh_shapes: Option<Vec<(NodeId, CellId)>>,
/// Interpreter stack bytes of this callee's frame and those of the
/// inlined calls it is in.
pub frame_bytes: u64,
@@ -632,6 +635,11 @@ impl GraphBuilder<'_> {
};
return self.inline_call(call);
}
+ if feedback.forwarded.is_none()
+ && let Some(flow) = self.try_inline_constant_callee(instruction)?
+ {
+ return Ok(Some(flow));
+ }
let Some(forwarded) = feedback.forwarded else {
return Ok(None);
};
@@ -710,6 +718,57 @@ impl GraphBuilder<'_> {
self.inline_call(call)
}
+ /// Inlines a `Call` of a function the code holds as a constant, which
+ /// needs no feedback: called itself (`f(...)`), or through
+ /// `Function.prototype.call` (`f.call(this_arg, ...)`). Sites that call
+ /// several functions, like a method of a constructor every class shares,
+ /// call one of them where the code knows which. Returns `None`, having
+ /// built nothing that matters, if it does not.
+ fn try_inline_constant_callee(&mut self, instruction: &Instruction) -> Result<Option<Flow>, CompileFailure> {
+ let Instruction::Call {
+ dst,
+ callee,
+ this_value,
+ argument_count,
+ arguments,
+ ..
+ } = instruction
+ else {
+ return Ok(None);
+ };
+ if let Some(index) = self.constant_inlinable_function(*callee) {
+ let call = InlinedCallSite::new(
+ index,
+ InlineValue::Operand(*this_value),
+ arguments.iter().copied().map(InlineValue::Operand).collect(),
+ *argument_count,
+ *dst,
+ );
+ return self.inline_call(call);
+ }
+ let Some(index) = self.constant_inlinable_function(*this_value) else {
+ return Ok(None);
+ };
+ if self.constant_intrinsic(*callee) != Some(Intrinsic::FunctionPrototypeCall) {
+ return Ok(None);
+ }
+ let call = InlinedCallSite {
+ forwarded: true,
+ ..InlinedCallSite::new(
+ index,
+ arguments
+ .first()
+ .map_or(InlineValue::Constant(value::UNDEFINED), |this| {
+ InlineValue::Operand(*this)
+ }),
+ arguments.iter().skip(1).copied().map(InlineValue::Operand).collect(),
+ argument_count.saturating_sub(1),
+ *dst,
+ )
+ };
+ self.inline_call(call)
+ }
+
/// Inlines the call of the getter whose executable is snapshot executable
/// `index` with `this` as its `this`, into `dst`, for a `GetById` that
/// checked that it calls that getter, or with `getter`, the function it
@@ -1064,6 +1123,7 @@ impl GraphBuilder<'_> {
let callee_frame = AbstractFrame {
slots,
fields: Default::default(),
+ fresh_shapes: self.frame.fresh_shapes.clone(),
};
callee_function.inline = Some(InlineCall {
caller_frame_state,
@@ -1083,6 +1143,7 @@ impl GraphBuilder<'_> {
},
continuation: None,
returns: Vec::new(),
+ return_fresh_shapes: None,
frame_bytes,
construct: construct.is_some(),
});
@@ -1107,6 +1168,7 @@ impl GraphBuilder<'_> {
self.order.push(continuation);
self.block = continuation;
self.frame = call.caller_frame;
+ self.frame.fresh_shapes = call.return_fresh_shapes.unwrap_or_default();
let values = call.returns;
let result = if values.iter().all(|value| *value == values[0]) {
values[0]
@@ -1151,12 +1213,13 @@ impl GraphBuilder<'_> {
continuation
}
};
- self.function
- .inline
- .as_mut()
- .expect("returns from inlined callees")
- .returns
- .push(value);
+ let call = self.function.inline.as_mut().expect("returns from inlined callees");
+ call.returns.push(value);
+ let fresh_shapes = &self.frame.fresh_shapes;
+ match &mut call.return_fresh_shapes {
+ Some(shapes) => shapes.retain(|shape| fresh_shapes.contains(shape)),
+ None => call.return_fresh_shapes = Some(fresh_shapes.clone()),
+ }
self.set_control(Op::Jump { target: continuation }, Vec::new());
self.graph.blocks[continuation.index()].predecessors.push(self.block);
Flow::Ended
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
index 8e8284f9bd4..9db8a510efb 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
@@ -88,11 +88,13 @@ use crate::ir::BranchCondition;
use crate::ir::FrameField;
use crate::ir::FrameStateId;
use crate::ir::Graph;
+use crate::ir::Locations;
use crate::ir::Node;
use crate::ir::NodeId;
use crate::ir::Op;
use crate::ir::value;
use crate::snapshot::CallFeedbackSnapshot;
+use crate::snapshot::CellId;
use crate::snapshot::ExecutableSnapshot;
use crate::snapshot::Intrinsic;
use crate::snapshot::RuntimeInfo;
@@ -167,6 +169,10 @@ enum SlotState {
Value { node: NodeId, in_sync: bool },
}
+/// How many allocated objects the graph builder knows the shapes of at once
+/// (see `AbstractFrame::fresh_shapes`).
+const MAX_FRESH_SHAPES: usize = 16;
+
/// The builder's view of the frame's registers, locals and arguments,
/// indexed by `FrameLayout::tracked_index()`, and of the fields of its
/// execution context.
@@ -177,6 +183,10 @@ struct AbstractFrame {
/// the field holds on this path, once loaded or set (see
/// `GraphBuilder::frame_field()`).
fields: [Option<NodeId>; FrameField::ALL.len()],
+ /// The shapes of objects the code allocated, by their allocation nodes,
+ /// as far as this path knows them: each object's shape since its last
+ /// addition, until something runs that may change shapes otherwise.
+ fresh_shapes: Vec<(NodeId, CellId)>,
}
impl AbstractFrame {
@@ -186,6 +196,7 @@ impl AbstractFrame {
Self {
slots: vec![SlotState::InMemory; slot_count],
fields: [None; FrameField::ALL.len()],
+ fresh_shapes: Vec::new(),
}
}
@@ -197,6 +208,19 @@ impl AbstractFrame {
self.fields[field as usize] = Some(value);
}
+ /// The shapes every one of `frames` (their `fresh_shapes`) knows its
+ /// objects have.
+ fn common_fresh_shapes<'f>(mut frames: impl Iterator<Item = &'f [(NodeId, CellId)]>) -> Vec<(NodeId, CellId)> {
+ let Some(first) = frames.next() else {
+ return Vec::new();
+ };
+ let mut shapes = first.to_vec();
+ for other in frames {
+ shapes.retain(|shape| other.contains(shape));
+ }
+ shapes
+ }
+
/// Forgets the environments, which an instruction may change.
fn forget_environments(&mut self) {
for field in FrameField::ALL.into_iter().filter(|field| field.is_environment()) {
@@ -491,6 +515,9 @@ struct GraphBuilder<'a> {
build_osr_entries: bool,
/// The intrinsics among the constants, by value.
intrinsics: HashMap<u64, Intrinsic>,
+ /// The functions among the constants that calls may inline, by value:
+ /// their indices in `Snapshot::executables`.
+ inlinable_functions: HashMap<u64, u32>,
/// How `instanceof` runs with the functions the code uses as constants
/// on its right-hand side (see `GlobalValueSnapshot::has_instance`), by
/// their bits.
@@ -536,6 +563,7 @@ impl<'a> GraphBuilder<'a> {
virtualize_arguments,
build_osr_entries,
intrinsics: HashMap::default(),
+ inlinable_functions: HashMap::default(),
has_instance: HashMap::default(),
})
}
@@ -705,6 +733,11 @@ impl<'a> GraphBuilder<'a> {
.loop_index
.is_some_and(|loop_index| self.function.loops_replacing_environments[loop_index]);
let osr_loop_header = self.function.osr_loop_headers[block_index];
+ // NB: Loops may change the shapes their headers would know.
+ if !is_loop_header {
+ merged.fresh_shapes =
+ AbstractFrame::common_fresh_shapes(incoming.iter().map(|(_, frame)| frame.fresh_shapes.as_slice()));
+ }
for field in FrameField::ALL {
let first = incoming.first().and_then(|(_, frame)| frame.field(field));
if let Some(value) = first
@@ -1007,9 +1040,48 @@ impl<'a> GraphBuilder<'a> {
debug_assert!(!op.is_control());
let node = self.graph.add_node(Node::new(op, inputs, repr, self.function.pc));
self.graph.blocks[self.block.index()].body.push(node);
+ self.note_shape_changes(node);
node
}
+ /// Updates the shapes the frame knows objects have (see
+ /// `AbstractFrame::fresh_shapes`) for the effects of `node`.
+ fn note_shape_changes(&mut self, node: NodeId) {
+ let node_data = self.graph.node(node);
+ match node_data.op {
+ Op::AllocateObject { shape, .. } => {
+ // NB: Only the latest allocations are worth knowing, and the
+ // frames that copy their shapes stay small.
+ if self.frame.fresh_shapes.len() == MAX_FRESH_SHAPES {
+ self.frame.fresh_shapes.remove(0);
+ }
+ self.frame.fresh_shapes.push((node, shape));
+ }
+ Op::AddNamed { shape, .. } => {
+ let object = self.graph.unrefined(node_data.inputs[0]);
+ self.frame.fresh_shapes.retain(|(known, _)| *known != object);
+ self.frame.fresh_shapes.push((object, shape));
+ }
+ ref op => {
+ let properties = op.properties();
+ if properties.runs_code || properties.writes.intersects(Locations::SHAPES) {
+ self.frame.fresh_shapes.clear();
+ }
+ }
+ }
+ }
+
+ /// The shape the frame knows `object` has, if it is an object the code
+ /// allocated.
+ fn fresh_shape(&self, object: NodeId) -> Option<CellId> {
+ let object = self.graph.unrefined(object);
+ self.frame
+ .fresh_shapes
+ .iter()
+ .find(|(known, _)| *known == object)
+ .map(|(_, shape)| *shape)
+ }
+
fn set_control(&mut self, op: Op, inputs: Vec<NodeId>) -> NodeId {
debug_assert!(op.is_control());
let node = self.graph.add_node(Node::new(op, inputs, None, self.function.pc));
@@ -1101,6 +1173,16 @@ impl<'a> GraphBuilder<'a> {
self.intrinsics.get(&bits).copied()
}
+ /// The snapshot executable of the function an operand holds as a
+ /// constant, if calls of it may be inlined.
+ fn constant_inlinable_function(&self, operand: Operand) -> Option<u32> {
+ let SlotState::Value { node, .. } = self.peek(operand) else {
+ return None;
+ };
+ let bits = self.graph.constant_value(node)?;
+ self.inlinable_functions.get(&bits).copied()
+ }
+
/// The feedback a call instruction recorded in its feedback slot `slot`.
fn call_feedback(&self, slot: u16) -> Option<CallFeedbackSnapshot> {
self.function.executable.feedback.call.get(usize::from(slot)).copied()
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs b/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs
index 6530b91420c..599740a3acb 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs
@@ -91,8 +91,15 @@ impl GraphBuilder<'_> {
node
}
- /// `value`, refined: known to be an object, or the code exits.
+ /// `value`, refined: known to be an object, or the code exits. Objects
+ /// the code allocated need no check.
pub(super) fn check_object(&mut self, value: NodeId) -> NodeId {
+ if matches!(
+ self.graph.node(self.graph.unrefined(value)).op,
+ Op::AllocateObject { .. } | Op::AllocateArray { .. } | Op::AllocateFunction { .. }
+ ) {
+ return value;
+ }
self.emit_checked(Op::CheckObject, vec![value], None)
}
@@ -171,10 +178,13 @@ impl GraphBuilder<'_> {
let holder = self.constant(holder);
match entry.prototype_property {
Some((expected, intrinsic)) if self.may_speculate(ExitKind::UnexpectedValue) => {
+ let bits = self.boxed_object(expected);
if let Some(intrinsic) = intrinsic {
- let bits = self.boxed_object(expected);
self.intrinsics.insert(bits, intrinsic);
}
+ if let Some(index) = entry.prototype_property_inline_executable {
+ self.inlinable_functions.insert(bits, index);
+ }
self.load_constant_named(holder, offset, expected)
}
_ => self.load_named(holder, offset),
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/property_additions.rs b/Libraries/LibJS/JIT/Rust/src/builder/property_additions.rs
index b8e5cce3ee6..7e2615989b2 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/property_additions.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/property_additions.rs
@@ -66,11 +66,12 @@ impl GraphBuilder<'_> {
return Ok(false);
};
let object = self.read(base)?;
+ let allocation = self.graph.unrefined(object);
let Op::AllocateObject {
shape: allocated_shape,
property_count,
reserve,
- } = self.graph.node(object).op
+ } = self.graph.node(allocation).op
else {
return Ok(false);
};
@@ -80,10 +81,11 @@ impl GraphBuilder<'_> {
}
let value = self.read(src)?;
+ let entries = self.entries_for_known_shape(object, &entries);
let shapes = entries.iter().map(|entry| entry.shape).collect::<Vec<_>>();
self.dispatch_on_shapes(
object,
- &entries,
+ entries,
&shapes,
entries.len() == 1,
|builder, entry, object| {
@@ -114,7 +116,7 @@ impl GraphBuilder<'_> {
None
},
);
- self.graph.nodes[object.index()].op = Op::AllocateObject {
+ self.graph.nodes[allocation.index()].op = Op::AllocateObject {
shape: allocated_shape,
property_count,
reserve,
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
index 9412bf40f6f..996e1e6e9a5 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
@@ -838,6 +838,7 @@ pub(crate) mod property_access {
key_value: 0,
prototype_property: None,
prototype_property_intrinsic: None,
+ prototype_property_inline_executable: None,
accessor_function: None,
holds_accessor: false,
}
diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
index 07a8d0f1a28..f7b99c6d137 100644
--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs
+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
@@ -644,6 +644,10 @@ pub struct PropertyCacheEntrySnapshot {
/// Which intrinsic `prototype_property` is, if it is one the compiler
/// knows.
pub prototype_property_intrinsic: Option<Intrinsic>,
+ /// The executable of `prototype_property` as an inlining candidate, if
+ /// it is a function JIT code may inline: code that calls the property's
+ /// value as a constant can inline the call without feedback for it.
+ pub prototype_property_inline_executable: Option<u32>,
/// The function of the accessor the access calls: for `GetPropertyInPrototypeChain` entries, the getter of the
/// accessor `prototype` held in the property when the snapshot was
/// taken, for `ChangePropertyInPrototypeChain` entries its setter, and
diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rs
index 755aa0bae0d..579f4f70c51 100644
--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs
+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs
@@ -428,6 +428,9 @@ impl SnapshotBuilder<'_> {
self.vm,
prototype_property.map(|object| Value::from_object(object).as_cell()),
),
+ prototype_property_inline_executable: prototype_property.and_then(|object| {
+ self.inline_executable_index(Some(Value::from_object(object).as_cell()), caller)
+ }),
accessor_function,
holds_accessor: entry_holds_accessor(slot),
});
diff --git a/Tests/LibJS/JIT/ir/known-shape-method-inlining.js b/Tests/LibJS/JIT/ir/known-shape-method-inlining.js
new file mode 100644
index 00000000000..5a77d1a299c
--- /dev/null
+++ b/Tests/LibJS/JIT/ir/known-shape-method-inlining.js
@@ -0,0 +1,30 @@
+// REQUIRES: inline-allocation
+// The graph builder knows the shape of an object it allocated, so a method call on it reads the method of that shape
+// as a constant and inlines the call, though the call site saw several methods of several shapes.
+
+function A() {}
+A.prototype.value = function () {
+ return 1;
+};
+function B() {}
+B.prototype.value = function () {
+ return 2;
+};
+function invoke(object) {
+ return object.value();
+}
+function make() {
+ return invoke(new A());
+}
+jit.prepare(make);
+for (let i = 0; i < 10; ++i) {
+ invoke(new B());
+ make();
+}
+jit.compile(make);
+
+// CHECK-FUNCTION: make
+// CHECK-PASS: graph building
+// CHECK-NOT: ShapeSwitch
+// CHECK-NOT: CallSlowPath
+// CHECK: Return