Skip to content

Truly independent web browser

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

//! Redundant check and load elimination.
//!
//! A forward dataflow analysis over the control flow graph computes, before
//! every node, what is known about values (see `Facts`): what kinds of value
//! they may be, which shapes and elements kinds objects may have, which
//! prototype chains are valid, which values passed which value checks, and
//! what named properties, bindings, element counts and elements hold. Loop
//! headers start optimistically with what holds on entry and are revisited
//! until what the back edges bring agrees with it.
//!
//! Branches on the kind of a value tell their targets what it is, and
//! become jumps where what is known decides them. So do branches on values
//! alone (comparisons, builtin tests), which go the way a branch on the same
//! values went before.
//!
//! With those facts, checks that already passed are removed, loads of a
//! property whose value is known are replaced by that value (including
//! values stored before, and the constants a value check established), and
//! shape switches on objects whose shapes are known only keep the cases
//! that can match, or become jumps.
//!
//! A removed check's value is the latest refinement of its input on every
//! path to it, which a check or branch that passed made, so that what uses
//! it stays behind that check. Checks with no such refinement stay.
//!
//! Objects keep stable shapes (see `Dependency::StableShape`) while other
//! code runs, as long as the compiled code stays valid. The first shape
//! check that relies on that after other code ran becomes an `AssumeValid`,
//! and the code depends on the stable shapes known from then on.

use super::edit;
use super::edit::Constants;
use super::edit::Replacements;
use super::facts::BranchKey;
use super::facts::ElementCount;
use super::facts::Facts;
use super::facts::Location;
use super::facts::Moved;
use super::facts::ValueKind;
use super::facts::elements_kind_implies;
use crate::bytecode::OpCode;
use crate::code::Dependency;
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;
use ak::Zone;
use ak::ZoneBitSet;
use ak::ZoneVec;

/// What the analysis decided for the nodes of one visit of the graph.
struct Decisions<'w> {
    replacements: Replacements<'w>,
    removed: ZoneBitSet<'w>,
    /// Control nodes to replace, with what.
    controls: ZoneVec<'w, (NodeId, NewControl<'w>)>,
    /// Shape checks that become `AssumeValid` nodes.
    assumptions: ZoneVec<'w, NodeId>,
    /// The stable shapes the code relies on staying stable.
    stable_shapes: ZoneVec<'w, CellId>,
    /// The inputs of the node being visited, as the analysis knows them.
    inputs: ZoneVec<'w, NodeId>,
    /// The cases of the shape switch being visited that can match.
    possible: ZoneVec<'w, (ShapeCheck, BlockId)>,
}

/// Facts flowing along edges, each with the block the edge leads to.
type Edges<'w> = ZoneVec<'w, (BlockId, Facts<'w>)>;

/// What a control node is replaced with.
enum NewControl<'w> {
    Jump {
        target: BlockId,
    },
    /// A shape switch with fewer cases, each a shape and its target.
    ShapeSwitch {
        cases: &'w [(ShapeCheck, BlockId)],
    },
}

impl Decisions<'_> {
    /// Forgets the decisions of the last visit.
    fn clear(&mut self) {
        self.replacements.clear();
        self.removed.clear();
        self.controls.clear();
        self.assumptions.clear();
        self.stable_shapes.clear();
    }

    /// The value the analysis knows `value` as: what it is replaced by, and
    /// the value it refines (facts are about values, whatever refines them).
    fn value(&self, graph: &Graph, value: NodeId) -> NodeId {
        let mut value = self.replacements.resolve(value);
        loop {
            let unrefined = graph.unrefined(value);
            let replaced = self.replacements.resolve(unrefined);
            if replaced == value {
                return value;
            }
            value = replaced;
        }
    }
}

/// The edges out of a block, each with the slot of the facts along it in the `Store`.
type EdgeSlots<'w> = ZoneVec<'w, (BlockId, u32)>;

