Skip to content

Commit

Permalink
perf: pre-compute EQ, NEQ, UNM, and BNOT with literals
Browse files Browse the repository at this point in the history
  • Loading branch information
R-unic committed Jan 21, 2025
1 parent a5953a5 commit 263bf44
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions Heir/CodeGeneration/BytecodeOptimizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,25 @@ public List<Instruction> Optimize()
// pre-compute the result of operations using only literal values
// FUCK THIS CODE

// unary
{
if (instruction.Operand is long or ulong or int or uint or short or ushort or byte or sbyte or double or float or decimal &&
PeekBytecode(1) is
{
OpCode: OpCode.UNM or OpCode.BNOT
} operation)
{
var result = operation.OpCode == OpCode.UNM
? -Convert.ToDouble(instruction.Operand)
: ~Convert.ToInt64(instruction.Operand);

Advance();
Advance();
return instruction.WithOperand(result);
}
}

// binary
{
if (instruction.Operand is long or ulong or int or uint or short or ushort or byte or sbyte or double or float or decimal &&
PeekBytecode(1) is
Expand Down Expand Up @@ -116,6 +135,29 @@ public List<Instruction> Optimize()
return instruction.WithOperand(result);
}
}
{
if (instruction.Operand is var left &&
PeekBytecode(1) is
{
OpCode: OpCode.PUSH,
Operand: var right
} &&
PeekBytecode(2) is
{
OpCode: OpCode.EQ or OpCode.NEQ
} operation)
{
var equalityComparer = EqualityComparer<object>.Default;
var result = equalityComparer.Equals(left, right);
if (operation.OpCode == OpCode.NEQ)
result = !result;

Advance();
Advance();
Advance();
return instruction.WithOperand(result);
}
}

break;
}
Expand Down

0 comments on commit 263bf44

Please sign in to comment.