ParallelAssociativeMemoryModel constructor

ParallelAssociativeMemoryModel({
  1. required Logic clk,
  2. required Logic reset,
  3. required int entryCount,
  4. required AssociativeMemoryContract contract,
  5. List<AssociativeUpdatePortInterface>? updatePorts,
  6. List<AssociativeLookupPortInterface>? lookupPorts,
  7. bool enableValidTracking = false,
  8. List<AssociativeIndexedSideReadRequest> sideReadRequests = const [],
  9. String name = 'behavioral_parallel_associative_memory',
  10. @Deprecated('Use updatePorts instead.') List<AssociativeUpdatePortInterface>? updates,
  11. @Deprecated('Use lookupPorts instead.') List<AssociativeLookupPortInterface>? lookups,
})

Creates a simulation-only implementation of the parallel RTL contract.

updates and lookups are deprecated former names of updatePorts and lookupPorts.

Implementation

ParallelAssociativeMemoryModel({
  required super.clk,
  required super.reset,
  required super.entryCount,
  required super.contract,
  super.updatePorts,
  super.lookupPorts,
  this.enableValidTracking = false,
  List<AssociativeIndexedSideReadRequest> sideReadRequests = const [],
  super.name = 'behavioral_parallel_associative_memory',
  @Deprecated('Use updatePorts instead.') super.updates,
  @Deprecated('Use lookupPorts instead.') super.lookups,
})  : _sideReads = List.unmodifiable(sideReadRequests),
      sideReadResponses = List.unmodifiable([
        for (final _ in sideReadRequests)
          // Retain packed responses on the compatibility provider.
          // Preserve compatibility with released model providers.
          // ignore: deprecated_member_use_from_same_package
          AssociativeIndexedSideReadResponse(
              keyWidth: resolveAssociativePortList(
                      lookupPorts, lookups, 'lookupPorts')
                  .first
                  .keyWidth)
      ]),
      super(definitionName: 'BehavioralParallelAssociativeMemory') {
  if (contract.implementationKind !=
          AssociativeMemoryImplementationKind.simulationOnly ||
      contract.lookupLatency != 0 ||
      contract.updateLatency != 0 ||
      contract.duplicateKeyPolicy != AssociativeDuplicateKeyPolicy.allow ||
      contract.lookupUpdatePolicy !=
          AssociativeLookupUpdatePolicy.lookupAfterUpdate ||
      contract.updateCollisionPolicy ==
          AssociativeUpdateCollisionPolicy.disallow ||
      contract.resetBehavior !=
          AssociativeMemoryResetBehavior.clearValidity ||
      contract.resetTiming != AssociativeMemoryResetTiming.synchronous ||
      _sideReads.any((request) => request.index.width != indexWidth)) {
    throw ArgumentError('The behavioral parallel associative memory requires '
        'the parallel RTL contract.');
  }
  _model = AssociativeModel(AssociativeMemoryRequest(
    keyWidth: keyWidth,
    indexWidth: indexWidth,
    entryCount: entryCount,
    updatePortCount: numUpdates,
    lookupPortCount: numLookups,
    lookupLatency: 0,
    duplicateKeyPolicy: contract.duplicateKeyPolicy,
    matchSelection: contract.matchSelection,
    resultShape: contract.resultShape,
    lookupUpdatePolicy: contract.lookupUpdatePolicy,
    updateCollisionPolicy: contract.updateCollisionPolicy,
    requiredResetBehavior: contract.resetBehavior,
  ));
  description = ParallelAssociativeMemoryModelDescription(
    entryCount: entryCount,
    keyWidth: keyWidth,
    indexWidth: indexWidth,
    updateCount: numUpdates,
    matchVectors: [
      for (final lookup in localLookups) lookup.matchVector != null
    ],
    sideReadCount: _sideReads.length,
    trackValidity: enableValidTracking,
    selection: contract.matchSelection,
    collision: contract.updateCollisionPolicy,
  );
  _model._entries = List.generate(
      entryCount,
      (_) => (
            key: LogicValue.filled(keyWidth, LogicValue.x),
            valid: LogicValue.x
          ));

  if (enableValidTracking) {
    addOutput('valid_count', width: (entryCount + 1).log2Ceil);
    addOutput('full');
    addOutput('empty');
    addOutput('valid_mask', width: entryCount);
  }
  for (final (port, request) in _sideReads.indexed) {
    final suffix = port == 0 ? '' : '_$port';
    _sideIndices.add(
        addInput('side_read_index$suffix', request.index, width: indexWidth));
    final key = addOutput('side_read_key$suffix', width: keyWidth);
    final valid = addOutput('side_read_valid$suffix');
    sideReadResponses[port].key <= key;
    sideReadResponses[port].entryValid <= valid;
  }

  void refreshLookup(AssociativeLookupPortInterface lookup) {
    final entries = _model._entries;
    final result = _model._lookup(
        AssociativeModelLookup(key: lookup.key.value), entries);
    final enabledHit = lookup.en.value & result.hit;
    lookup.hit.put(enabledHit);
    lookup.index.put(selectLogicValue(enabledHit, result.index,
        LogicValue.filled(indexWidth, LogicValue.zero)));
    lookup.matchVector?.put(selectLogicValue(lookup.en.value,
        result.matchVector, LogicValue.filled(entryCount, LogicValue.zero)));
  }

  void refreshSide(int port) {
    final value = _sideIndices[port].value;
    final AssociativeModelEntry entry;
    if (!value.isValid) {
      entry = (
        key: LogicValue.filled(keyWidth, LogicValue.x),
        valid: LogicValue.x
      );
    } else if (value.toBigInt() >= BigInt.from(entryCount)) {
      entry = _model._emptyEntry();
    } else {
      entry = _model._readEntry(value.toInt());
    }
    final suffix = port == 0 ? '' : '_$port';
    output('side_read_key$suffix').put(entry.key);
    output('side_read_valid$suffix').put(entry.valid);
  }

  void refresh() {
    final entries = _model._entries;
    if (enableValidTracking) {
      final mask = LogicValue.of([for (final entry in entries) entry.valid]);
      final width = (entryCount + 1).log2Ceil;
      var count = LogicValue.filled(width, LogicValue.zero);
      for (final entry in entries) {
        count += entry.valid.zeroExtend(width);
      }
      validCount!.put(count);
      full!.put(mask.and());
      empty!.put(~mask.or());
      validMask!.put(mask);
    }
    localLookups.forEach(refreshLookup);
    for (var port = 0; port < _sideIndices.length; port++) {
      refreshSide(port);
    }
  }

  _refresh = refresh;
  for (final lookup in localLookups) {
    lookup.en.glitch.listen((_) => refreshLookup(lookup));
    lookup.key.glitch.listen((_) => refreshLookup(lookup));
  }
  for (final (port, index) in _sideIndices.indexed) {
    index.glitch.listen((_) => refreshSide(port));
  }
  clk.changed.listen((event) {
    if (!event.previousValue.isValid || !event.newValue.isValid) {
      _model._entries = List.generate(
          entryCount,
          (_) => (
                key: LogicValue.filled(keyWidth, LogicValue.x),
                valid: LogicValue.x
              ));
      refresh();
      return;
    }
    if (event.previousValue != LogicValue.zero ||
        event.newValue != LogicValue.one) {
      return;
    }
    final resetValue = reset.previousValue!;
    final entries = _model._entries;
    if (resetValue == LogicValue.one) {
      _resetSeen = true;
      _model._entries =
          List.generate(entryCount, (_) => _model._emptyEntry());
    } else if (resetValue != LogicValue.zero) {
      _model._entries = List.generate(
          entryCount,
          (_) => (
                key: LogicValue.filled(keyWidth, LogicValue.x),
                valid: LogicValue.x
              ));
    } else {
      final ordered = contract.updateCollisionPolicy ==
              AssociativeUpdateCollisionPolicy.lowestPortWins
          ? localUpdates.reversed
          : localUpdates;
      for (var index = 0; index < entryCount; index++) {
        for (final update in ordered) {
          final select = update.en.previousValue! &
              storedValueIndexMatches(update.index.previousValue!, index);
          if (select == LogicValue.one) {
            entries[index] = (
              key: normalizeStoredValue(update.key.previousValue!),
              valid: normalizeStoredValue(update.entryValid.previousValue!)
            );
          } else if (select != LogicValue.zero) {
            entries[index] = (
              key: LogicValue.filled(keyWidth, LogicValue.x),
              valid: LogicValue.x
            );
          }
        }
      }
      _model._entries = entries;
    }
    refresh();
  });
  Simulator.injectAction(refresh);
}