/// The facts that the visits of blocks hand on to later ones, in a step zone. Each is in a slot, which the tables of
/// `Round` name, so that a move of the facts in use copies those and nothing else.
struct Store<'f> {
    zone: &'f Zone,
    /// The facts of each slot, or none for a slot that is free.
    facts: ZoneVec<'f, Option<Facts<'f>>>,
    /// The facts along the edges into the block being visited, which is empty between visits.
    incoming: Edges<'f>,
    /// The facts along the edges out of the block being visited, which is empty between visits.
    outgoing: Edges<'f>,
}

impl<'f> Store<'f> {
    fn new_in(zone: &'f Zone) -> Self {
        Self {
            zone,
            facts: ZoneVec::new_in(zone),
            incoming: ZoneVec::new_in(zone),
            outgoing: ZoneVec::new_in(zone),
        }
    }

    /// Puts `facts` in a slot that `free` lists, or in a new one, and returns the slot.
    fn put(&mut self, facts: Facts<'f>, free: &mut ZoneVec<u32>) -> u32 {
        if let Some(slot) = free.pop() {
            self.facts[slot as usize] = Some(facts);
            return slot;
        }
        self.facts.push(Some(facts));
        u32::try_from(self.facts.len() - 1).expect("the facts in use fit in 2^32 slots")
    }

    /// Takes the facts of `slot`, which becomes free.
    fn take(&mut self, slot: u32, free: &mut ZoneVec<u32>) -> Facts<'f> {
        free.push(slot);
        self.facts[slot as usize].take().expect("a slot in use holds facts")
    }

    fn get(&self, slot: u32) -> &Facts<'f> {
        self.facts[slot as usize].as_ref().expect("a slot in use holds facts")
    }

    fn get_mut(&mut self, slot: u32) -> &mut Facts<'f> {
        self.facts[slot as usize].as_mut().expect("a slot in use holds facts")
    }

    /// The same facts in the same slots, in `zone`, with lists that are shared where they are here.
    fn move_to(self, zone: &Zone) -> Store<'_> {
        debug_assert!(self.incoming.is_empty() && self.outgoing.is_empty());
        let mut moved = Moved::new_in(zone);
        let facts = ZoneVec::from_iter_in(
            self.facts
                .iter()
                .map(|facts| facts.as_ref().map(|facts| facts.move_to(&mut moved))),
            zone,
        );
        Store {
            zone,
            facts,
            incoming: ZoneVec::new_in(zone),
            outgoing: ZoneVec::new_in(zone),
        }
    }
}

/// How many bytes a step zone of the pass may hold before the facts still in use move to the other one: twice what
/// they took right after the last move, and at least 1 MiB, so that the zone holds at most about three times the facts
/// in use, and the facts of small functions never move.
fn move_limit(kept: usize) -> usize {
    (2 * kept).max(1 << 20)
}

pub fn run(graph: &mut Graph, work: &Zone, steps: &mut [Zone; 2]) {
    let mut constants = Constants::new(graph, work);
    // NB: The visits add no nodes to blocks, only constants.
    let mut decisions = Decisions {
        replacements: Replacements::new(graph, work),
        removed: ZoneBitSet::new_in(graph.nodes.len(), work),
        controls: ZoneVec::new_in(work),
        assumptions: ZoneVec::new_in(work),
        stable_shapes: ZoneVec::new_in(work),
        inputs: ZoneVec::new_in(work),
        possible: ZoneVec::new_in(work),
    };
    let mut round = Round::new(graph, &mut constants, &mut decisions, work);
    // NB: The facts of each block copy lists of the facts before it, which a zone takes back only all at once. So
    //     the visits stop when the store of the facts holds much more than after the last move, the facts in use
    //     move to the other step zone, and the zone they leave is reset.
    let [zone, other] = steps;
    let mut store = Store::new_in(zone);
    let mut kept = 0;
    loop {
        if round.run(&mut store, move_limit(kept)) {
            break;
        }
        let mut moved = store.move_to(other);
        kept = other.used();
        zone.reset();
        if round.run(&mut moved, move_limit(kept)) {
            break;
        }
        store = moved.move_to(zone);
        kept = zone.used();
        other.reset();
    }

    decisions.replacements.apply(graph);
    edit::remove_nodes(graph, &decisions.removed);
    for node in decisions.assumptions.drain_all() {
        graph.nodes[node.index()].op = Op::AssumeValid;
        graph.nodes[node.index()].inputs.clear();
        graph.nodes[node.index()].repr = None;
    }
    for shape in decisions.stable_shapes.drain_all() {
        graph.depend_on(Dependency::StableShape(shape));
    }
    let changed_control_flow = !decisions.controls.is_empty();
    for (node, control) in decisions.controls.drain_all() {
        match control {
            NewControl::Jump { target } => edit::make_jump(graph, node, target),
            NewControl::ShapeSwitch { cases } => {
                let zone = graph.zone;
                graph.nodes[node.index()].op = Op::ShapeSwitch {
                    shapes: zone.alloc_slice_from_iter(cases.iter().map(|(shape, _)| *shape)),
                    targets: zone.alloc_slice_from_iter(cases.iter().map(|(_, target)| *target)),
                };
            }
        }
    }
    if changed_control_flow {
        edit::clean_up_control_flow(graph, work);
    }
}

