diff --git a/compiler/packages/babel-plugin-react-forget/src/HIR/PrintHIR.ts b/compiler/packages/babel-plugin-react-forget/src/HIR/PrintHIR.ts index 580b612955..f0d78a51e2 100644 --- a/compiler/packages/babel-plugin-react-forget/src/HIR/PrintHIR.ts +++ b/compiler/packages/babel-plugin-react-forget/src/HIR/PrintHIR.ts @@ -675,8 +675,9 @@ export function printPlace(place: Place): string { " ", printIdentifier(place.identifier), printMutableRange(place.identifier), + printType(place.identifier.type), + place.reactive ? "{reactive}" : null, ]; - items.push(printType(place.identifier.type)); return items.filter((x) => x != null).join(""); } diff --git a/compiler/packages/babel-plugin-react-forget/src/Inference/InferReactivePlaces.ts b/compiler/packages/babel-plugin-react-forget/src/Inference/InferReactivePlaces.ts index aa96ec7bb9..040741c6b4 100644 --- a/compiler/packages/babel-plugin-react-forget/src/Inference/InferReactivePlaces.ts +++ b/compiler/packages/babel-plugin-react-forget/src/Inference/InferReactivePlaces.ts @@ -22,7 +22,6 @@ import { eachInstructionValueOperand, eachTerminalOperand, } from "../HIR/visitors"; -import { hasBackEdge } from "../Optimization/DeadCodeElimination"; import { assertExhaustive } from "../Utils/utils"; /** @@ -94,9 +93,9 @@ export function inferReactivePlaces(fn: HIRFunction): void { const postDominators = computePostDominatorTree(fn, { includeThrowsAsExitNode: false, }); - const hasLoop = hasBackEdge(fn); const postDominatorFrontierCache = new Map>(); do { + const identifierMapping = new Map(); for (const [, block] of fn.body.blocks) { for (const phi of block.phis) { if (reactiveIdentifiers.isReactiveIdentifier(phi.id)) { @@ -194,6 +193,10 @@ export function inferReactivePlaces(fn: HIRFunction): void { case Effect.Store: case Effect.ConditionallyMutate: case Effect.Mutate: { + const resolvedId = identifierMapping.get(operand.identifier); + if (resolvedId !== undefined) { + reactiveIdentifiers.markReactiveIdentifier(resolvedId); + } reactiveIdentifiers.markReactive(operand); break; } @@ -219,12 +222,37 @@ export function inferReactivePlaces(fn: HIRFunction): void { } } } + + switch (value.kind) { + case "LoadLocal": { + identifierMapping.set( + instruction.lvalue.identifier, + value.place.identifier + ); + break; + } + case "PropertyLoad": + case "ComputedLoad": { + const resolvedId = + identifierMapping.get(value.object.identifier) ?? + value.object.identifier; + identifierMapping.set(instruction.lvalue.identifier, resolvedId); + break; + } + case "LoadContext": { + identifierMapping.set( + instruction.lvalue.identifier, + value.place.identifier + ); + break; + } + } } for (const operand of eachTerminalOperand(block.terminal)) { reactiveIdentifiers.isReactive(operand); } } - } while (reactiveIdentifiers.snapshot() && hasLoop); + } while (reactiveIdentifiers.snapshot()); } /** diff --git a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/CollectReactiveIdentifiers.ts b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/CollectReactiveIdentifiers.ts new file mode 100644 index 0000000000..c9f3fc8d0b --- /dev/null +++ b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/CollectReactiveIdentifiers.ts @@ -0,0 +1,53 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { + IdentifierId, + InstructionId, + Place, + ReactiveFunction, +} from "../HIR/HIR"; +import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors"; + +class Visitor extends ReactiveFunctionVisitor> { + // Visitors don't visit lvalues as places by default, but we want to visit all places to + // check for reactivity + override visitLValue( + id: InstructionId, + lvalue: Place, + state: Set + ): void { + this.visitPlace(id, lvalue, state); + } + + // This visitor only infers data dependencies and does not account for control dependencies + // where a variable may be assigned a different value based on some conditional, eg via two + // different paths of an if statement. + override visitPlace( + _id: InstructionId, + place: Place, + state: Set + ): void { + if (place.reactive) { + state.add(place.identifier.id); + } + } +} + +/** + * Computes a set of identifiers which are reactive, using the analysis previously performed + * in `InferReactivePlaces`. + */ +export function collectReactiveIdentifiers( + fn: ReactiveFunction +): Set { + const visitor = new Visitor(); + const state = new Set(); + visitReactiveFunction(fn, visitor, state); + + return state; +} diff --git a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/InferReactiveIdentifiers.ts b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/InferReactiveIdentifiers.ts deleted file mode 100644 index ff7ea44404..0000000000 --- a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/InferReactiveIdentifiers.ts +++ /dev/null @@ -1,226 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -import { CompilerError } from "../CompilerError"; -import { Environment } from "../HIR"; -import { - Effect, - IdentifierId, - InstructionId, - Place, - ReactiveFunction, - ReactiveInstruction, - getHookKind, -} from "../HIR/HIR"; -import { eachInstructionLValue } from "../HIR/visitors"; -import { assertExhaustive } from "../Utils/utils"; -import { - ReactiveFunctionVisitor, - eachReactiveValueOperand, - visitReactiveFunction, -} from "./visitors"; - -type IdentifierReactivity = Map; - -class State { - env: Environment; - reactivityMap: IdentifierReactivity = new Map(); - temporaries: Map = new Map(); - - constructor(env: Environment) { - this.env = env; - } -} - -class Visitor extends ReactiveFunctionVisitor { - override visitLValue( - _id: InstructionId, - _lvalue: Place, - _state: State - ): void { - this.visitPlace(_id, _lvalue, _state); - } - override visitPlace(_id: InstructionId, _place: Place, _state: State): void { - if (_place.reactive) { - _state.reactivityMap.set(_place.identifier.id, _place.reactive); - } - } - - override visitInstruction(instr: ReactiveInstruction, state: State): void { - this.traverseInstruction(instr, state); - const lval = instr.lvalue; - if (lval == null) { - return; - } - const { value } = instr; - let hasReactiveInput = false; - // Globals are currently treated as non-reactive this happens implicitly because LoadGlobal - // has no operands which can be registered as reactive. - // Consider adding an option to declare whether a given global can be reactive or not, or - // a more general "treat all globals as reactive" flag. - for (const operand of eachReactiveValueOperand(value)) { - if (operand.effect === Effect.Store) { - continue; - } - const ownId = operand.identifier.id; - const resolvedId = state.temporaries.get(ownId); - // We need to check reactivity of both the operand and its resolved source (if operand is - // produced by a LoadLocal / PropertyLoad / ComputedLoad). Both the operand and its source - // can have reactivity. e.g. - // ```js - // const o = makeObject(); // source has no reactivity - // const x = o[props.x]; // x is reactive - // ``` - if ( - state.reactivityMap.get(ownId) || - (resolvedId && state.reactivityMap.get(resolvedId)) - ) { - hasReactiveInput = true; - break; - } - } - if (!hasReactiveInput) { - if ( - instr.value.kind === "CallExpression" && - getHookKind(state.env, instr.value.callee.identifier) != null - ) { - // Hooks cannot be memoized. Even if they do not accept any reactive inputs, - // they are not guaranteed to memoize their return value, and their result - // must be assumed to be reactive. - // TODO: use types or an opt-in registry of custom hook information to - // allow treating safe hooks as non-reactive. - hasReactiveInput = true; - } else if ( - instr.value.kind === "MethodCall" && - getHookKind(state.env, instr.value.property.identifier) != null - ) { - // Same as above, but for invoking hooks via a property load such as `React.useState()` - hasReactiveInput = true; - } - } - state.reactivityMap.set(lval.identifier.id, hasReactiveInput); - - if (hasReactiveInput) { - for (const lvalue of eachInstructionLValue(instr)) { - state.reactivityMap.set(lvalue.identifier.id, true); - } - // all mutating effects must also be marked as reactive - for (const operand of eachReactiveValueOperand(value)) { - switch (operand.effect) { - case Effect.Capture: - case Effect.Store: - case Effect.ConditionallyMutate: - case Effect.Mutate: { - const resolvedId: IdentifierId = - state.temporaries.get(operand.identifier.id) ?? - operand.identifier.id; - state.reactivityMap.set(resolvedId, true); - break; - } - case Effect.Freeze: - case Effect.Read: { - // no-op - break; - } - case Effect.Unknown: { - CompilerError.invariant(false, { - reason: "Unexpected unknown effect", - description: null, - loc: operand.loc, - suggestions: null, - }); - } - default: { - assertExhaustive( - operand.effect, - `Unexpected effect kind '${operand.effect}'` - ); - } - } - } - } - if (instr.lvalue !== null) { - if (instr.value.kind === "LoadLocal") { - state.temporaries.set( - instr.lvalue.identifier.id, - instr.value.place.identifier.id - ); - } else if ( - instr.value.kind === "PropertyLoad" || - instr.value.kind === "ComputedLoad" - ) { - const resolvedId = - state.temporaries.get(instr.value.object.identifier.id) ?? - instr.value.object.identifier.id; - state.temporaries.set(instr.lvalue.identifier.id, resolvedId); - } else if (instr.value.kind === "LoadContext") { - state.temporaries.set( - instr.lvalue.identifier.id, - instr.value.place.identifier.id - ); - } - } - } -} -/** - * Computes a map of {@link Place} -> reactivityMap. A Place is reactive if any - * operant used in its construction is reactive. Sources of reactivity are - * {@link ReactiveFunction.params} and HookCall return values (TODO). - * Free values are currently not populated. - * - * This relies on alias analysis done by InferReactiveScopeVariables, which - * creates reactive scopes for variables that mutate together. If one value - * declared in a scope is Reactive, then the rest are marked as reactive as - * well. - * e.g. - * ```javascript - * function foo(props) { - * let x = {}; - * let y = []; - * x.y = y; - * y.push(props.a) - * // references to x are reactive here - * } - * ``` - * This an overestimate when two identifiers have overlapping scope, but - * one is not actually reactive. However, since the same ReactiveBlock now - * produces both identifiers, they are effectively both reactive (i.e. - * object creation is not stable) - * e.g. - * ```javascript - * function bar(props) { - * // x and y have overlapping mutableRanges, so they share a ReactiveScope - * // (even though they are not aliased together) - * // technically y has no reactive inputs, but it becomes non-stable due to - * // sharing a ReactiveScopeBlock with x - * let x = {}; - * let y = []; - * mutate1(x, props); - * mutate2(y); - * } - * ``` - */ -export function inferReactiveIdentifiers( - fn: ReactiveFunction -): Set { - const visitor = new Visitor(); - const state = new State(fn.env); - for (const param of fn.params) { - if (param.kind === "Identifier") { - state.reactivityMap.set(param.identifier.id, true); - } else { - state.reactivityMap.set(param.place.identifier.id, true); - } - } - visitReactiveFunction(fn, visitor, state); - - const result = new Set(); - state.reactivityMap.forEach((isReactive, id) => { - if (isReactive) result.add(id); - }); - return result; -} diff --git a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/PruneNonReactiveDependencies.ts b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/PruneNonReactiveDependencies.ts index 7a148515ff..1c726557b7 100644 --- a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/PruneNonReactiveDependencies.ts +++ b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/PruneNonReactiveDependencies.ts @@ -11,7 +11,7 @@ import { ReactiveScopeBlock, isSetStateType, } from "../HIR"; -import { inferReactiveIdentifiers } from "./InferReactiveIdentifiers"; +import { collectReactiveIdentifiers } from "./CollectReactiveIdentifiers"; import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors"; /** @@ -21,14 +21,17 @@ import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors"; * This pass prunes dependencies that are guaranteed to be non-reactive. */ export function pruneNonReactiveDependencies(fn: ReactiveFunction): void { - const state = inferReactiveIdentifiers(fn); - visitReactiveFunction(fn, new Visitor(), state); + const reactiveIdentifiers = collectReactiveIdentifiers(fn); + visitReactiveFunction(fn, new Visitor(), reactiveIdentifiers); } -type State = Set; +type ReactiveIdentifiers = Set; -class Visitor extends ReactiveFunctionVisitor { - override visitScope(scope: ReactiveScopeBlock, state: State): void { +class Visitor extends ReactiveFunctionVisitor { + override visitScope( + scope: ReactiveScopeBlock, + state: ReactiveIdentifiers + ): void { this.traverseScope(scope, state); for (const dep of scope.scope.dependencies) { const isReactive =