Skip to content

Truly independent web browser

32.0 KB
Raw Blame
/*
 * Copyright (c) 2026-present, the Ladybird developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

//! Escape analysis and scalar replacement of allocations.
//!
//! An object an `AllocateObject` makes, or a closure an `AllocateFunction`
//! makes, escapes when anything could see it
//! besides accesses of its named properties: when it is stored into the
//! frame or into an object that escapes, passed to anything but property
//! accesses and checks (an operand of a slow path or a call included),
//! passed to an inlined call whose legacy `arguments` code it runs can read
//! where no `AssumeLegacyArgumentsUnread` follows, or where code read them
//! before (`ExitKind::LegacyArgumentsRead`), or merged in a phi. An object
//! that does not escape is never allocated: its properties become SSA
//! values, initialized to `undefined`. Stores update them, loads become the
//! value stored last, checks of the object (whose shape is known) go away,
//! and where paths merge, phis merge the values.
//!
//! Frame states only reach the frame when compiled code leaves: at exits,
//! and when slow paths and calls do not continue in compiled code (see
//! `SiteKind::Leave`). Frame states that need the object refer to an
//! `Op::VirtualObject` with the values its properties have there, and the
//! runtime creates it then. So does code that reads it through legacy
//! `arguments`, after which compiled code leaves at the next
//! `AssumeLegacyArgumentsUnread` (see that).
//!
//! Values stored into an object that does not escape do not escape by being
//! stored there, so nested objects (an options bag holding a location
//! object, say) go away together. But where paths merge the property that
//! holds one in a phi, the object escapes and the pass starts over: a phi
//! of objects that are never allocated cannot be the value of a property
//! of a virtual object.
//!
//! A closure escapes when anything but a frame state refers to it: the frame
//! of an inlined call of it, which has its environments as the inputs of the
//! `AllocateFunction` (see `GraphBuilder::frame_field()`), needs no more. It
//! escapes where frame states that refer to it are published with their
//! headers too (see `codegen::lowering_info::LoweringInfo::publishes_frames`),
//! since only the runtime could write them, every time. Calls without the
//! frames of inlined calls (see `Op::CallDirect`) leave those frames to stack
//! walks, which would show a closure created for them as the legacy caller
//! of the callee, so closures that would be one escape at those too.

use super::edit;
use super::edit::Constants;
use super::edit::Replacements;
use crate::code::ExitKind;
use crate::code::Repr;
use crate::codegen::lowering_info::lowering_info;
use crate::ir::Block;
use crate::ir::BlockId;
use crate::ir::FrameState;
use crate::ir::FrameStateId;
use crate::ir::Graph;
use crate::ir::NodeId;
use crate::ir::Op;
use crate::ir::VirtualObjectKind;
use crate::ir::value;
use crate::snapshot::CellId;
use ak::Zone;
use ak::ZoneBitSet;
use ak::ZoneMap;
use ak::ZoneSet;
use ak::ZoneVec;

/// The shape and property count each object has at some point, which
/// `AddNamed` nodes change.
type Shapes<'w> = ZoneMap<'w, NodeId, (CellId, u32)>;

/// The analysis of one graph.
struct Analysis<'w> {
    /// The allocations that may be replaced.
    candidates: ZoneSet<'w, NodeId>,
    /// The candidates that are closures.
    closures: ZoneSet<'w, NodeId>,
    /// For every value that is a candidate or stands for one (a candidate
    /// with empty values made undefined, or its cell address): the candidate.
    roots: ZoneMap<'w, NodeId, NodeId>,
    escaped: ZoneBitSet<'w>,
    /// Whether an object that does not escape is stored into another one.
    has_nested_objects: bool,
}

impl Analysis<'_> {
    fn root(&self, value: NodeId) -> Option<NodeId> {
        self.roots.get(&value).copied()
    }
}

fn placed_nodes<'w>(graph: &Graph, work: &'w Zone) -> ZoneVec<'w, NodeId> {
    ZoneVec::from_iter_in(graph.blocks.iter().flat_map(Block::nodes), work)
}

fn analyze<'w>(graph: &Graph, work: &'w Zone, placed: &[NodeId], escaping: &[NodeId]) -> Analysis<'w> {
    let mut candidates = ZoneSet::new_in(work);
    let mut closures = ZoneSet::new_in(work);
    let mut roots = ZoneMap::new_in(work);
    for node in placed {
        match graph.node(*node).op {
            Op::AllocateObject { .. } => {}
            Op::AllocateFunction { .. } => {
                closures.insert(*node);
            }
            _ => continue,
        }
        candidates.insert(*node);
        roots.insert(*node, *node);
    }
    let mut escaped = ZoneBitSet::new_in(graph.nodes.len(), work);
    for object in escaping {
        escaped.insert(object.index());
    }
    if candidates.is_empty() {
        return Analysis {
            candidates,
            closures,
            roots,
            escaped,
            has_nested_objects: false,
        };
    }

    // Values that stand for a candidate. They are defined after it, so one
    // walk in block order finds them.
    let mut changed = true;
    while changed {
        changed = false;
        for node in placed {
            let data = graph.node(*node);
            let stands_for_input = matches!(data.op, Op::EmptyToUndefined | Op::CellAddress)
                || data.op.refined_input() == Some(0) && data.repr.is_some();
            if !stands_for_input || roots.contains_key(node) {
                continue;
            }
            if let Some(root) = roots.get(&data.inputs[0]).copied() {
                roots.insert(*node, root);
                changed = true;
            }
        }
    }

    // NB: Code that calls run may read the legacy `arguments` of the frames
    //     of inlined calls. The runtime creates the objects among them that
    //     the code never allocated then, after nodes that guard against that
    //     (see `Op::AssumeLegacyArgumentsUnread`), except where code read
    //     them before: there, and after other nodes, they stay allocated.
    let guarded = ZoneSet::from_iter_in(
        graph
            .legacy_arguments_guards
            .iter()
            .flat_map(|(_, nodes)| nodes.iter().copied()),
        work,
    );
    let read_before = ZoneSet::from_iter_in(
        graph
            .exit_sites
            .iter()
            .filter(|(_, _, kind)| *kind == ExitKind::LegacyArgumentsRead)
            .map(|(executable, pc, _)| (*executable, *pc)),
        work,
    );
    for node in placed {
        let allocated_in = |frame_state: &FrameState| {
            !guarded.contains(node) || read_before.contains(&(frame_state.executable, frame_state.pc))
        };
        for value in graph.legacy_argument_values_read_by(*node, allocated_in) {
            if let Some(root) = roots.get(&value) {
                escaped.insert(root.index());
            }
        }
    }

    let shapes_before = shapes_before_uses(graph, work, &candidates, &roots, &mut escaped);

    // NB: Only closures escape from frame states.
    for node in placed.iter().filter(|_| !closures.is_empty()) {
        let data = graph.node(*node);
        let Some(frame_state) = data.frame_state else {
            continue;
        };
        let is_published = graph.frame_state(frame_state).parent.is_some() && lowering_info(data).publishes_frames;
        let is_call_without_frames = matches!(
            data.op,
            Op::CallDirect { inlined_frame_bytes, .. } | Op::CallNative { inlined_frame_bytes, .. }
                if inlined_frame_bytes != 0
        );
        if !is_published && !is_call_without_frames {
            continue;
        }
        for value in frame_state_values(graph, frame_state) {
            let Some(root) = roots.get(&value).copied().filter(|root| closures.contains(root)) else {
                continue;
            };
            let legacy_caller = matches!(
                graph.node(root).op,
                Op::AllocateFunction {
                    legacy_caller: true,
                    ..
                }
            );
            if is_published || legacy_caller {
                escaped.insert(root.index());
            }
        }
    }

    // Values stored into candidates: (value's candidate, the candidate it is stored into).
    let mut stored_into = ZoneVec::new_in(work);
    for node in placed {
        let data = graph.node(*node);
        for (index, input) in data.inputs.iter().enumerate() {
            let Some(root) = roots.get(input).copied() else {
                continue;
            };
            // NB: Every use of a candidate is where it has a known shape.
            let Some((shape, count)) = shapes_before.get(&(*node, root)).copied() else {
                escaped.insert(root.index());
                continue;
            };
            // NB: Closures have no properties that this pass knows.
            if closures.contains(&root) {
                if !matches!(data.op, Op::EmptyToUndefined | Op::CellAddress | Op::CheckObject) {
                    escaped.insert(root.index());
                }
                continue;
            }
            let accesses_object = match &data.op {
                Op::EmptyToUndefined | Op::CellAddress | Op::CheckObject => true,
                Op::LoadNamed { offset, .. } => *offset < count,
                Op::CheckShape { shapes } => shapes
                    .iter()
                    .any(|check| check.shape == shape && check.dictionary_generation.is_none()),
                Op::InitializeNamed { offset } | Op::StoreNamed { offset, .. } if index != 1 => *offset < count,
                Op::AddNamed { offset, .. } if index != 1 => *offset == count,
                Op::InitializeNamed { offset } | Op::StoreNamed { offset, .. } | Op::AddNamed { offset, .. } => {
                    stored_into.push((root, roots.get(&data.inputs[0]).copied(), *offset));
                    true
                }
                _ => false,
            };
            if !accesses_object {
                escaped.insert(root.index());
            }
        }
        // A frame state that refers to a candidate describes it as a virtual object with the shape it has there,
        // so it escapes where that shape isn't known: at a loop header that only a back edge reaches, e.g.
        if let Some(frame_state) = data.frame_state {
            for value in frame_state_values(graph, frame_state) {
                if let Some(root) = roots.get(&value).copied()
                    && !shapes_before.contains_key(&(*node, root))
                {
                    escaped.insert(root.index());
                }
            }
        }
    }
    // Loads of properties of candidates, as (candidate, offset).
    let loaded = ZoneVec::from_iter_in(
        placed.iter().filter_map(|node| match graph.node(*node).op {
            Op::LoadNamed { offset, .. } => roots.get(&graph.node(*node).inputs[0]).map(|root| (*root, offset)),
            _ => None,
        }),
        work,
    );
    // An object stored into one that escapes escapes too. So does one stored
    // into a property that is loaded, which makes its value another value
    // standing for the object.
    // FIXME: Track the objects loaded properties may hold, for objects
    //        nested in others that are read.
    let mut changed = true;
    while changed {
        changed = false;
        for (value, target, offset) in &stored_into {
            let target_escapes =
                target.is_none_or(|target| escaped.contains(target.index()) || loaded.contains(&(target, *offset)));
            if target_escapes && !escaped.contains(value.index()) {
                escaped.insert(value.index());
                changed = true;
            }
        }
    }
    let has_nested_objects = stored_into
        .iter()
        .any(|(value, target, _)| target.is_some() && !escaped.contains(value.index()));
    Analysis {
        candidates,
        closures,
        roots,
        escaped,
        has_nested_objects,
    }
}

/// Merges the shapes objects have at the ends of a block's predecessors:
/// objects whose shapes differ between paths escape, and objects missing on
/// a path are not defined after the merge.
fn merge_shapes<'a, 'w: 'a>(
    mut exits: impl Iterator<Item = &'a Shapes<'w>> + Clone,
    escaped: &mut ZoneBitSet,
    work: &'w Zone,
) -> Shapes<'w> {
    let Some(first) = exits.next() else {
        return Shapes::new_in(work);
    };
    let mut merged = Shapes::with_capacity_in(first.len(), work);
    for (object, shape) in first.iter() {
        let mut kept = true;
        for exit in exits.clone() {
            match exit.get(object) {
                Some(other) if other == shape => {}
                Some(_) => {
                    escaped.insert(object.index());
                    kept = false;
                    break;
                }
                None => {
                    kept = false;
                    break;
                }
            }
        }
        if kept {
            merged.insert(*object, *shape);
        }
    }
    merged
}

/// The shape and property count each object candidate has where each node
/// uses it, or its frame state refers to it, as (node, candidate). Objects
/// whose shapes differ between paths joining, or around a loop, escape.
fn shapes_before_uses<'w>(
    graph: &Graph,
    work: &'w Zone,
    candidates: &ZoneSet<NodeId>,
    roots: &ZoneMap<NodeId, NodeId>,
    escaped: &mut ZoneBitSet,
) -> ZoneMap<'w, (NodeId, NodeId), (CellId, u32)> {
    let mut before = ZoneMap::new_in(work);
    let block_count = graph.blocks.len();
    let mut entries: ZoneVec<Shapes> = ZoneVec::from_iter_in((0..block_count).map(|_| Shapes::new_in(work)), work);
    let mut exits: ZoneVec<Option<Shapes>> = ZoneVec::from_iter_in((0..block_count).map(|_| None), work);
    for (index, block) in graph.blocks.iter().enumerate() {
        let forward = block
            .predecessors
            .iter()
            .filter(|predecessor| predecessor.index() < index)
            .filter_map(|predecessor| exits[predecessor.index()].as_ref());
        let mut shapes = merge_shapes(forward, escaped, work);
        entries[index] = shapes.clone();
        for node in block.nodes() {
            let data = graph.node(node);
            let referred = data
                .frame_state
                .into_iter()
                .flat_map(|frame_state| frame_state_values(graph, frame_state));
            for value in data.inputs.iter().copied().chain(referred) {
                if let Some(root) = roots.get(&value)
                    && let Some(shape) = shapes.get(root)
                {
                    before.insert((node, *root), *shape);
                }
            }
            match data.op {
                Op::AllocateObject {
                    shape, property_count, ..
                } if candidates.contains(&node) => {
                    shapes.insert(node, (shape, property_count));
                }
                // NB: A closure has one shape, and no properties that this pass knows.
                Op::AllocateFunction { sample_slot, .. } if candidates.contains(&node) => {
                    shapes.insert(node, (sample_slot, 0));
                }
                Op::AddNamed {
                    shape, property_count, ..
                } => {
                    if let Some(root) = roots.get(&data.inputs[0]) {
                        shapes.insert(*root, (shape, property_count));
                    }
                }
                _ => {}
            }
        }
        exits[index] = Some(shapes);
    }
    for (index, block) in graph.blocks.iter().enumerate() {
        for predecessor in block
            .predecessors
            .iter()
            .filter(|predecessor| predecessor.index() >= index)
        {
            let Some(exit) = exits[predecessor.index()].as_ref() else {
                continue;
            };
            for (object, shape) in entries[index].iter() {
                if exit.get(object).is_some_and(|other| other != shape) {
                    escaped.insert(object.index());
                }
            }
        }
    }
    before
}

/// The values the frame states in the chain `frame_state` starts refer to.
fn frame_state_values<'g>(graph: &'g Graph, frame_state: FrameStateId) -> impl Iterator<Item = NodeId> + 'g {
    graph
        .frame_state_chain(frame_state)
        .flat_map(|id| graph.frame_state(id).values.iter().map(|(_, value)| *value))
}

/// The value of each property of each replaced object at one point.
type Properties<'w> = ZoneMap<'w, (NodeId, u32), NodeId>;

pub fn run(graph: &mut Graph, work: &Zone, steps: &mut [Zone; 2]) {
    let [step, _] = steps;
    let placed = placed_nodes(graph, work);
    let mut escaping = ZoneVec::new_in(work);
    loop {
        // NB: Each trial makes an analysis and a copy of the graph, which go when it ends.
        let done = step.scope(|step| {
            let analysis = analyze(graph, step, &placed, &escaping);
            // NB: Only objects stored into others can be values of phis of
            //     properties.
            if !analysis.has_nested_objects {
                replace_objects(graph, &analysis, step)
                    .expect("objects not stored into others merge in no phi of properties");
                return true;
            }
            // NB: A trial leaves the graph half edited where it fails, so it edits a copy, and the graph gets the
            //     same edits where it works.
            let mut copy = graph.clone_in(step);
            match replace_objects(&mut copy, &analysis, step) {
                Ok(()) => {
                    replace_objects(graph, &analysis, step).expect("the edits of a copy of the graph worked");
                    true
                }
                Err(objects) => {
                    escaping.extend_from_slice(objects);
                    false
                }
            }
        });
        if done {
            break;
        }
    }
    resolve_legacy_arguments_guards(graph, work);
}

/// Makes the `AssumeLegacyArgumentsUnread` nodes after nodes whose code may
/// read objects the code never allocated through legacy `arguments` (see
/// `Graph::defers_legacy_argument_objects()`) `AssumeValid` nodes, and
/// removes the others.
fn resolve_legacy_arguments_guards(graph: &mut Graph, work: &Zone) {
    let mut placed = ZoneBitSet::new_in(graph.nodes.len(), work);
    for node in placed_nodes(graph, work) {
        placed.insert(node.index());
    }
    let mut removed = ZoneBitSet::new_in(graph.nodes.len(), work);
    for (guard, nodes) in graph.legacy_arguments_guards.take() {
        let needed = nodes
            .iter()
            .any(|node| placed.contains(node.index()) && graph.defers_legacy_argument_objects(*node));
        if needed {
            graph.nodes[guard.index()].op = Op::AssumeValid;
        } else {
            removed.insert(guard.index());
        }
    }
    edit::remove_nodes(graph, &removed);
}

/// Lists that `virtualize_frame_state()` uses for each frame state, which it
/// empties when it is done with them.
struct Scratch<'w> {
    /// A frame state chain, innermost frame first.
    chain: ZoneVec<'w, FrameStateId>,
    /// The virtual object of each replaced object, made once for a point.
    objects: ZoneMap<'w, NodeId, NodeId>,
    /// The virtual objects whose inputs are their properties.
    filled: ZoneVec<'w, NodeId>,
    inputs: ZoneVec<'w, NodeId>,
}

/// Replaces the objects of `analysis` that do not escape. Fails with the
/// replaced objects that would be the values of phis of properties where
/// paths merge, which must escape instead, leaving `graph` half edited.
fn replace_objects<'w>(graph: &mut Graph, analysis: &Analysis, work: &'w Zone) -> Result<(), &'w [NodeId]> {
    if analysis
        .candidates
        .iter()
        .all(|candidate| analysis.escaped.contains(candidate.index()))
    {
        return Ok(());
    }
    let is_replaced = |value: NodeId| {
        analysis
            .root(value)
            .is_some_and(|root| !analysis.escaped.contains(root.index()))
    };

    let mut constants = Constants::new(graph, work);
    let undefined = constants.get(graph, value::UNDEFINED);
    let mut replacements = Replacements::new(graph, work);
    let mut removed = ZoneBitSet::new_in(graph.nodes.len(), work);
    let block_count = graph.blocks.len();
    let mut exit_properties: ZoneVec<Option<Properties>> = ZoneVec::from_iter_in((0..block_count).map(|_| None), work);
    let mut exit_shapes: ZoneVec<Option<Shapes>> = ZoneVec::from_iter_in((0..block_count).map(|_| None), work);
    // Loop header phis whose inputs along back edges are filled in last:
    // (phi, block, property).
    let mut pending_phis: ZoneVec<(NodeId, BlockId, (NodeId, u32))> = ZoneVec::new_in(work);
    // Replaced objects that would be values of those phis.
    let mut conflicts: ZoneVec<NodeId> = ZoneVec::new_in(work);
    let mut predecessors = ZoneVec::new_in(work);
    let mut values = ZoneVec::new_in(work);
    let mut nodes = ZoneVec::new_in(work);
    let mut scratch = Scratch {
        chain: ZoneVec::new_in(work),
        objects: ZoneMap::new_in(work),
        filled: ZoneVec::new_in(work),
        inputs: ZoneVec::new_in(work),
    };

    for block_index in 0..block_count {
        let block = BlockId::from_index(block_index);
        predecessors.assign(&graph.block(block).predecessors);
        let mut forward = predecessors
            .iter()
            .filter(|predecessor| predecessor.index() < block_index)
            .copied();
        let first = forward.next();
        let forward_count = forward.count() + usize::from(first.is_some());
        let mut properties = Properties::new_in(work);
        // NB: Replaced objects have the same shape on every path.
        let mut shapes = first
            .and_then(|first| exit_shapes[first.index()].clone())
            .unwrap_or_else(|| Shapes::new_in(work));
        if let Some(first) = first
            && let Some(first_properties) = exit_properties[first.index()].as_ref()
        {
            let has_back_edges = forward_count < predecessors.len();
            for (key, first_value) in first_properties.iter() {
                let (key, first_value) = (*key, *first_value);
                values.clear();
                let mut defined = true;
                for predecessor in &predecessors {
                    let value = if predecessor.index() < block_index {
                        exit_properties[predecessor.index()]
                            .as_ref()
                            .and_then(|exit| exit.get(&key).copied())
                    } else {
                        Some(first_value)
                    };
                    match value {
                        Some(value) => values.push(value),
                        None => {
                            defined = false;
                            break;
                        }
                    }
                }
                // NB: An object missing on a path is not defined there, so
                //     nothing after the merge uses it.
                if !defined {
                    continue;
                }
                if !has_back_edges && values.iter().all(|value| *value == first_value) {
                    properties.insert(key, first_value);
                    continue;
                }
                conflicts.extend(
                    values
                        .iter()
                        .map(|value| replacements.resolve(*value))
                        .filter(|value| is_replaced(*value))
                        .filter_map(|value| analysis.root(value)),
                );
                let phi = graph.add(Op::Phi, &values, Some(Repr::Tagged), 0);
                graph.blocks[block_index].phis.push(phi);
                if has_back_edges {
                    pending_phis.push((phi, block, key));
                }
                properties.insert(key, phi);
            }
        }

        nodes.clear();
        nodes.extend(
            graph
                .block(block)
                .body
                .iter()
                .chain(&graph.block(block).control)
                .copied(),
        );
        for node in &nodes {
            let node = *node;
            let data = graph.node(node);
            let (node_op, first_input, second_input, node_repr, node_frame_state) = (
                data.op.clone(),
                data.inputs.first().copied(),
                data.inputs.get(1).copied(),
                data.repr,
                data.frame_state,
            );
            let second_input = || second_input.expect("stores have a value");
            if let Some(frame_state) = node_frame_state {
                let new_frame_state = virtualize_frame_state(
                    graph,
                    analysis,
                    (&is_replaced, &replacements),
                    (&properties, &shapes),
                    frame_state,
                    &mut scratch,
                );
                graph.nodes[node.index()].frame_state = new_frame_state.or(node_frame_state);
            }
            let object = first_input.filter(|object| is_replaced(*object));
            match node_op {
                Op::AllocateObject {
                    shape, property_count, ..
                } if is_replaced(node) => {
                    for offset in 0..property_count {
                        properties.insert((node, offset), undefined);
                    }
                    shapes.insert(node, (shape, property_count));
                    removed.insert(node.index());
                }
                Op::AllocateFunction { sample_slot, .. } if is_replaced(node) => {
                    shapes.insert(node, (sample_slot, 0));
                    removed.insert(node.index());
                }
                Op::AddNamed {
                    offset,
                    shape,
                    property_count,
                } if object.is_some() => {
                    let root = analysis
                        .root(object.expect("checked"))
                        .expect("replaced objects have roots");
                    properties.insert((root, offset), replacements.resolve(second_input()));
                    shapes.insert(root, (shape, property_count));
                    removed.insert(node.index());
                }
                Op::InitializeNamed { offset } | Op::StoreNamed { offset, .. } if object.is_some() => {
                    let root = analysis
                        .root(object.expect("checked"))
                        .expect("replaced objects have roots");
                    properties.insert((root, offset), replacements.resolve(second_input()));
                    removed.insert(node.index());
                }
                Op::LoadNamed { offset, .. } if object.is_some() => {
                    let root = analysis
                        .root(object.expect("checked"))
                        .expect("replaced objects have roots");
                    let value = properties.get(&(root, offset)).copied().unwrap_or(undefined);
                    replacements.replace(node, value);
                    removed.insert(node.index());
                }
                Op::CheckShape { .. } | Op::CheckObject | Op::EmptyToUndefined | Op::CellAddress
                    if object.is_some() =>
                {
                    // NB: What a removed check refined is the object itself.
                    if node_op.refined_input().is_some() && node_repr.is_some() {
                        replacements.replace(node, object.expect("checked"));
                    }
                    removed.insert(node.index());
                }
                _ => {}
            }
        }
        exit_properties[block_index] = Some(properties);
        exit_shapes[block_index] = Some(shapes);
    }

    for (phi, block, key) in pending_phis.drain_all() {
        predecessors.assign(&graph.block(block).predecessors);
        for (index, predecessor) in predecessors.iter().enumerate() {
            if predecessor.index() < block.index() {
                continue;
            }
            // NB: A path that does not define the object leaves the phi's
            //     value as it is.
            let value = exit_properties[predecessor.index()]
                .as_ref()
                .and_then(|exit| exit.get(&key).copied())
                .unwrap_or(phi);
            let value = replacements.resolve(value);
            if is_replaced(value) {
                conflicts.extend(analysis.root(value));
            }
            graph.nodes[phi.index()].inputs[index] = value;
        }
    }

    if !conflicts.is_empty() {
        conflicts.sort_unstable();
        conflicts.dedup();
        return Err(conflicts.into_slice());
    }
    replacements.apply(graph);
    edit::remove_nodes(graph, &removed);
    edit::remove_trivial_phis(graph, work);
    Ok(())
}

/// A copy of the frame state chain `frame_state` with the objects that were
/// replaced made virtual objects with the shapes and property values they
/// have there, or `None` if it refers to no such object.
fn virtualize_frame_state(
    graph: &mut Graph,
    analysis: &Analysis,
    (is_replaced, replacements): (&dyn Fn(NodeId) -> bool, &Replacements),
    (properties, shapes): (&Properties, &Shapes),
    frame_state: FrameStateId,
    scratch: &mut Scratch,
) -> Option<FrameStateId> {
    let refers_to_replaced = graph.frame_state_chain(frame_state).any(|id| {
        graph
            .frame_state(id)
            .values
            .iter()
            .any(|(_, value)| is_replaced(replacements.resolve(*value)))
    });
    if !refers_to_replaced {
        return None;
    }
    let Scratch {
        chain,
        objects,
        filled,
        inputs,
    } = scratch;
    chain.clear();
    chain.extend(graph.frame_state_chain(frame_state));
    objects.clear();
    filled.clear();
    // The virtual object of each replaced object, made once for this point.
    let virtual_object = |graph: &mut Graph, objects: &mut ZoneMap<NodeId, NodeId>, value: NodeId| -> NodeId {
        let value = replacements.resolve(value);
        if !is_replaced(value) {
            return value;
        }
        let root = analysis.root(value).expect("replaced objects have roots");
        if let Some(object) = objects.get(&root) {
            return *object;
        }
        let (shape, _) = *shapes.get(&root).expect("replaced objects have shapes");
        let kind = if analysis.closures.contains(&root) {
            VirtualObjectKind::Closure { sample_slot: shape }
        } else {
            VirtualObjectKind::Object { shape }
        };
        let object = graph.add(
            Op::VirtualObject { kind, allocation: root },
            &[],
            Some(Repr::Tagged),
            graph.node(root).pc,
        );
        objects.insert(root, object);
        object
    };
    let mut parent = None;
    for id in chain.iter().rev() {
        let mut copy = graph.frame_state(*id).clone();
        for (_, value) in &mut copy.values {
            *value = virtual_object(graph, objects, *value);
        }
        copy.parent = parent;
        parent = Some(graph.add_frame_state(copy));
    }
    // The properties of the virtual objects, which may be virtual objects
    // themselves.
    loop {
        let Some((root, object)) = objects
            .iter()
            .map(|(root, object)| (*root, *object))
            .find(|(_, object)| !filled.contains(object))
        else {
            break;
        };
        filled.push(object);
        inputs.clear();
        // NB: The environments of a closure are what its allocation had.
        if analysis.closures.contains(&root) {
            inputs.extend(graph.node(root).inputs.iter().map(|input| replacements.resolve(*input)));
            graph.nodes[object.index()].inputs.assign(inputs);
            continue;
        }
        let (_, property_count) = *shapes.get(&root).expect("replaced objects have shapes");
        for offset in 0..property_count {
            let property = properties
                .get(&(root, offset))
                .copied()
                .expect("replaced objects have every property");
            let value = virtual_object(graph, objects, property);
            inputs.push(value);
        }
        graph.nodes[object.index()].inputs.assign(inputs);
    }
    parent
}