Accumulator constructor

Accumulator(
  1. Logic amount, {
  2. required Logic clk,
  3. required Logic reset,
  4. required int width,
  5. Logic? enable,
  6. Logic? clear,
  7. Logic? restart,
  8. dynamic resetValue = 0,
  9. bool saturates = false,
  10. bool asyncReset = false,
  11. String name = 'accumulator',
  12. bool reserveName = false,
  13. bool reserveDefinitionName = false,
  14. String? definitionName,
})

Creates an unsigned increment-only accumulator.

Implementation

Accumulator(
  Logic amount, {
  required Logic clk,
  required Logic reset,
  required this.width,
  Logic? enable,
  Logic? clear,
  Logic? restart,
  dynamic resetValue = 0,
  this.saturates = false,
  this.asyncReset = false,
  super.name = 'accumulator',
  super.reserveName,
  super.reserveDefinitionName,
  String? definitionName,
}) : super(
        definitionName: definitionName ??
            'Accumulator_W${width}_A${amount.width}_'
                'S${saturates ? 1 : 0}_R${restart == null ? 0 : 1}_'
                'C${clear == null ? 0 : 1}_E${enable == null ? 0 : 1}_'
                'A${asyncReset ? 1 : 0}',
      ) {
  if (width <= 0) {
    throw RohdHclException('Accumulator width must be greater than zero.');
  }

  amount = addInput('amount', amount, width: amount.width);
  clk = addInput('clk', clk);
  reset = addInput('reset', reset);
  if (enable != null) {
    enable = addInput('enable', enable);
  }
  if (clear != null) {
    clear = addInput('clear', clear);
  }
  if (restart != null) {
    restart = addInput('restart', restart);
  }

  final resetValueLogic = _makeResetValue(resetValue);
  final value = addOutput('value', width: width);
  final accumulationWidth = max(width, amount.width) + 1;
  final baseValue = mux(
    restart ?? Const(0),
    resetValueLogic,
    value,
  ).zeroExtend(accumulationWidth);
  final enabledAmount = mux(
    enable ?? Const(1),
    amount,
    Const(0, width: amount.width),
  ).zeroExtend(accumulationWidth);
  final wideSum =
      (baseValue + enabledAmount).named('wideSum', naming: Naming.mergeable);
  final nextValue = saturates
      ? mux(
          wideSum.getRange(width).or(),
          Const((BigInt.one << width) - BigInt.one, width: width),
          wideSum.getRange(0, width),
        )
      : wideSum.getRange(0, width);

  Sequential(
    clk,
    reset: reset,
    asyncReset: asyncReset,
    resetValues: {value: resetValueLogic},
    [
      If(clear ?? Const(0), then: [
        value < resetValueLogic,
      ], orElse: [
        If((restart ?? Const(0)) | (enable ?? Const(1)), then: [
          value < nextValue,
        ]),
      ]),
    ],
  );
}