Cache<T extends Logic> constructor

Cache<T extends Logic>({
  1. required Logic clk,
  2. required Logic reset,
  3. required CacheLookupPort<T> lookup,
  4. required CacheFillPort<T> fill,
  5. required int setCount,
  6. required int waysPerSet,
  7. CacheReplacement replacement = CacheReplacement.roundRobin,
  8. CacheDataStorage? dataStorage,
  9. MemoryArrayFunctor<T>? dataMemory,
  10. CacheReadDuringFill readDuringFill = CacheReadDuringFill.oldData,
  11. AssociativeMemoryFunctor tagMemory = parallelAssociativeMemoryFunctor,
  12. String name = 'cache',
})

Creates a cache with an explicit number of sets and ways.

Implementation

Cache({
  required Logic clk,
  required Logic reset,
  required CacheLookupPort<T> lookup,
  required CacheFillPort<T> fill,
  required this.setCount,
  required this.waysPerSet,
  this.replacement = CacheReplacement.roundRobin,
  CacheDataStorage? dataStorage,
  MemoryArrayFunctor<T>? dataMemory,
  this.readDuringFill = CacheReadDuringFill.oldData,
  AssociativeMemoryFunctor tagMemory = parallelAssociativeMemoryFunctor,
  super.name = 'cache',
})  : dataStorage = _resolveDataStorage(dataStorage),
      super(
        definitionName: 'Cache_S${setCount}_W${waysPerSet}_'
            'A${fill.address.width}_${payloadShapeIdentity(fill.data)}_'
            '${replacement.identity}_'
            '${_dataIdentity(dataMemory, dataStorage)}_'
            '${readDuringFill.name}_'
            '${tagMemory.identity}',
      ) {
  if (setCount < 1 || (setCount & (setCount - 1)) != 0) {
    throw ArgumentError.value(setCount, 'setCount', 'Must be a power of 2.');
  }

  if (waysPerSet < 1) {
    throw ArgumentError.value(waysPerSet, 'waysPerSet', 'Must be positive.');
  }
  final setBits = (setCount - 1).bitLength;
  if (fill.address.width < max(1, setBits) ||
      lookup.address.width != fill.address.width) {
    throw ArgumentError(
        'Cache address widths must match and address all sets.');
  }
  if (clk.width != 1 || reset.width != 1) {
    throw ArgumentError('Clock and reset must be bits.');
  }
  if (!sameRohdPayloadShape(fill.data, lookup.data)) {
    throw ArgumentError('Cache port payload shapes must match.');
  }

  final fillAddress = fill.address;
  final fillData = fill.data;
  final localClk = addInput('clk', clk);
  final localReset = addInput('reset', reset);
  final localLookup = addInterfacePorts(lookup,
      inputTags: [PairDirection.fromProvider],
      outputTags: [PairDirection.fromConsumer],
      uniquify: (signal) => 'lookup_$signal');
  final localFill = addInterfacePorts(fill,
      inputTags: [PairDirection.fromProvider],
      outputTags: [PairDirection.fromConsumer],
      uniquify: _cacheFillSignalName);
  final localLookupValid = localLookup.valid;
  final localLookupAddress = localLookup.address;
  final localFillValid = localFill.valid;
  final localFillAddress = localFill.address;
  final localFillData = localFill.data;
  final localEvictionReady = localFill.evictionReady;
  final localLookupReady = localLookup.ready;

  final fillAccepted = Logic(name: 'fill_accepted');
  final lookupHits = <Logic>[];
  final lookupDataBySet = <Logic>[];
  final readyBySet = <Logic>[];
  final evictBySet = <Logic>[];
  final evictAddressBySet = <Logic>[];
  final evictDataBySet = <Logic>[];
  final evictionDemandBySet = <Logic>[];
  final wayWidth = max(1, (waysPerSet - 1).bitLength);

  Logic selects(Logic address, int set) => setBits == 0
      ? Const(1)
      : storedIndexMatches(address.getRange(0, setBits), set);

  for (var set = 0; set < setCount; set++) {
    final lookupSelected = selects(localLookupAddress, set);
    final fillSelected = selects(localFillAddress, set);
    final update = TypedAssociativeUpdatePortInterface(
        Logic(width: fillAddress.width),
        indexWidth: wayWidth);
    final lookup = TypedAssociativeLookupPortInterface(
        Logic(width: fillAddress.width),
        indexWidth: wayWidth);
    final fillLookup = TypedAssociativeLookupPortInterface(
        Logic(width: fillAddress.width),
        indexWidth: wayWidth);
    final sideRead = AssociativeIndexedSideReadRequest(indexWidth: wayWidth);
    final lookupAccess = ReplacementAccessInterface(waysPerSet);
    final fillAccess = ReplacementAccessInterface(waysPerSet);
    final allocation = ReplacementAllocationInterface(waysPerSet);
    final dataWrite = DataPortInterface<T>.typed(localFillData, wayWidth);
    final dataLookup = DataPortInterface<T>.typed(localFillData, wayWidth);
    final dataEviction = DataPortInterface<T>.typed(localFillData, wayWidth);

    lookup.en <= localLookupReady & localLookupValid & lookupSelected;
    lookup.key <= localLookupAddress;
    fillLookup.en <= localFillValid & ~localReset & fillSelected;
    fillLookup.key <= localFillAddress;
    allocation.en <= fillLookup.en & ~fillLookup.hit;
    allocation.commit <= fillAccepted & fillSelected & ~fillLookup.hit;
    lookupAccess.en <= lookup.hit;
    lookupAccess.index <= lookup.index;
    fillAccess.en <= fillLookup.hit;
    fillAccess.index <= fillLookup.index;
    final selectedWay =
        mux(fillLookup.hit, fillLookup.index, allocation.index);
    update.en <= fillAccepted & fillSelected;
    update.index <= selectedWay;
    update.key <= localFillAddress;
    update.entryValid <= Const(1);
    sideRead.index <= allocation.index;

    final binding = tagMemory(
      clk: localClk,
      reset: localReset,
      updatePorts: [update],
      lookupPorts: [lookup, fillLookup],
      entryCount: waysPerSet,
      sideReadRequest: sideRead,
      requiresValidityMask: true,
      lookupLatency: 0,
      duplicateKeyPolicy: AssociativeDuplicateKeyPolicy.allow,
      matchSelection: AssociativeMatchSelection.lowestIndex,
      resultShape: AssociativeResultShape.selectedIndex,
      lookupUpdatePolicy: AssociativeLookupUpdatePolicy.lookupAfterUpdate,
      updateCollisionPolicy: AssociativeUpdateCollisionPolicy.highestPortWins,
      requiredResetBehavior: AssociativeMemoryResetBehavior.clearValidity,
      name: 'tags_$set',
    );
    final tags = binding.memory!;
    final validity = (tags as AssociativeValidityMaskProvider).validMask!;
    final sideResponse =
        (tags as AssociativeIndexedSideReadProvider).sideReadResponse!;
    final eligible =
        Const((BigInt.one << waysPerSet) - BigInt.one, width: waysPerSet);
    final policy = replacement.build(
      clk: localClk,
      reset: localReset,
      validMask: validity,
      eligibleMask: eligible,
      accesses: [lookupAccess, fillAccess],
      allocations: [allocation],
      entryCount: waysPerSet,
      name: 'replacement_$set',
    );
    if (policy.entryCount != waysPerSet) {
      throw StateError('Replacement factory ${replacement.identity} '
          'built a policy with an incompatible entry count.');
    }

    dataWrite.en <= update.en;
    dataWrite.addr <= selectedWay;
    dataWrite.data <= normalizeStoredLogic(localFillData);
    dataLookup.en <= lookup.hit;
    dataLookup.addr <= lookup.index;
    dataEviction.en <= allocation.evict;
    dataEviction.addr <= allocation.index;
    (dataMemory ?? _cacheDataMemory<T>(dataStorage))(
      clk: localClk,
      reset: localReset,
      writePorts: [dataWrite],
      readPorts: [dataLookup, dataEviction],
      entryCount: waysPerSet,
      readLatency: 0,
      maxConcurrentReads: 2,
      maxConcurrentWrites: 1,
      name: 'data_$set',
    );

    lookupHits.add(lookup.hit);
    lookupDataBySet.add(
        mux(lookup.hit, dataLookup.data, Const(0, width: fillData.width)));
    readyBySet.add(fillSelected &
        (fillLookup.hit |
            (allocation.valid & (~allocation.evict | localEvictionReady))));
    evictBySet.add(allocation.evict);
    evictionDemandBySet.add(fillLookup.en & ~fillLookup.hit & validity.and());
    evictAddressBySet.add(mux(allocation.evict, sideResponse.key,
        Const(0, width: fillAddress.width)));
    evictDataBySet.add(mux(allocation.evict, dataEviction.data,
        Const(0, width: fillData.width)));
  }

  Logic combine(List<Logic> values) =>
      values.reduce((left, right) => left | right);
  localLookupReady <= ~localReset & ~combine(evictionDemandBySet);
  localFill.ready <= ~localReset & combine(readyBySet);
  fillAccepted <= localFillValid & localFill.ready;
  final forward = readDuringFill == CacheReadDuringFill.forward
      ? localLookupReady &
          localLookupValid &
          fillAccepted &
          storedAddressMatches(localLookupAddress, localFillAddress)
      : Const(0);
  localLookup.hit <= forward | combine(lookupHits);
  localLookup.data <=
      mux(forward, normalizeStoredLogic(localFillData),
          combine(lookupDataBySet));
  localFill.evictionValid <= combine(evictBySet);
  localFill.evictionAddress <= combine(evictAddressBySet);
  localFill.evictionData <= combine(evictDataBySet);
}