generateModelSystemVerilog method

  1. @override
String generateModelSystemVerilog({
  1. required String moduleName,
})
override

Emits a behavioral definition with the requested module name.

Implementation

@override
String generateModelSystemVerilog({required String moduleName}) {
  if (!Sanitizer.isSanitary(moduleName)) {
    throw ArgumentError.value(
        moduleName, 'moduleName', 'Invalid identifier.');
  }
  final d = description;
  final rf = d.registerFile;
  final pessimistic =
      rf?.fourStatePolicy == RegisterFileFourStatePolicy.pessimistic;
  final entryCount = rf?.entryCount ?? d.synchronousEntryCount;
  if (entryCount == null) {
    throw UnsupportedError(
        'Behavioral Verilog requires a finite memory configuration.');
  }
  final count = BigInt.from(entryCount) < (BigInt.one << d.addrWidth)
      ? entryCount
      : (BigInt.one << d.addrWidth).toInt();
  final masked = d.writeMasked.contains(true);
  final maskWidth = masked ? d.dataWidth ~/ 8 : 1;
  String literal(LogicValue value) =>
      "${value.width}'b${MemoryValueCodec.binary(value)}";
  String storedBits(String expression) =>
      pessimistic ? "($expression ^ '0)" : expression;
  String inRange(String address) =>
      "({1'b0,$address} < ${d.addrWidth + 1}'d$count)";
  String mask(int index) => d.writeMasked[index] ? 'wr_mask_$index' : "'1";
  String writeValue(int index, String old) => d.writeMasked[index]
      ? 'apply_mask(write_data_$index,$old,wr_mask_$index)'
      : 'write_data_$index';

  final source = StringBuffer('module $moduleName (\n')
    ..writeln([
      for (final (ports, direction) in [
        (d.inputPorts, 'input'),
        (d.outputPorts, 'output')
      ])
        for (final port in ports.entries)
          '  $direction logic [${port.value - 1}:0] ${port.key}'
    ].join(',\n'))
    ..writeln(');')
    ..writeln('  logic [${d.dataWidth - 1}:0] words [0:${count - 1}];')
    ..writeln("  logic old_clk=1'bx;");
  if (masked) {
    final selectedByte = pessimistic
        ? "bytes[b] === 1'b1 ? value[b*8 +: 8] : "
            "bytes[b] === 1'b0 ? previous[b*8 +: 8] : 'x"
        : 'bytes[b] ? value[b*8 +: 8] : previous[b*8 +: 8]';
    source
      ..writeln('  logic [${d.dataWidth - 1}:0] old_words [0:${count - 1}];')
      ..writeln('''
function automatic [${d.dataWidth - 1}:0] apply_mask(
    input logic [${d.dataWidth - 1}:0] value, previous,
    input logic [${maskWidth - 1}:0] bytes);
  for(integer b=0;b<$maskWidth;b=b+1)
    apply_mask[b*8 +: 8]=$selectedByte;
endfunction
''');
  }
  for (final (name, constraints) in [
    ('write', d.writeEnums),
    ('read', d.readEnums)
  ]) {
    for (final (index, fields) in constraints.indexed) {
      source.writeln('''
function automatic [${d.dataWidth - 1}:0] normalize_${name}_$index(
    input logic [${d.dataWidth - 1}:0] value);
  normalize_${name}_$index=value;
''');
      for (final field in fields) {
        final slice = 'value[${field.offset} +: ${field.width}]';
        final legal = field.encodings
            .map((value) => "$slice === ${field.width}'d$value")
            .join(' || ');
        source.writeln("    if($slice !== ${field.width}'bz && !($legal))\n"
            '      normalize_${name}_$index '
            "[${field.offset} +: ${field.width}]='x;");
      }
      source.writeln('  endfunction');
    }
  }
  for (var index = 0; index < d.writeMasked.length; index++) {
    source.writeln('  wire [${d.dataWidth - 1}:0] write_data_$index= '
        "${storedBits('normalize_write_$index(wr_data_$index)')};");
  }
  if (rf == null) {
    for (var index = 0; index < d.readMasked.length; index++) {
      source.writeln('''
logic [${d.dataWidth - 1}:0] data_pipe_$index [0:${d.readLatency - 1}];
logic valid_pipe_$index [0:${d.readLatency - 1}];
logic [${d.dataWidth - 1}:0] requested_$index;
assign rd_data_$index=normalize_read_$index(data_pipe_$index[${d.readLatency - 1}]);
assign rd_valid_$index=valid_pipe_$index[${d.readLatency - 1}];
''');
    }
    source.writeln('''
function automatic [${d.dataWidth - 1}:0] read_word(
    input logic en, input logic [${d.addrWidth - 1}:0] address);
  if(en === 1'b0) read_word='0;
  else if(en !== 1'b1 || \$isunknown(address)) read_word='x;
  else if(!${inRange('address')}) read_word='0;
  else read_word=words[address];
endfunction
''');
  }
  source.writeln('''
task automatic apply_write(input integer index, input logic selected,
    input logic [${d.dataWidth - 1}:0] incoming,
    input logic [${maskWidth - 1}:0] bytes, input bit masked);
  logic [${d.dataWidth - 1}:0] value;
  begin
    if(selected !== 1'b0) begin
      value=selected === 1'b1 ? incoming : 'x;
      ${masked ? '''
      if(masked${rf == null ? " && selected === 1'b1" : ''})
        value=apply_mask(value,old_words[index],bytes);
''' : ''}
      words[index]=value;
    end
  end
endtask
initial begin
  old_clk=clk;
  for(integer i=0;i<$count;i=i+1) words[i]='${pessimistic ? 'x' : 'z'};
''');
  final initialValues = rf?.initialValues;
  if (initialValues != null) {
    for (var index = 0; index < count; index++) {
      source.writeln(
          '    words[$index]=${storedBits(literal(initialValues[index]))};');
    }
  }
  if (rf == null) {
    for (var index = 0; index < d.readMasked.length; index++) {
      source.writeln('''
  for(integer stage=0;stage<${d.readLatency};stage=stage+1) begin
    data_pipe_$index[stage]='z; valid_pipe_$index[stage]=1'bz;
  end
''');
    }
  }
  source.writeln('  end\n  always @(clk) begin');
  if (rf == null) {
    source.writeln('''
  if(\$isunknown(old_clk) || \$isunknown(clk)) begin
    for(integer i=0;i<$count;i=i+1) words[i]='x;
''');
    for (var index = 0; index < d.readMasked.length; index++) {
      source.writeln('''
    for(integer stage=0;stage<${d.readLatency};stage=stage+1) begin
      data_pipe_$index[stage]='x; valid_pipe_$index[stage]=1'bx;
    end
''');
    }
    source.writeln('    end else');
  }
  source.writeln("    if(old_clk === 1'b0 && clk === 1'b1) begin\n"
      "      if(reset !== 1'b0) begin");
  if (rf == null) {
    if (d.resetPolicy == MemoryModelResetPolicy.clear) {
      source.writeln('        for(integer i=0;i<$count;i=i+1)\n'
          "          words[i]=reset === 1'b1 ? '0 : 'x;");
    } else {
      source.writeln("        if(reset !== 1'b1)\n"
          "          for(integer i=0;i<$count;i=i+1) words[i]='x;");
    }
    for (var index = 0; index < d.readMasked.length; index++) {
      source.writeln('''
      for(integer stage=0;stage<${d.readLatency};stage=stage+1) begin
        data_pipe_$index[stage]=reset === 1'b1 ? '0 : 'x;
        valid_pipe_$index[stage]=reset === 1'b1 ? 1'b0 : 1'bx;
      end
''');
    }
  } else {
    if (d.resetPolicy == MemoryModelResetPolicy.clear) {
      final common = rf.resetValues.first;
      source.writeln('        for(integer i=0;i<$count;i=i+1)\n'
          "          words[i]=reset === 1'b1 ? "
          "${storedBits(literal(common))} : 'x;");
      for (var index = 0; index < count; index++) {
        final dynamic =
            d.dynamicResetValues.isNotEmpty && d.dynamicResetValues[index];
        if (dynamic || rf.resetValues[index] != common) {
          final value =
              dynamic ? 'resetValue_$index' : literal(rf.resetValues[index]);
          source.writeln('        words[$index]= '
              "reset === 1'b1 ? ${storedBits(value)} : 'x;");
        }
      }
    } else {
      source.writeln("        if(reset !== 1'b1)\n"
          "          for(integer i=0;i<$count;i=i+1) words[i]='x;");
    }
  }
  source.writeln('      end else begin');
  if (masked) {
    source.writeln('        for(integer i=0;i<$count;i=i+1) '
        'old_words[i]=words[i];');
  }
  void sampleReads() {
    for (var index = 0; index < d.readMasked.length; index++) {
      source.writeln('        requested_$index= '
          'read_word(rd_en_$index,rd_addr_$index);');
    }
  }

  if (rf == null && d.readBeforeWrites) {
    sampleReads();
  }
  for (var index = 0; index < d.writeMasked.length; index++) {
    final write = '''
      if(wr_en_$index !== 1'b0) begin
        if(\$isunknown(wr_addr_$index)) begin
          for(integer i=0;i<$count;i=i+1)
            apply_write(i,wr_en_$index & ${rf == null ? "1'bx" : "(wr_addr_$index == ${d.addrWidth}'(i))"},
                write_data_$index,${mask(index)},${d.writeMasked[index] ? 1 : 0});
        end else if(${inRange('wr_addr_$index')})
          apply_write(wr_addr_$index,wr_en_$index,
              write_data_$index,${mask(index)},${d.writeMasked[index] ? 1 : 0});
      end
''';
    if (d.invalidWritePolicy ==
        MemoryStorageInvalidWritePolicy.setAffectedBitsToX) {
      source.write(write);
    } else {
      final maskActive =
          d.writeMasked[index] ? "wr_mask_$index !== '0" : "1'b1";
      final unknownMask =
          d.writeMasked[index] ? '\$isunknown(wr_mask_$index)' : "1'b0";
      final invalid = '\$isunknown(wr_en_$index) || '
          '\$isunknown(wr_addr_$index) || $unknownMask';
      source.writeln('''
      if(wr_en_$index !== 1'b0 && $maskActive) begin
        if($invalid) begin
          ${d.invalidWritePolicy == MemoryStorageInvalidWritePolicy.clearAll ? "for(integer i=0;i<$count;i=i+1) words[i]='x;" : ''}
        end else begin
          if(${inRange('wr_addr_$index')})
            apply_write(wr_addr_$index,wr_en_$index,
                write_data_$index,${mask(index)},${d.writeMasked[index] ? 1 : 0});
        end
      end
''');
    }
  }
  if (rf == null) {
    if (!d.readBeforeWrites) {
      sampleReads();
    }
    for (var index = 0; index < d.readMasked.length; index++) {
      source.writeln('''
      for(integer stage=${d.readLatency - 1};stage>0;stage=stage-1) begin
        data_pipe_$index[stage]=data_pipe_$index[stage-1];
        valid_pipe_$index[stage]=valid_pipe_$index[stage-1];
      end
      data_pipe_$index[0]=requested_$index;
      valid_pipe_$index[0]=rd_en_$index;
''');
    }
  }
  source.writeln('      end\n    end\n    old_clk=clk;\n  end');
  if (rf != null) {
    for (var index = 0; index < d.readMasked.length; index++) {
      source.writeln('''
logic [${d.dataWidth - 1}:0] stored_$index, result_$index;
always @* begin
  stored_$index='0;
  for(integer i=$count-1;i>=0;i=i-1)
    stored_$index=(rd_addr_$index == ${d.addrWidth}'(i)) ? words[i] : stored_$index;
  result_$index=stored_$index;
''');
      if (rf.readUnderWrite == RegisterFileReadUnderWrite.writeFirst) {
        for (var write = 0; write < d.writeMasked.length; write++) {
          final maskGuard = '& !\$isunknown(wr_mask_$write) ';
          final invalidWriteGuard = d.invalidWritePolicy ==
                  MemoryStorageInvalidWritePolicy.setAffectedBitsToX
              ? ''
              : ' & !\$isunknown(wr_en_$write) '
                  '& !\$isunknown(wr_addr_$write) '
                  '${d.writeMasked[write] ? maskGuard : ''}';
          source.writeln('    result_$index=(~reset$invalidWriteGuard & '
              'wr_en_$write & '
              '(wr_addr_$write == rd_addr_$index) & '
              "${inRange('rd_addr_$index')}) ? "
              '${writeValue(write, 'stored_$index')} : result_$index;');
        }
      }
      final readData = pessimistic
          ? "rd_en_$index === 1'b0 ? '0 : "
              "(rd_en_$index !== 1'b1 || \$isunknown(rd_addr_$index)) "
              "? 'x : result_$index"
          : "rd_en_$index ? result_$index : '0";
      source.writeln(
          '    rd_data_$index=normalize_read_$index($readData);\n  end');
    }
  }
  source.writeln('endmodule');
  return source.toString();
}