Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[compiler] Optimize instruction reordering #29882

Merged
merged 8 commits into from
Jun 21, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,20 @@
HIRFunction,
IdentifierId,
Instruction,
InstructionId,
MutableRange,

Check failure on line 17 in compiler/packages/babel-plugin-react-compiler/src/Optimization/InstructionReordering.ts

View workflow job for this annotation

GitHub Actions / Lint babel-plugin-react-compiler

'MutableRange' is defined but never used. Allowed unused vars must match /^_/u
josephsavona marked this conversation as resolved.
Show resolved Hide resolved
Place,
isExpressionBlockKind,
makeInstructionId,
markInstructionIds,
} from "../HIR";
import { printInstruction } from "../HIR/PrintHIR";
import {
eachInstructionLValue,
eachInstructionValueLValue,
eachInstructionValueOperand,
eachTerminalOperand,
terminalFallthrough,

Check failure on line 29 in compiler/packages/babel-plugin-react-compiler/src/Optimization/InstructionReordering.ts

View workflow job for this annotation

GitHub Actions / Lint babel-plugin-react-compiler

'terminalFallthrough' is defined but never used. Allowed unused vars must match /^_/u
} from "../HIR/visitors";
import { mayAllocate } from "../ReactiveScopes/InferReactiveScopeVariables";
import { getOrInsertWith } from "../Utils/utils";
Expand Down Expand Up @@ -69,8 +75,9 @@
export function instructionReordering(fn: HIRFunction): void {
// Shared nodes are emitted when they are first used
const shared: Nodes = new Map();
const references = findReferencedRangeOfTemporaries(fn);
for (const [, block] of fn.body.blocks) {
reorderBlock(fn.env, block, shared);
reorderBlock(fn.env, block, shared, references);
}
CompilerError.invariant(shared.size === 0, {
reason: `InstructionReordering: expected all reorderable nodes to have been emitted`,
Expand All @@ -91,10 +98,76 @@
depth: number | null;
};

// Inclusive start and end
type References = {
accessedRanges: AccessedRanges;
lastAssignments: LastAssignments;
};
type LastAssignments = Map<string, InstructionId>;
type AccessedRanges = Map<IdentifierId, Range>;
type Range = { start: InstructionId; end: InstructionId };
enum ReferenceKind {
Read,
Write,
}
function findReferencedRangeOfTemporaries(fn: HIRFunction): References {
const accessedRanges: AccessedRanges = new Map();
const lastAssignments: LastAssignments = new Map();
function reference(
instr: InstructionId,
place: Place,
kind: ReferenceKind
): void {
if (
place.identifier.name !== null &&
place.identifier.name.kind === "named"
) {
if (kind === ReferenceKind.Write) {
const name = place.identifier.name.value;
const previous = lastAssignments.get(name);
if (previous === undefined) {
lastAssignments.set(name, instr);
} else {
lastAssignments.set(
name,
makeInstructionId(Math.max(previous, instr))
);
}
}
return;
} else if (kind === ReferenceKind.Read) {
const range = getOrInsertWith(
accessedRanges,
place.identifier.id,
() => ({
start: instr,
end: instr,
})
);
range.end = instr;
}
}
for (const [, block] of fn.body.blocks) {
for (const instr of block.instructions) {
for (const operand of eachInstructionValueLValue(instr.value)) {
reference(instr.id, operand, ReferenceKind.Read);
}
for (const lvalue of eachInstructionLValue(instr)) {
reference(instr.id, lvalue, ReferenceKind.Write);
}
}
for (const operand of eachTerminalOperand(block.terminal)) {
reference(block.terminal.id, operand, ReferenceKind.Read);
}
}
return { accessedRanges, lastAssignments };
}

function reorderBlock(
env: Environment,
block: BasicBlock,
shared: Nodes
shared: Nodes,
references: References
): void {
const locals: Nodes = new Map();
const named: Map<string, IdentifierId> = new Map();
Expand All @@ -116,7 +189,7 @@
* Ensure non-reoderable instructions have their order retained by
* adding explicit dependencies to the previous such instruction.
*/
if (getReoderability(instr) === Reorderability.Nonreorderable) {
if (getReoderability(instr, references) === Reorderability.Nonreorderable) {
if (previous !== null) {
node.dependencies.add(previous);
}
Expand Down Expand Up @@ -220,7 +293,8 @@
}
CompilerError.invariant(
node.instruction != null &&
getReoderability(node.instruction) === Reorderability.Reorderable,
getReoderability(node.instruction, references) ===
Reorderability.Reorderable,
{
reason: `Expected all remaining instructions to be reorderable`,
loc: node.instruction?.loc ?? block.terminal.loc,
Expand Down Expand Up @@ -334,7 +408,10 @@
Reorderable,
Nonreorderable,
}
function getReoderability(instr: Instruction): Reorderability {
function getReoderability(
instr: Instruction,
references: References
): Reorderability {
switch (instr.value.kind) {
case "JsxExpression":
case "JsxFragment":
Expand All @@ -346,6 +423,23 @@
case "UnaryExpression": {
return Reorderability.Reorderable;
}
case "LoadLocal": {
const name = instr.value.place.identifier.name;
if (name !== null && name.kind === "named") {
const lastAssignment = references.lastAssignments.get(name.value);
const range = references.accessedRanges.get(instr.lvalue.identifier.id);
if (
lastAssignment !== undefined &&
lastAssignment < instr.id &&
range !== undefined &&
range.end === range.start // this LoadLocal is used exactly once
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think I understand what the accessedRanges conditions are enforcing here, or why it matters that a local is used exactly once. It seems like it would be safe to reorder a load to be anywhere between the last place that the local was written to (which this pass enforces) and the first place that the load's lvalue is read from -- which I would expect is enforced by the existing dependency analysis. I'm sure there's something I'm missing here though!

Also -- if the thing we want to validate is just that the local is used exactly once, maybe rather than building an accessed range for the local, we could just count the number of reads?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah i was on the fence about checking the accessed range or just counting reads. Without some form of this check i saw some cases where a LoadLocal was used twice, but once was at the wrong block scope level, so it would be invalid to reorder to the first usage. I'll update this to just count reads and only reorder for LoadLocals whose temp is used exactly once.

) {
console.log(`reorderable: ${name.value}`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: should we remove the console.log?

return Reorderability.Reorderable;
}
}
return Reorderability.Nonreorderable;
}
default: {
return Reorderability.Nonreorderable;
}
Expand Down
Loading