/// The rounds of visits of the blocks, until the facts stop changing, with what lasts from one visit to the next
/// apart from the facts themselves: the slots of the facts in the `Store`, which can move to another zone between
/// two visits.
struct Round<'a, 'g, 'w> {
    graph: &'a mut Graph<'g>,
    constants: &'a mut Constants<'w>,
    decisions: &'a mut Decisions<'w>,
    /// Whether each block has predecessors later in the order. Only those can see other facts in another round:
    /// they decide when the rounds are done.
    revisited: ZoneVec<'w, bool>,
    visited: ZoneVec<'w, bool>,
    skipped: ZoneVec<'w, BlockId>,
    /// For each block, the edges out of it from its latest visit that no block took the facts of yet.
    edges: ZoneVec<'w, EdgeSlots<'w>>,
    /// For each block that `revisited` holds for, the slot of its facts at entry from its latest visit, if any.
    entry_facts: ZoneVec<'w, Option<u32>>,
    /// The slots of the store that are free.
    free: ZoneVec<'w, u32>,
    /// Whether the facts changed in this round.
    changed: bool,
    /// The block to visit next in this round.
    next: usize,
}

impl<'a, 'g, 'w> Round<'a, 'g, 'w> {
    fn new(
        graph: &'a mut Graph<'g>,
        constants: &'a mut Constants<'w>,
        decisions: &'a mut Decisions<'w>,
        work: &'w Zone,
    ) -> Self {
        let block_count = graph.blocks.len();
        let revisited = ZoneVec::from_iter_in(
            (0..block_count).map(|block| {
                graph.blocks[block]
                    .predecessors
                    .iter()
                    .any(|predecessor| predecessor.index() >= block)
            }),
            work,
        );
        let mut round = Self {
            graph,
            constants,
            decisions,
            revisited,
            visited: ZoneVec::from_elem_in(false, block_count, work),
            skipped: ZoneVec::new_in(work),
            edges: ZoneVec::from_iter_in((0..block_count).map(|_| ZoneVec::new_in(work)), work),
            entry_facts: ZoneVec::from_elem_in(None, block_count, work),
            free: ZoneVec::new_in(work),
            changed: false,
            next: 0,
        };
        round.start();
        round
    }

    /// Starts a round.
    fn start(&mut self) {
        self.decisions.clear();
        self.changed = false;
        self.visited.fill(false);
        self.skipped.clear();
        self.next = 0;
    }

    /// Visits blocks until the facts stop changing, and returns true, or until `store` holds more than `limit` bytes
    /// before a visit, and returns false. It goes on where it stopped when it is called again.
    fn run(&mut self, store: &mut Store, limit: usize) -> bool {
        loop {
            if self.next == self.graph.blocks.len() {
                // NB: A block that only back edges lead to (code after an entry that comes later in the order,
                //     such as an on-stack replacement entry) is skipped until they bring facts, which they did if
                //     a predecessor visited later has facts along its edge. What can be reached from it then saw
                //     other facts along the other paths in this round.
                let edges = &self.edges;
                let graph = &*self.graph;
                self.changed |= self.skipped.iter().any(|block| {
                    graph
                        .block(*block)
                        .predecessors
                        .iter()
                        .any(|predecessor| edges[predecessor.index()].iter().any(|(target, _)| target == block))
                });
                if !self.changed {
                    return true;
                }
                self.start();
                continue;
            }
            if store.zone.used() > limit {
                return false;
            }
            self.visit(store, self.next);
            self.next += 1;
        }
    }

