RewindableOrderWindow<LogicType extends Logic> constructor

RewindableOrderWindow<LogicType extends Logic>({
  1. required Logic clk,
  2. required Logic reset,
  3. required Logic flush,
  4. required Logic enqueue,
  5. required CompactedLanes<LogicType> enqueueData,
  6. required Logic retire,
  7. required Logic retireCount,
  8. required Logic rewind,
  9. required OrderedTag rewindCheckpoint,
  10. required int capacity,
  11. int? sequenceWidth,
  12. bool allowRetireWithRewind = false,
  13. RegisterFileFunctor? storageImplementation,
  14. String name = 'rewindable_order_window',
})

Creates a rewindable program-order ring driven by explicit actions.

Implementation

RewindableOrderWindow(
    {required Logic clk,
    required Logic reset,
    required Logic flush,
    required Logic enqueue,
    required CompactedLanes<LogicType> enqueueData,
    required Logic retire,
    required Logic retireCount,
    required Logic rewind,
    required OrderedTag rewindCheckpoint,
    required this.capacity,
    int? sequenceWidth,
    this.allowRetireWithRewind = false,
    RegisterFileFunctor? storageImplementation,
    super.name = 'rewindable_order_window'})
    : laneCount = enqueueData.laneCount,
      indexWidth = max(1, capacity.log2Ceil),
      sequenceWidth = sequenceWidth ?? max(2, capacity.log2Ceil + 2),
      super(
          definitionName: 'RewindableOrderWindow_'
              'C${capacity}_L${enqueueData.laneCount}_'
              'S${sequenceWidth ?? max(2, capacity.log2Ceil + 2)}_'
              'RWRT${allowRetireWithRewind ? 1 : 0}_'
              'R${retireCount.width}_'
              '${payloadShapeIdentity(enqueueData)}'
              '${storageImplementation == null ? '' : '_'}'
              '${storageImplementation?.identity ?? ''}') {
  if (capacity < 1 || laneCount < 1 || laneCount > capacity) {
    throw ArgumentError(
        'Capacity and lane count must be positive, with lanes at most '
        'capacity.');
  }
  if (!rohdPayloadsCompatible(enqueueData.lanes.arrayElements,
      ignoreConstantNames: true)) {
    throw ArgumentError('Enqueue lane payloads must be compatible.');
  }
  if (this.sequenceWidth < 2 || capacity >= (1 << (this.sequenceWidth - 1))) {
    throw ArgumentError(
        'Capacity must fit in less than half the sequence space.');
  }
  final countWidth = max(1, (capacity + 1).log2Ceil);
  if (retireCount.width < countWidth ||
      rewindCheckpoint.tagWidth != indexWidth ||
      rewindCheckpoint.ageWidth != this.sequenceWidth) {
    throw ArgumentError(
        'Retirement counts and rewind checkpoints must represent the '
        'configured window.');
  }
  final localClk = addInput('clk', clk);
  final localReset = addInput('reset', reset);
  final localFlush = addInput('flush', flush);
  final localEnqueue = addInput('enqueue', enqueue);
  final localEnqueueData = addTypedInput('enqueueData', enqueueData);
  final localRetire = addInput('retire', retire);
  final localRetireCount =
      addInput('retireCount', retireCount, width: retireCount.width);
  final localRewind = addInput('rewind', rewind);
  final localRewindCheckpoint =
      addTypedInput('rewindCheckpoint', rewindCheckpoint);

  final stored = [
    for (var index = 0; index < capacity; index++)
      localEnqueueData.lanes.arrayElements.first
          .cloneTyped(name: '${name}_entry_$index')
  ];
  final headPointer = Logic(name: '${name}_head', width: indexWidth);
  final tailPointer = Logic(name: '${name}_tail', width: indexWidth);
  final headSequence =
      Logic(name: '${name}_head_sequence', width: this.sequenceWidth);
  final tailSequence =
      Logic(name: '${name}_tail_sequence', width: this.sequenceWidth);
  final occupancyRegister =
      Logic(name: '${name}_occupancy', width: countWidth);

  Logic pointerAtOffset(Logic pointer, int offset, String signalName) {
    Logic selected = Const(offset % capacity, width: indexWidth);
    for (var base = capacity - 1; base >= 0; base--) {
      selected = mux(pointer.eq(base),
          Const((base + offset) % capacity, width: indexWidth), selected);
    }
    return selected.named(signalName);
  }

  Logic pointerAfterCount(
      Logic pointer, Logic count, int maximum, String signalName) {
    var selected = pointer;
    for (var offset = maximum; offset >= 0; offset--) {
      selected = mux(
          count.eq(offset),
          pointerAtOffset(pointer, offset, '${signalName}_offset_$offset'),
          selected);
    }
    return selected.named(signalName);
  }

  final arithmeticWidth = countWidth + 1;
  final currentOccupancy = occupancyRegister.zeroExtend(arithmeticWidth);
  final zeroCount = Const(0, width: arithmeticWidth);
  // Validate full-width requests before using their low bits for arithmetic.
  Logic resizeCount(Logic count, int width) => count.width > width
      ? count.getRange(0, width)
      : count.zeroExtend(width);
  final inputCount = localEnqueueData.validCount;
  final fitsLaneCount = inputCount.lte(laneCount);
  final inputCountValid = inputCount.neq(0) & fitsLaneCount;
  final boundedInputCount = resizeCount(inputCount, arithmeticWidth);
  final proposedInputCount =
      mux(localEnqueue & inputCountValid, boundedInputCount, zeroCount)
          .named('${name}_proposed_input_count');

  final retireComparisonWidth = max(arithmeticWidth, localRetireCount.width);
  final retireWithinOccupancy =
      localRetireCount.zeroExtend(retireComparisonWidth).lte(
            currentOccupancy.zeroExtend(retireComparisonWidth),
          );
  final retireCountValid = localRetireCount.neq(0) & retireWithinOccupancy;
  final effectiveRetireCount = mux(
          localRetireCount.eq(0),
          zeroCount,
          mux(
              retireWithinOccupancy,
              resizeCount(localRetireCount, arithmeticWidth),
              currentOccupancy))
      .named('${name}_effective_retire_count');

  final normalTraffic = ~localFlush & ~localRewind;
  addOutput('canRetire') <=
      (allowRetireWithRewind ? ~localFlush : normalTraffic);
  final acceptedRetire = localRetire & canRetire;
  final acceptedRetireCount =
      mux(acceptedRetire, effectiveRetireCount, zeroCount)
          .named('${name}_accepted_retire_count');
  final occupancyAfterRetire = currentOccupancy - acceptedRetireCount;
  final availableAfterRetire =
      Const(capacity, width: arithmeticWidth) - occupancyAfterRetire;
  final requiredSlots = mux(fitsLaneCount, boundedInputCount,
      Const(laneCount, width: arithmeticWidth));
  addOutput('canEnqueue') <=
      normalTraffic & availableAfterRetire.gte(requiredSlots);
  final acceptedEnqueue = localEnqueue & canEnqueue;
  final acceptedInputCount =
      mux(acceptedEnqueue & inputCountValid, boundedInputCount, zeroCount)
          .named('${name}_accepted_input_count');

  final rewindDistance = (localRewindCheckpoint.age - headSequence)
      .named('${name}_rewind_distance');
  final rewindComparisonWidth = max(this.sequenceWidth, arithmeticWidth);
  final rewindWithinLive = rewindDistance
      .zeroExtend(rewindComparisonWidth)
      .lte(currentOccupancy.zeroExtend(rewindComparisonWidth));
  final expectedRewindPointer = pointerAfterCount(headPointer, rewindDistance,
      capacity, '${name}_expected_rewind_pointer');
  final rewindPointerMatches =
      localRewindCheckpoint.tag.eq(expectedRewindPointer);
  final checkpointMatches = rewindWithinLive & rewindPointerMatches;
  final rewindValid = allowRetireWithRewind
      ? checkpointMatches &
          rewindDistance.zeroExtend(rewindComparisonWidth).gte(
                acceptedRetireCount.zeroExtend(rewindComparisonWidth),
              )
      : checkpointMatches;
  addOutput('canRewind') <= ~localFlush;
  final acceptedRewind = localRewind & canRewind;

  headWindow = addTypedPayloadOutput(this, 'headWindow', localEnqueueData);
  final offeredCount = mux(currentOccupancy.lte(laneCount), currentOccupancy,
      Const(laneCount, width: arithmeticWidth));
  headWindow.validCount <= resizeCount(offeredCount, headWindow.countWidth);
  Logic consumedMask = Const(0, width: laneCount);
  for (var lane = 0; lane < laneCount; lane++) {
    final laneValid = offeredCount.gt(lane);
    consumedMask = consumedMask | (laneValid.zeroExtend(laneCount) << lane);
    Logic selected = stored.first;
    final lanePointer =
        pointerAtOffset(headPointer, lane, '${name}_head_lane_$lane');
    for (var index = capacity - 1; index >= 0; index--) {
      selected = mux(lanePointer.eq(index), stored[index], selected);
    }
    headWindow.lanes.arrayElements[lane] <= selected;
  }
  headWindow.consumedMask <= consumedMask;

  final tailCheckpointPrototype = OrderedTag(
      tagWidth: indexWidth,
      ageWidth: this.sequenceWidth,
      name: 'tailCheckpoint');
  tailCheckpoint =
      addTypedOutput('tailCheckpoint', tailCheckpointPrototype.clone);
  tailCheckpoint.tag <= tailPointer;
  tailCheckpoint.age <= tailSequence;
  tailCheckpointsAfterLanePrefixes = [tailCheckpoint];
  for (var prefix = 1; prefix <= laneCount; prefix++) {
    final checkpointPrototype = OrderedTag(
        tagWidth: indexWidth,
        ageWidth: this.sequenceWidth,
        name: 'tailCheckpointAfterLanePrefix$prefix');
    final checkpoint = addTypedOutput(
        'tailCheckpointAfterLanePrefix$prefix', checkpointPrototype.clone);
    final includedCount = mux(proposedInputCount.lte(prefix),
        proposedInputCount, Const(prefix, width: arithmeticWidth));
    checkpoint.tag <=
        pointerAfterCount(tailPointer, includedCount, laneCount,
            '${name}_tail_after_prefix_$prefix');
    checkpoint.age <=
        tailSequence + includedCount.zeroExtend(this.sequenceWidth);
    tailCheckpointsAfterLanePrefixes.add(checkpoint);
  }

  addOutput('occupancy', width: countWidth) <= occupancyRegister;
  addOutput('availableCount', width: countWidth) <=
      Const(capacity, width: countWidth) - occupancyRegister;
  addOutput('empty') <= occupancyRegister.eq(0);
  addOutput('full') <= occupancyRegister.eq(capacity);
  addOutput('invalidEnqueueCount') <= acceptedEnqueue & ~inputCountValid;
  addOutput('invalidRetireCount') <= acceptedRetire & ~retireCountValid;
  addOutput('invalidRewind') <= acceptedRewind & ~rewindValid;

  final nextHead = pointerAfterCount(
      headPointer, acceptedRetireCount, capacity, '${name}_next_head');
  final nextTail = pointerAfterCount(
      tailPointer, acceptedInputCount, laneCount, '${name}_next_tail');
  final nextOccupancy = occupancyAfterRetire + acceptedInputCount;
  List<Conditional> dataWrites(List<Logic> target) => [
        for (var lane = 0; lane < laneCount; lane++)
          for (var index = 0; index < capacity; index++)
            If(
                acceptedEnqueue &
                    inputCountValid &
                    inputCount.gt(lane) &
                    pointerAtOffset(tailPointer, lane,
                            '${name}_write_${lane}_pointer')
                        .eq(index),
                then: [
                  target[index] < localEnqueueData.lanes.arrayElements[lane]
                ])
      ];
  Sequential(localClk, reset: localReset, resetValues: {
    headPointer: 0,
    tailPointer: 0,
    headSequence: 0,
    tailSequence: 0,
    occupancyRegister: 0,
    if (storageImplementation == null)
      for (final entry in stored) entry: 0
  }, [
    If(localFlush, then: [
      headPointer < tailPointer,
      headSequence < tailSequence,
      occupancyRegister < 0
    ], orElse: [
      If(acceptedRewind & rewindValid, then: [
        headPointer < nextHead,
        tailPointer < localRewindCheckpoint.tag,
        headSequence <
            headSequence + acceptedRetireCount.zeroExtend(this.sequenceWidth),
        tailSequence < localRewindCheckpoint.age,
        occupancyRegister <
            (rewindDistance -
                    acceptedRetireCount.zeroExtend(rewindDistance.width))
                .getRange(0, countWidth)
      ], orElse: [
        headPointer < nextHead,
        tailPointer < nextTail,
        headSequence <
            headSequence + acceptedRetireCount.zeroExtend(this.sequenceWidth),
        tailSequence <
            tailSequence + acceptedInputCount.zeroExtend(this.sequenceWidth),
        occupancyRegister < nextOccupancy.getRange(0, countWidth),
        if (storageImplementation == null) ...dataWrites(stored)
      ])
    ])
  ]);
  if (storageImplementation != null) {
    final next = [
      for (var index = 0; index < capacity; index++)
        Logic(name: '${name}_next_$index', width: stored[index].width)
    ];
    Combinational([
      for (var index = 0; index < capacity; index++)
        next[index] < stored[index],
      If(localFlush, then: [], orElse: [
        If(acceptedRewind & rewindValid, then: [], orElse: dataWrites(next))
      ]),
    ]);
    connectRegisterFileBank(
      clk: localClk,
      reset: localReset,
      current: stored,
      next: next,
      resetValues: List.filled(
          capacity, LogicValue.filled(stored.first.width, LogicValue.zero)),
      implementation: storageImplementation,
      name: '${name}_storage',
    );
  }
}