[HIR] Naive implementation of pruneUnusedLabels in HIR

ghstack-source-id: 6d55db3d5c0fd7736a59d48c6afb2de9b5729d16
Pull Request resolved: https://github.com/facebook/react-forget/pull/2866
This commit is contained in:
Mofei Zhang committed 2024-04-23 10:18:50 +01:00
1 parent 555100ca83
commit 40474b8eaf
3 files changed
+77

No files matched your search

@@ -17,6 +17,7 @@ import {
assertValidMutableRanges,
lower,
mergeConsecutiveBlocks,
pruneUnusedLabelsHIR,
} from "../HIR";
import {
Environment,
@@ -236,6 +237,13 @@ function* runWithEnvironment(
});
if (env.config.enableAlignReactiveScopesToBlockScopesHIR) {
pruneUnusedLabelsHIR(hir);
yield log({
kind: "hir",
name: "PruneUnusedLabelsHIR",
value: hir,
});
alignReactiveScopesToBlockScopesHIR(hir);
yield log({
kind: "hir",
@@ -0,0 +1,68 @@
import { CompilerError } from "..";
import { BlockId, GotoVariant, HIRFunction } from "./HIR";
export function pruneUnusedLabelsHIR(fn: HIRFunction): void {
const merged: Array<{
label: BlockId;
next: BlockId;
fallthrough: BlockId;
}> = [];
for (const [blockId, block] of fn.body.blocks) {
const terminal = block.terminal;
if (terminal.kind === "label") {
const { block: nextId, fallthrough: fallthroughId } = terminal;
const next = fn.body.blocks.get(nextId)!;
const fallthrough = fn.body.blocks.get(fallthroughId)!;
if (
next.terminal.kind === "goto" &&
next.terminal.variant === GotoVariant.Break &&
next.terminal.block === fallthroughId
) {
if (next.kind === "block" && fallthrough.kind === "block") {
// Only merge normal block types
merged.push({
label: blockId,
next: nextId,
fallthrough: fallthroughId,
});
}
}
}
}
for (const {
label: labelId,
next: nextId,
fallthrough: fallthroughId,
} of merged) {
const label = fn.body.blocks.get(labelId)!;
const next = fn.body.blocks.get(nextId)!;
const fallthrough = fn.body.blocks.get(fallthroughId)!;
// Merge block and fallthrough
CompilerError.invariant(
next.phis.size === 0 && fallthrough.phis.size === 0,
{
reason: "Unexpected phis when merging label blocks",
loc: label.terminal.loc,
}
);
CompilerError.invariant(
next.preds.size === 1 &&
fallthrough.preds.size === 1 &&
next.preds.has(labelId) &&
fallthrough.preds.has(nextId),
{
reason: "Unexpected block predecessors when merging label blocks",
loc: label.terminal.loc,
}
);
label.instructions.push(...next.instructions, ...fallthrough.instructions);
label.terminal = fallthrough.terminal;
fn.body.blocks.delete(nextId);
fn.body.blocks.delete(fallthroughId);
}
}
@@ -27,3 +27,4 @@ export {
} from "./HIRBuilder";
export { mergeConsecutiveBlocks } from "./MergeConsecutiveBlocks";
export { printFunction, printHIR } from "./PrintHIR";
export { pruneUnusedLabelsHIR } from "./PruneUnusedLabelsHIR";