    /// Frees the slots of the edges out of `block`.
    fn clear_edges(&mut self, store: &mut Store, block: usize) {
        for (_, slot) in self.edges[block].drain_all() {
            store.take(slot, &mut self.free);
        }
    }

    /// Visits `block`, with the facts along the edges into it, and hands on the facts along the edges out of it.
    fn visit(&mut self, store: &mut Store, block: usize) {
        let block_id = BlockId::from_index(block);
        let mut incoming = store.incoming.take();
        let facts = facts_at_entry(
            self.graph,
            block_id,
            (&mut self.edges, store, &mut self.free, &mut incoming),
            &self.visited,
            &self.revisited,
            self.decisions,
        );
        store.incoming = incoming;
        let Some(mut facts) = facts else {
            // No visited predecessor reaches this block.
            self.clear_edges(store, block);
            self.skipped.push(block_id);
            return;
        };
        self.visited[block] = true;
        if self.revisited[block] {
            match self.entry_facts[block] {
                Some(slot) if *store.get(slot) == facts => {}
                Some(slot) => {
                    self.changed = true;
                    *store.get_mut(slot) = facts.share();
                }
                None => {
                    self.changed = true;
                    self.entry_facts[block] = Some(store.put(facts.share(), &mut self.free));
                }
            }
        }
        self.clear_edges(store, block);
        let mut outgoing = store.outgoing.take();
        visit_block(
            self.graph,
            self.constants,
            block_id,
            facts,
            self.decisions,
            &mut outgoing,
        );
        for (target, facts) in outgoing.drain_all() {
            let slot = store.put(facts, &mut self.free);
            self.edges[block].push((target, slot));
        }
        store.outgoing = outgoing;
    }
}

/// The facts at the start of `block`, which takes them from the edges into
/// it: what holds on every edge into it from a visited predecessor. Edges
/// from predecessors not visited yet in this round (loop back edges) are
/// 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.
///
/// It takes the facts of the edges into the block out of `store`, whose
/// slots `edges` names, and frees their slots in `free`. `incoming` is a list
/// for the facts along the edges into the block, which is empty and stays
/// empty.
fn facts_at_entry<'f>(
    graph: &Graph,
    block: BlockId,
    (edges, store, free, incoming): (&mut [EdgeSlots], &mut Store<'f>, &mut ZoneVec<u32>, &mut Edges<'f>),
    visited: &[bool],
    revisited: &[bool],
    decisions: &Decisions,
) -> Option<Facts<'f>> {
    let zone = store.zone;
    let predecessors = &graph.block(block).predecessors;
    if predecessors.is_empty() {
        let mut facts = Facts::new_in(zone);
        facts.assume_code_valid();
        return Some(facts);
    }
    for predecessor in predecessors {
        let is_back_edge = predecessor.index() >= block.index();
        if !is_back_edge && !visited[predecessor.index()] {
            continue;
        }
        let edges = &mut edges[predecessor.index()];
        let mut index = 0;
        while index < edges.len() {
            if edges[index].0 == block {
                let (_, slot) = edges.remove(index);
                incoming.push((*predecessor, store.take(slot, free)));
            } else {
                index += 1;
            }
        }
    }
    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(zone, incoming.drain_all().map(|(_, facts)| facts))),
        };
    }
    let mut facts = Facts::merge(zone, incoming.iter_mut().map(|(_, facts)| facts.share()));
    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);
    }
    incoming.clear();
    Some(facts)
}

