Skip to content

Commit cae4d86

Browse files
Optimize (local.set $x (i32.const $c)) to avoid using a const slot
1 parent 72cb0ce commit cae4d86

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

Sources/WasmKit/Translator.swift

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1460,9 +1460,24 @@ struct InstructionTranslator<Context: TranslatorContext>: InstructionVisitor {
14601460
mutating func visitLocalSetOrTee(localIndex: UInt32, isTee: Bool) throws {
14611461
preserveLocalsOnStack(localIndex)
14621462
let type = try locals.type(of: localIndex)
1463-
guard let value = try popVRegOperand(type) else { return }
1464-
guard try controlStack.currentFrame().reachable else { return }
14651463
let result = localReg(localIndex)
1464+
1465+
guard let op = try popOperand(type) else { return }
1466+
1467+
if case .const(let slotIndex, _) = op {
1468+
// Optimize (local.set $x (i32.const $c)) to reg:$x = 42 rather than through const slot
1469+
let value = constantSlots.values[slotIndex]
1470+
let is32Bit = type == .i32 || type == .f32
1471+
if is32Bit {
1472+
emit(.const32(Instruction.Const32Operand(value: UInt32(value.storage), result: LVReg(result))))
1473+
} else {
1474+
emit(.const64(Instruction.Const64Operand(value: value, result: LLVReg(result))))
1475+
}
1476+
return
1477+
}
1478+
1479+
let value = ensureOnVReg(op)
1480+
guard try controlStack.currentFrame().reachable else { return }
14661481
if !isTee, iseqBuilder.relinkLastInstructionResult(result) {
14671482
// Good news, copyStack is optimized out :)
14681483
return

0 commit comments

Comments
 (0)