From 90ee663269b4b318be5ebfa256cf47ba4292f22f Mon Sep 17 00:00:00 2001 From: murdoa Date: Sat, 10 Oct 2026 19:36:23 +0100 Subject: [PATCH] perf(core): simplify decoder and execution datapaths Reuse the priority-selected decoder lane match, separate search-stage clears, and use parallel operand selectors. Split RV64 add/sub into carry-select halves without adding cycles or changing defaults. Adapt the cycle-neutral subset of local 5ec678377fde4d36c721023490c58b3fa85dc364, retaining upstream rs3 index-only handling. Add identical-behavior decoder and arithmetic regression controls. Validate with 252 paired cases per side, RTL simulation, component equivalence, comparative Xilinx synthesis, and eight production Nix builds. No routed timing or board-performance claim. --- packages/river_hdl/lib/src/core/decoder.dart | 68 +++----- packages/river_hdl/lib/src/core/exec.dart | 105 ++++++------ .../river_hdl/lib/src/core/microcode_alu.dart | 16 +- .../test/core/decoder_lane_match_test.dart | 154 ++++++++++++++++++ .../test/m/microcode_alu_carry_test.dart | 63 +++++++ 5 files changed, 304 insertions(+), 102 deletions(-) create mode 100644 packages/river_hdl/test/core/decoder_lane_match_test.dart create mode 100644 packages/river_hdl/test/m/microcode_alu_carry_test.dart diff --git a/packages/river_hdl/lib/src/core/decoder.dart b/packages/river_hdl/lib/src/core/decoder.dart index 8da214f..8aee62c 100644 --- a/packages/river_hdl/lib/src/core/decoder.dart +++ b/packages/river_hdl/lib/src/core/decoder.dart @@ -407,10 +407,18 @@ class DynamicInstructionDecoder extends InstructionDecoder { return pm & nzf & zf; } + final laneMatches = [for (var l = 0; l < lanes; l++) laneMatch(laneRow(l))]; + var selectedMatch = + laneMatches.last & rowField(laneRow(lanes - 1), 'mask').neq(0); var selData = laneRow(lanes - 1); for (var l = lanes - 2; l >= 0; l--) { + selectedMatch = mux( + laneMatches[l], + rowField(laneRow(l), 'mask').neq(0), + selectedMatch, + ); selData = mux( - laneMatch(laneRow(l)), + laneMatches[l], laneRow(l), selData, ).named('decodeSelData_$l'); @@ -451,20 +459,9 @@ class DynamicInstructionDecoder extends InstructionDecoder { .toList(); final opIdxWidth = pattern['opIndex']!.width; - final nzfMatch = mux( - pattern['nzfMask']!.neq(0), - (instr & pattern['nzfMask']!).neq(0), - Const(1), - ).named('nzfMatch'); - final zfMatch = mux( - pattern['zfMask']!.neq(0), - (instr & pattern['zfMask']!).eq(0), - Const(1), - ).named('zfMatch'); - - final patternMatch = (instr & pattern['mask']!) - .eq(pattern['value']!) - .named('patternMatch'); + // Carry the winning lane's match alongside its row instead of matching + // the priority-muxed row again. Preserve zero-mask tail rejection and the + // same lowest-lane priority for both the metadata and match decision. // STAGE 2 field extraction, sourced from the REGISTERED match result. This // is the identical field logic as before, just driven by _matchInstr / @@ -512,14 +509,9 @@ class DynamicInstructionDecoder extends InstructionDecoder { ]), ]; - // "No valid decode this cycle" output clear (fresh Conditionals each call). - List clearOutputs() => [ - done < 0, - valid < 0, - index < 0, - ...instrTypeMap.entries.map((entry) => entry.value < 0), - ...fields.entries.map((entry) => entry.value < 0), - ]; + // Only completion status depends on the ROM match. Clear search-stage + // data independently so the match cone does not drive every field bit. + List clearOutputs() => [done < 0, valid < 0]; // First cycle of a NEW instruction: the fetch holds `pc_in` stable across the // multi-cycle scan, so `pc_in != pc_out` (pc_out is last cycle's pc_in) is @@ -547,6 +539,9 @@ class DynamicInstructionDecoder extends InstructionDecoder { then: [microcodeRead.en < 0, ...computeFields()], orElse: [ // STAGE 1: search the microcode ROM, one packed row per cycle. + index < 0, + ...instrTypeMap.entries.map((entry) => entry.value < 0), + ...fields.entries.map((entry) => entry.value < 0), microcodeRead.en < 1, // _counter is sized for the unpacked pattern count; the packed ROM // has ceil(patterns/lanes) words, so its address port is narrower. @@ -576,10 +571,7 @@ class DynamicInstructionDecoder extends InstructionDecoder { microcodeRead.valid, then: [ If( - patternMatch & - nzfMatch & - zfMatch & - pattern['mask']!.neq(0), + selectedMatch, // Match: latch ONLY the result; the field Cases run next // cycle in stage 2. done/valid stay low until then. Exec // already tolerates variable decode latency (the ROM @@ -630,17 +622,7 @@ class DynamicInstructionDecoder extends InstructionDecoder { then: [ If( _rescanned, - then: [ - done < 1, - valid < 0, - index < 0, - ...instrTypeMap.entries.map( - (entry) => entry.value < 0, - ), - ...fields.entries.map( - (entry) => entry.value < 0, - ), - ], + then: [done < 1, valid < 0], orElse: [ _counter < 0, _rescanned < 1, @@ -656,15 +638,7 @@ class DynamicInstructionDecoder extends InstructionDecoder { ], ), ], - orElse: [ - done < 1, - valid < 0, - index < 0, - ...instrTypeMap.entries.map( - (entry) => entry.value < 0, - ), - ...fields.entries.map((entry) => entry.value < 0), - ], + orElse: [done < 1, valid < 0], ), ], orElse: clearOutputs(), diff --git a/packages/river_hdl/lib/src/core/exec.dart b/packages/river_hdl/lib/src/core/exec.dart index eee18ab..bd8f40d 100644 --- a/packages/river_hdl/lib/src/core/exec.dart +++ b/packages/river_hdl/lib/src/core/exec.dart @@ -2031,67 +2031,64 @@ class DynamicExecutionUnit extends ExecutionUnit { .slice(MicroOp.functRange.end, MicroOp.functRange.start) .named('mopFunct'); - Logic readSource(Logic source) => mux( - source.eq(Const(MicroOpSource.imm, width: MicroOpSource.width)), - imm, - mux( - source.eq(Const(MicroOpSource.alu, width: MicroOpSource.width)), - alu, - mux( - source.eq(Const(MicroOpSource.rs1, width: MicroOpSource.width)), - rs1, - mux( - source.eq(Const(MicroOpSource.rs2, width: MicroOpSource.width)), - rs2, - mux( - source.eq(Const(MicroOpSource.rd, width: MicroOpSource.width)), - rd, - nextPc, - ), - ), + Logic readSource(Logic source) { + final value = Logic(name: 'sourceValue', width: mxlen.size); + Combinational([ + Case( + source, + [ + for (final entry in { + MicroOpSource.imm: imm, + MicroOpSource.alu: alu, + MicroOpSource.rs1: rs1, + MicroOpSource.rs2: rs2, + MicroOpSource.rd: rd, + }.entries) + CaseItem(Const(entry.key, width: MicroOpSource.width), [ + value < entry.value, + ]), + ], + defaultItem: [value < nextPc], ), - ), - ); + ]); + return value; + } // rs3, the third source of an r4-type fused multiply-add, exists only when // the ISA carries such an op. Its decode field then appears in [fields]. final hasRs3 = fields.containsKey('rs3'); - Logic readField(Logic field, {bool register = true}) => mux( - field.eq(Const(MicroOpField.rd, width: MicroOpField.width)), - (register ? rd : fields['rd']!).zeroExtend(mxlen.size), - mux( - field.eq(Const(MicroOpField.rs1, width: MicroOpField.width)), - (register ? rs1 : fields['rs1']!).zeroExtend(mxlen.size), - mux( - field.eq(Const(MicroOpField.rs2, width: MicroOpField.width)), - (register ? rs2 : fields['rs2']!).zeroExtend(mxlen.size), - mux( - field.eq(Const(MicroOpField.imm, width: MicroOpField.width)), - register ? imm : fields['imm']!, - mux( - field.eq(Const(MicroOpField.pc, width: MicroOpField.width)), - nextPc, - // rs3 is named ONLY as a register INDEX, by the extra ReadRegister - // that a fused multiply-add carries. The FPU takes its third - // operand straight from the rs3 latch, so no XLEN-wide data path - // ever selects rs3. Folding rs3 into the decode-field variant only - // keeps the register variant, which is the wide one and has many - // more users, at its existing five-way mux. - (hasRs3 && !register) - ? mux( - field.eq( - Const(MicroOpField.rs3, width: MicroOpField.width), - ), - fields['rs3']!.zeroExtend(mxlen.size), - nextSp, - ) - : nextSp, - ), - ), + Logic readField(Logic field, {bool register = true}) { + final value = Logic(name: 'fieldValue', width: mxlen.size); + // Distinct field codes are parallel choices, not a priority mux chain. + // rs3 remains an INDEX-only source; the FPU uses its separate data latch. + final choices = { + MicroOpField.rd: (register ? rd : fields['rd']!).zeroExtend(mxlen.size), + MicroOpField.rs1: (register ? rs1 : fields['rs1']!).zeroExtend( + mxlen.size, ), - ), - ); + MicroOpField.rs2: (register ? rs2 : fields['rs2']!).zeroExtend( + mxlen.size, + ), + MicroOpField.imm: register ? imm : fields['imm']!, + MicroOpField.pc: nextPc, + if (hasRs3 && !register) + MicroOpField.rs3: fields['rs3']!.zeroExtend(mxlen.size), + }; + Combinational([ + Case( + field, + [ + for (final entry in choices.entries) + CaseItem(Const(entry.key, width: MicroOpField.width), [ + value < entry.value, + ]), + ], + defaultItem: [value < nextSp], + ), + ]); + return value; + } // Shared microcode-ALU operands: hoisted out of the ~19-arm funct Case so // synth infers ONE operand mux per side instead of one per arm (mux-bound). diff --git a/packages/river_hdl/lib/src/core/microcode_alu.dart b/packages/river_hdl/lib/src/core/microcode_alu.dart index b526335..2fc247f 100644 --- a/packages/river_hdl/lib/src/core/microcode_alu.dart +++ b/packages/river_hdl/lib/src/core/microcode_alu.dart @@ -33,7 +33,21 @@ class MicrocodeAlu extends Module { // ONE shared adder: add/sub/addw/subw. sub-family inverts b and carries in. final isSub = f(MicroOpAluFunct.sub) | f(MicroOpAluFunct.subw); - final sum = a + mux(isSub, ~b, b) + isSub.zeroExtend(xlen); + final addB = mux(isSub, ~b, b); + Logic sum; + if (xlen == 64) { + // Carry-select halves keep operand inversion off a full XLEN carry + // chain. Both upper carry outcomes are computed in parallel. + final low = + a.slice(31, 0).zeroExtend(33) + + addB.slice(31, 0).zeroExtend(33) + + isSub.zeroExtend(33); + final high0 = a.slice(63, 32) + addB.slice(63, 32); + final high1 = a.slice(63, 32) + addB.slice(63, 32) + Const(1, width: 32); + sum = [mux(low[32], high1, high0), low.slice(31, 0)].swizzle(); + } else { + sum = a + addB + isSub.zeroExtend(xlen); + } final sumW = sum.slice(31, 0).signExtend(xlen); // Bitwise. diff --git a/packages/river_hdl/test/core/decoder_lane_match_test.dart b/packages/river_hdl/test/core/decoder_lane_match_test.dart new file mode 100644 index 0000000..9da180d --- /dev/null +++ b/packages/river_hdl/test/core/decoder_lane_match_test.dart @@ -0,0 +1,154 @@ +import 'dart:async'; + +import 'package:river/river.dart'; +import 'package:river_hdl/river_hdl.dart'; +import 'package:rohd/rohd.dart'; +import 'package:test/test.dart'; + +/// Drive packed rows directly: the selected row and its match decision must +/// have identical priority, including zero/nonzero-field guards and padding. +void main() { + tearDown(() async { + await Simulator.endSimulation(); + await Simulator.reset(); + }); + + for (final mxlen in [RiscVMxlen.rv32, RiscVMxlen.rv64]) { + for (final lanes in [1, 2, 4, 8]) { + test('RV${mxlen.size} $lanes lanes preserve match priority', () async { + final rom = MicrocodeRom( + RiscVIsaConfig(mxlen: mxlen, extensions: [rv32i]), + ); + final patterns = rom.decodeLookup.values.toList(); + final first = patterns.first; + final second = patterns.firstWhere((p) => p.opIndex != first.opIndex); + final typeWidth = rom.typeStructs.length.bitLength; + final clk = SimpleClockGenerator(10).clk; + final reset = Logic()..put(1); + final enable = Logic()..put(0); + final instruction = Logic(width: 32)..put(0); + final port = DataPortInterface( + rom.patternWidth * lanes, + rom.decodeLookup.length.bitLength, + ); + port.data.put(0); + port.done.put(0); + port.valid.put(0); + final dut = DynamicInstructionDecoder( + clk, + reset, + enable, + instruction, + port, + microcode: rom, + mxlen: mxlen, + ); + await dut.build(); + + Simulator.setMaxSimTime(100000); + unawaited(Simulator.run()); + Future tick() async { + await clk.nextPosedge; + await clk.nextNegedge; + } + + OperationDecodePattern row(int index, {int nz = 0, int z = 0}) => + OperationDecodePattern(0x7f, 0x13, index, first.type, nz, z); + final miss = OperationDecodePattern( + 0x7f, + 0x33, + second.opIndex, + second.type, + 0, + 0, + ); + const padding = OperationDecodePattern(0, 0, 0, 0, 0, 0); + + Future check( + List rows, + int? expected, + ) async { + reset.put(1); + enable.put(0); + await tick(); + reset.put(0); + enable.put(1); + instruction.put(0x00108093); // addi x1, x1, 1 + var packed = BigInt.zero; + for (var lane = 0; lane < lanes; lane++) { + packed |= + rows[lane].encode(rom.opIndexWidth, typeWidth) << + (lane * rom.patternWidth); + } + port.data.put(packed); + port.valid.put(1); + port.done.put(0); + for (var i = 0; i < 3; i++) { + await tick(); + expect(dut.done.value.toBool(), isFalse); + } + port.done.put(1); + var completed = false; + for (var i = 0; i < 8; i++) { + // A one-lane nonmatch advances to a zero-filled ROM tail. + if (expected == null && i == 2) port.data.put(0); + await tick(); + if (dut.done.value.toBool()) { + completed = true; + break; + } + } + expect(completed, isTrue, reason: 'decoder must terminate'); + expect(dut.valid.value.toBool(), expected != null); + if (expected != null) { + expect(dut.index.value.toInt(), expected); + // Once committed, changes at the ROM input must not replace it. + port.data.put(0); + for (var i = 0; i < 3; i++) { + await tick(); + expect(dut.done.value.toBool(), isTrue); + expect(dut.valid.value.toBool(), isTrue); + expect(dut.index.value.toInt(), expected); + } + } + } + + // Every lane can win; no earlier nonmatching lane may steal its row. + for (var winner = 0; winner < lanes; winner++) { + final rows = List.filled(lanes, miss); + rows[winner] = row(first.opIndex); + await check(rows, first.opIndex); + } + // Multiple matches: lowest lane wins, not last matching lane. + await check([ + row(first.opIndex), + for (var lane = 1; lane < lanes; lane++) row(second.opIndex), + ], first.opIndex); + // Nonzero and zero-field predicates must travel with the row. + for (final guarded in [ + row(first.opIndex, nz: 1 << 20), + row(first.opIndex, z: 1 << 21), + ]) { + await check([ + guarded, + ...List.filled(lanes - 1, padding), + ], first.opIndex); + } + for (final rejected in [ + row(first.opIndex, nz: 1 << 21), + row(first.opIndex, z: 1 << 20), + ]) { + await check([rejected, ...List.filled(lanes - 1, padding)], null); + if (lanes > 1) { + await check([ + rejected, + row(second.opIndex), + ...List.filled(lanes - 2, padding), + ], second.opIndex); + } + } + await check(List.filled(lanes, padding), null); + }); + } + } +} diff --git a/packages/river_hdl/test/m/microcode_alu_carry_test.dart b/packages/river_hdl/test/m/microcode_alu_carry_test.dart new file mode 100644 index 0000000..2ef765a --- /dev/null +++ b/packages/river_hdl/test/m/microcode_alu_carry_test.dart @@ -0,0 +1,63 @@ +import 'dart:math'; + +import 'package:river/river.dart'; +import 'package:river_hdl/river_hdl.dart'; +import 'package:rohd/rohd.dart'; +import 'package:test/test.dart'; + +void main() { + for (final mxlen in [RiscVMxlen.rv32, RiscVMxlen.rv64]) { + test('RV${mxlen.size} shared add/sub carry boundaries', () async { + final width = mxlen.size; + final mask = (BigInt.one << width) - BigInt.one; + final a = Logic(width: width); + final b = Logic(width: width); + final funct = Logic(width: MicroOpAluFunct.width); + final dut = MicrocodeAlu(a, b, funct, mxlen: mxlen); + await dut.build(); + final edges = { + BigInt.zero, + BigInt.one, + mask, + mask - BigInt.one, + for (final bit in [15, 16, 30, 31, 32, width - 1]) + for (final delta in [-1, 0, 1]) + ((BigInt.one << bit) + BigInt.from(delta)) & mask, + }; + final random = Random(0x51a7); + BigInt operand() => + ((BigInt.from(random.nextInt(1 << 32)) << 32) | + BigInt.from(random.nextInt(1 << 32))) & + mask; + final pairs = [ + for (final x in edges) + for (final y in edges) (x, y), + for (var i = 0; i < 512; i++) (operand(), operand()), + ]; + for (final operation in [ + MicroOpAluFunct.add, + MicroOpAluFunct.sub, + if (width == 64) ...[MicroOpAluFunct.addw, MicroOpAluFunct.subw], + ]) { + final subtract = + operation == MicroOpAluFunct.sub || + operation == MicroOpAluFunct.subw; + final word = + operation == MicroOpAluFunct.addw || + operation == MicroOpAluFunct.subw; + funct.put(operation); + for (final pair in pairs) { + a.put(pair.$1); + b.put(pair.$2); + var expected = subtract ? pair.$1 - pair.$2 : pair.$1 + pair.$2; + if (word) expected = expected.toSigned(32); + expect( + dut.result.value.toBigInt(), + expected & mask, + reason: 'funct=$operation a=${pair.$1} b=${pair.$2}', + ); + } + } + }); + } +}