/// Applies the nodes of `block` to `facts`, recording decisions, and adds
/// the facts flowing along each of its outgoing edges to `edges`.
fn visit_block<'f>(
    graph: &mut Graph,
    constants: &mut Constants,
    block: BlockId,
    mut facts: Facts<'f>,
    decisions: &mut Decisions,
    edges: &mut Edges<'f>,
) {
    // NB: A phi makes another value of the objects it merges, which anything
    //     may see.
    for phi in &graph.block(block).phis {
        for input in &graph.node(*phi).inputs {
            facts.expose(decisions.value(graph, *input));
        }
    }
    for index in 0..graph.block(block).body.len() {
        let node = graph.block(block).body[index];
        visit_node(graph, constants, node, &mut facts, decisions);
    }
    let control = graph.control_id(block);
    // A branch on the kind of a value (or of the elements of an object)
    // knows it where it holds, and only keeps the edge that what is known
    // already decides.
    if let Op::Branch {
        condition,
        if_true,
        if_false,
    } = graph.node(control).op
        && Facts::is_about_kinds(condition)
    {
        let value = decisions.value(graph, graph.node(control).inputs[0]);
        if let Some(holds) = facts.decides(graph, value, condition) {
            let target = if holds { if_true } else { if_false };
            decisions.controls.push((control, NewControl::Jump { target }));
            edges.push((target, facts));
            return;
        }
        let mut passed = facts.share();
        passed.forget_refinement(value);
        passed.set_passed(value, condition);
        facts.set_failed(value, condition);
        edges.push((if_true, passed));
        edges.push((if_false, facts));
        return;
    }
    // A branch on values alone goes the way a branch on the same values
    // went before.
    if let Op::Branch { .. } = graph.node(control).op {
        let mut inputs = decisions.inputs.take();
        inputs.clear();
        inputs.extend(
            graph
                .node(control)
                .inputs
                .iter()
                .map(|input| decisions.value(graph, *input)),
        );
        let undecided = visit_value_branch(graph, control, &inputs, facts, decisions, edges);
        decisions.inputs = inputs;
        let Some(undecided) = undecided else {
            return;
        };
        facts = undecided;
    }
    let Op::ShapeSwitch { shapes, targets } = graph.node(control).op else {
        let successors = graph.successors(block);
        let Some((last, others)) = successors.split_last() else {
            return;
        };
        for successor in others {
            edges.push((*successor, facts.share()));
        }
        edges.push((*last, facts));
        return;
    };
    let object = decisions.value(graph, graph.node(control).inputs[0]);
    // NB: Shapes known only while the code is valid would need a check.
    let known = facts.shapes(object).filter(|_| !facts.is_unvalidated(object));
    let mut possible = decisions.possible.take();
    possible.clear();
    possible.extend(
        shapes
            .iter()
            .copied()
            .zip(targets.iter().copied())
            .filter(|(shape, _)| known.is_none_or(|known| known.contains(shape))),
    );
    let covers_known =
        known.is_some_and(|known| known.iter().all(|shape| possible.iter().any(|(case, _)| case == shape)));
    match possible.as_slice() {
        [(_, target)] if covers_known => decisions.controls.push((control, NewControl::Jump { target: *target })),
        _ if possible.len() < shapes.len() && !possible.is_empty() => {
            let cases = possible.zone().alloc_slice_copy(&possible);
            decisions.controls.push((control, NewControl::ShapeSwitch { cases }));
        }
        _ => {}
    }
    for (shape, target) in &possible {
        let mut case_facts = facts.share();
        case_facts.set_shapes(object, &[*shape]);
        edges.push((*target, case_facts));
    }
    decisions.possible = possible;
}

