|
| 1 | +package dev.rdh.bf.opt |
| 2 | + |
| 3 | +import dev.rdh.bf.BFOperation |
| 4 | +import dev.rdh.bf.Copy |
| 5 | +import dev.rdh.bf.PointerMove |
| 6 | +import dev.rdh.bf.SetToConstant |
| 7 | +import dev.rdh.bf.ValueChange |
| 8 | + |
| 9 | +/** |
| 10 | + * Final peephole pass that merges the current operation with the previously emitted one. |
| 11 | + */ |
| 12 | +internal object OpMerger : OptimisationPass { |
| 13 | + override fun run(program: MutableList<BFOperation>) { |
| 14 | + val merged = mutableListOf<BFOperation>() |
| 15 | + |
| 16 | + for (op in program) { |
| 17 | + var current = op |
| 18 | + |
| 19 | + while (merged.isNotEmpty()) { |
| 20 | + val previous = merged.last() |
| 21 | + val combined = tryMerge(previous, current) ?: break |
| 22 | + merged.removeLast() |
| 23 | + current = combined |
| 24 | + } |
| 25 | + |
| 26 | + when (current) { |
| 27 | + is PointerMove -> if (current.value != 0) merged += current |
| 28 | + is ValueChange -> if (current.value != 0) merged += current |
| 29 | + else -> merged += current |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + program.clear() |
| 34 | + program.addAll(merged) |
| 35 | + } |
| 36 | + |
| 37 | + private fun tryMerge(previous: BFOperation, current: BFOperation): BFOperation? { |
| 38 | + if (previous is PointerMove && current is PointerMove) { |
| 39 | + return PointerMove(previous.value + current.value) |
| 40 | + } |
| 41 | + |
| 42 | + if (previous is ValueChange && current is ValueChange && previous.offset == current.offset) { |
| 43 | + return ValueChange(previous.value + current.value, previous.offset) |
| 44 | + } |
| 45 | + |
| 46 | + if (previous is SetToConstant && current is ValueChange && previous.offset == current.offset) { |
| 47 | + val value = (previous.value.toInt() + current.value).toUByte() |
| 48 | + return SetToConstant(value = value, offset = previous.offset) |
| 49 | + } |
| 50 | + |
| 51 | + if (current is SetToConstant && previous.overwritesCell(current.offset)) { |
| 52 | + return current |
| 53 | + } |
| 54 | + |
| 55 | + return null |
| 56 | + } |
| 57 | + |
| 58 | + private fun BFOperation.overwritesCell(offset: Int): Boolean = when (this) { |
| 59 | + is SetToConstant -> this.offset == offset |
| 60 | + is ValueChange -> this.offset == offset |
| 61 | + is Copy -> this.offset == offset |
| 62 | + else -> false |
| 63 | + } |
| 64 | +} |
0 commit comments