/// The edges of the branch `control` on values alone, its `inputs` as the
/// analysis knows them: it goes the way a branch on the same values went
/// before. Gives `facts` back where it is no such branch.
fn visit_value_branch<'f>(
    graph: &Graph,
    control: NodeId,
    inputs: &[NodeId],
    mut facts: Facts<'f>,
    decisions: &mut Decisions,
    edges: &mut Edges<'f>,
) -> Option<Facts<'f>> {
    let Op::Branch {
        condition,
        if_true,
        if_false,
    } = graph.node(control).op
    else {
        return Some(facts);
    };
    // NB: A value of a known kind is no empty value (like a binding that
    //     is initialized, which a store of it checks).
    if let BranchCondition::TaggedEquals { equal } = condition
        && graph.constant_value(inputs[1]) == Some(value::EMPTY)
        && facts.value_kind(inputs[0]).is_some()
    {
        let target = if equal { if_false } else { if_true };
        decisions.controls.push((control, NewControl::Jump { target }));
        edges.push((target, facts));
        return None;
    }
    let Some(key) = BranchKey::of(graph, condition, inputs) else {
        return Some(facts);
    };
    if let Some(holds) = facts.branch_outcome(&key) {
        let target = if holds { if_true } else { if_false };
        decisions.controls.push((control, NewControl::Jump { target }));
        edges.push((target, facts));
        return None;
    }
    let mut passed = facts.share();
    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);
    }
    edges.push((if_true, passed));
    edges.push((if_false, facts));
    None
}

/// Whether input `index` of a node with `op` is an object whose properties
/// (or shape) the node accesses, and nothing else.
fn accesses_properties(op: &Op, index: usize) -> bool {
    match op {
        Op::CheckObject | Op::CellAddress | Op::InitializeNamed { .. } => index == 0,
        Op::CheckShape { .. }
        | Op::ShapeSwitch { .. }
        | Op::LoadNamed { .. }
        | Op::CheckAccessorFunction { .. }
        | Op::LoadAccessorFunction { .. } => true,
        Op::StoreNamed { .. } | Op::AddNamed { .. } => index != 1,
        _ => false,
    }
}

fn visit_node(
    graph: &mut Graph,
    constants: &mut Constants,
    node_id: NodeId,
    facts: &mut Facts,
    decisions: &mut Decisions,
) {
    let mut inputs = decisions.inputs.take();
    inputs.clear();
    inputs.extend(
        graph
            .node(node_id)
            .inputs
            .iter()
            .map(|input| decisions.value(graph, *input)),
    );
    visit_node_with_inputs(graph, constants, node_id, &inputs, facts, decisions);
    decisions.inputs = inputs;
}

/// `visit_node()`, with the inputs of the node as the analysis knows them.
fn visit_node_with_inputs(
    graph: &mut Graph,
    constants: &mut Constants,
    node_id: NodeId,
    inputs: &[NodeId],
    facts: &mut Facts,
    decisions: &mut Decisions,
) {
    let node = graph.node(node_id);
    let input = |index: usize| inputs[index];
    for (index, input) in inputs.iter().enumerate() {
        if facts.is_unexposed(*input) && !accesses_properties(&node.op, index) {
            facts.expose(*input);
        }
    }
    for value in graph.legacy_argument_values_read_by(node_id, |_| true) {
        facts.expose(decisions.value(graph, value));
    }
    // NB: A check known to pass is replaced by what refined its input
    //     before (see `Facts::refinement()`), and stays where nothing did.
    let refines = node.op.refined_input().is_some() && node.repr.is_some();
    let anchor = if refines {
        facts
            .refinement(input(0))
            .or_else(|| graph.constant_value(input(0)).map(|_| input(0)))
    } else {
        None
    };
    let removable = !refines || anchor.is_some();
    let mut remove = false;
    let mut becomes_assumption = false;
    match node.op {
        Op::CheckObject => {
            let value = input(0);
            let is_object_constant = graph
                .constant_value(value)
                .is_some_and(|bits| crate::ir::value::tag(bits) == crate::ir::value::OBJECT_TAG);
            remove = removable && (is_object_constant || facts.is_object(value));
            facts.set_object(value);
        }
        Op::CheckShape { shapes } => {
            let object = input(0);
            remove = removable
                && facts
                    .shapes(object)
                    .is_some_and(|known| known.iter().all(|shape| shapes.contains(shape)));
            if remove && facts.is_unvalidated(object) {
                // The object still has its stable shape if the code is still
                // valid, and so do all objects with known shapes after this.
                if !facts.is_code_valid() {
                    remove = false;
                    becomes_assumption = true;
                    decisions.assumptions.push(node_id);
                    if let Some(anchor) = anchor {
                        decisions.replacements.replace(node_id, anchor);
                    }
                    facts.assume_code_valid();
                }
                validate(facts, &graph.stable_shapes, decisions);
            } else if !remove {
                facts.set_shapes(object, shapes);
            }
        }
        // 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);
        }
        Op::CheckValue { expected, .. } => {
            let value = input(0);
            remove =
                removable && (graph.constant_value(value) == Some(expected) || facts.is_checked_value(value, expected));
            if !remove {
                facts.set_checked_value(value, expected);
                // A checked load of a property or a global binding makes it
                // known to hold the constant.
                if let Some(location @ (Location::Named { .. } | Location::GlobalBinding { .. })) =
                    loaded_location(graph, decisions, value)
                    && facts.contents(location) == Some(value)
                {
                    let constant = constants.get(graph, expected);
                    facts.set_contents(location, constant);
                }
            }
        }
        Op::LoadNamed { .. }
        | Op::LoadGlobalBinding { .. }
        | Op::LoadEnvironmentBinding { .. }
        | Op::LoadElementsLength
        | Op::LoadElementsCapacity
        | Op::LoadTypedArrayLength
        | Op::LoadTypedArrayDataOffset
        | Op::LoadElementAt { .. } => {
            let location = loaded_location(graph, decisions, node_id).expect("loads load a location");
            remove = reuse_contents(facts, location, node_id, decisions);
        }
        Op::AssumeValid => {
            remove = facts.is_code_valid();
            facts.assume_code_valid();
            validate(facts, &graph.stable_shapes, decisions);
        }
        Op::StoreGlobalBinding { environment, index } => {
            facts.forget_bindings_at(index);
            facts.set_contents(Location::GlobalBinding { environment, index }, input(0));
        }
        Op::StoreEnvironmentBinding { index } => {
            facts.forget_bindings_at(index);
            let location = Location::Binding {
                environment: input(0),
                index,
            };
            facts.set_contents(location, input(1));
        }
        Op::StoreNamed { offset, .. } => {
            let (object, value) = (input(0), input(1));
            facts.forget_named_properties_at(offset);
            facts.set_contents(Location::Named { object, offset }, value);
        }
        Op::AddNamed { offset, shape, .. } => {
            // NB: Values known to have the old shape may be the object, which
            //     has the new one now. No object had the new property before.
            let object = input(0);
            facts.forget_shapes_of(object);
            facts.set_object(object);
            facts.set_shapes(
                object,
                &[ShapeCheck {
                    shape,
                    dictionary_generation: None,
                }],
            );
            facts.set_contents(Location::Named { object, offset }, input(1));
        }
        Op::CheckElements { kind } => {
            let object = input(0);
            // NB: A holey access takes packed elements too.
            remove = removable
                && graph
                    .constant_value(object)
                    .and_then(|bits| graph.typed_array_constants.iter().find(|(value, _)| *value == bits))
                    .map(|(_, array)| ElementsKind::TypedArray(array.element))
                    .or_else(|| facts.elements_kind(object))
                    .is_some_and(|known| elements_kind_implies(known, kind) == Some(true));
            facts.set_object(object);
            if !remove {
                facts.set_elements_kind(object, kind);
            }
        }
        Op::AllocateObject {
            shape, property_count, ..
        } => {
            // A new object of the shape, with every property undefined.
            new_object(facts, node_id);
            facts.set_unexposed(node_id);
            facts.set_shapes(
                node_id,
                &[ShapeCheck {
                    shape,
                    dictionary_generation: None,
                }],
            );
            let undefined = constants.get(graph, crate::ir::value::UNDEFINED);
            for offset in 0..property_count {
                facts.set_contents(
                    Location::Named {
                        object: node_id,
                        offset,
                    },
                    undefined,
                );
            }
        }
        Op::InitializeNamed { offset } => {
            // NB: Nothing else can see the object yet, so no other object's
            //     property is the same one.
            facts.set_contents(
                Location::Named {
                    object: input(0),
                    offset,
                },
                input(1),
            );
        }
        // NB: SliceArguments is a runtime call that makes a new array and
        //     runs nothing else.
        Op::AllocateFunction { .. } | Op::SliceArguments => new_object(facts, node_id),
        Op::AllocateArray { count } => {
            // A new array, with packed elements if it has any.
            new_object(facts, node_id);
            if count != 0 {
                facts.set_elements_kind(node_id, ElementsKind::Packed);
            }
        }
        Op::CheckAppendableArray | Op::CheckArray => {
            // It exits for anything but arrays.
            facts.set_object(input(0));
        }
        ref op => {
            facts.apply(&op.properties(), &graph.stable_shapes);
        }
    }
    if remove {
        if let Some(anchor) = anchor {
            decisions.replacements.replace(node_id, anchor);
        }
        decisions.removed.insert(node_id.index());
    } else if refines && !becomes_assumption {
        facts.set_refinement(input(0), node_id);
    }
}

/// The location the load `load` reads, which facts may know the contents
/// of.
fn loaded_location(graph: &Graph, decisions: &Decisions, load: NodeId) -> Option<Location> {
    let node = graph.node(load);
    let input = |index: usize| decisions.value(graph, node.inputs[index]);
    Some(match node.op {
        Op::LoadNamed { offset, .. } => Location::Named {
            object: input(0),
            offset,
        },
        Op::LoadGlobalBinding { environment, index } => Location::GlobalBinding { environment, index },
        Op::LoadEnvironmentBinding { index } => Location::Binding {
            environment: input(0),
            index,
        },
        Op::LoadElementAt { kind } => Location::Element {
            storage: storage_object(graph, decisions, input(0)),
            index: index_value(graph, decisions, input(1)),
            kind,
        },
        ref op => {
            let count = ElementCount::loaded_by(op);
            if count.is_none() && !matches!(op, Op::LoadTypedArrayDataOffset) {
                return None;
            }
            let object = storage_object(graph, decisions, input(0));
            match count {
                Some(count) => Location::ElementCount { count, object },
                None => Location::TypedArrayDataOffset { object },
            }
        }
    })
}

/// The value that the index `index` of an element access is, as the
/// analysis knows it: refinements of a value (like the bounds checks of each
/// access) and int32 checks and unboxings of a value are the same index.
fn index_value(graph: &Graph, decisions: &Decisions, index: NodeId) -> NodeId {
    let mut index = decisions.value(graph, index);
    while matches!(graph.node(index).op, Op::CheckInt32 | Op::UnboxInt32) {
        index = decisions.value(graph, graph.node(index).inputs[0]);
    }
    index
}

/// The object whose address or whose typed array data address is
/// `address`, or `address` itself if it is none's.
fn storage_object(graph: &Graph, decisions: &Decisions, address: NodeId) -> NodeId {
    // NB: Before value numbering, an object may have several addresses,
    //     and every access of a typed array computes its data address.
    //     Writes of element counts, which change the storage offset, forget
    //     the elements of every storage.
    let node = graph.node(address);
    match node.op {
        Op::CellAddress => decisions.value(graph, node.inputs[0]),
        Op::TypedArrayDataAddress => {
            let offset = graph.node(graph.unrefined(decisions.value(graph, node.inputs[0])));
            match offset.op {
                Op::LoadTypedArrayDataOffset => storage_object(graph, decisions, offset.inputs[0]),
                _ => address,
            }
        }
        _ => address,
    }
}

/// `object` is a new object, which is what it is by its definition.
fn new_object(facts: &mut Facts, object: NodeId) {
    facts.set_object(object);
    facts.set_refinement(object, object);
}

/// The code is known to be valid from here on, which what is known about
/// shapes relies on.
fn validate(facts: &mut Facts, stable_shapes: &[CellId], decisions: &mut Decisions) {
    facts.validate(stable_shapes, &mut decisions.stable_shapes);
}

/// A load of `location` by `node`: replaced by what the location is known
/// to hold (returning true), or what it holds from now on.
fn reuse_contents(facts: &mut Facts, location: Location, node: NodeId, decisions: &mut Decisions) -> bool {
    match facts.contents(location) {
        Some(value) => {
            decisions.replacements.replace(node, value);
            true
        }
        None => {
            facts.set_contents(location, node);
            false
        }
    }
}